Search is not available for this dataset
content
stringlengths
60
399M
max_stars_repo_name
stringlengths
6
110
<|start_filename|>src/Event.hs<|end_filename|> {-# LANGUAGE NoImplicitPrelude, CPP #-} module Event ( Event, evtRead, evtWrite ) where #if MIN_VERSION_base(4,4,0) import GHC.Event ( Event, evtRead, evtWrite ) #else import System.Event ( Event, evtRead, evtWrite ) #endif <|start_filename|>src/System/USB/Descriptors.hs<|end_filename|> {-# LANGUAGE CPP #-} #if __GLASGOW_HASKELL__ >= 704 {-# LANGUAGE Trustworthy #-} #endif -------------------------------------------------------------------------------- -- | -- Module : System.USB.Descriptors -- Copyright : (c) 2009–2017 <NAME> -- License : BSD3 (see the file LICENSE) -- Maintainer : <NAME> <<EMAIL>> -- -- USB devices report their attributes using descriptors. A descriptor is a data -- structure with a defined format. Using descriptors allows concise storage of -- the attributes of individual configurations because each configuration may -- reuse descriptors or portions of descriptors from other configurations that -- have the same characteristics. In this manner, the descriptors resemble -- individual data records in a relational database. -- -- Where appropriate, descriptors contain references to string descriptors -- ('StrIx') that provide textual information describing a descriptor in -- human-readable form. Note that the inclusion of string descriptors is -- optional. -- -------------------------------------------------------------------------------- module System.USB.Descriptors ( -- * Device descriptor getDeviceDesc , DeviceDesc(..) , ReleaseNumber -- | For a database of USB vendors and products see the @usb-id-database@ -- package at: <http://hackage.haskell.org/package/usb-id-database> , VendorId, ProductId -- * Configuration descriptor , getConfigDesc , ConfigDesc(..) -- *** Configuration attributes , ConfigAttribs , DeviceStatus(..) -- * Interface descriptor , Interface , InterfaceDesc(..) -- * Endpoint descriptor , EndpointDesc(..) -- *** Endpoint address , EndpointAddress(..) , TransferDirection(..) -- *** Endpoint attributes , EndpointAttribs , TransferType(..) -- **** Isochronous transfer attributes , Synchronization(..) , Usage(..) -- *** Endpoint max packet size , MaxPacketSize(..) , TransactionOpportunities(..) , maxIsoPacketSize -- * String descriptors , getLanguages , LangId, PrimaryLangId, SubLangId , StrIx , getStrDesc , getStrDescFirstLang ) where import System.USB.Base <|start_filename|>src/SystemEventManager.hs<|end_filename|> {-# LANGUAGE CPP, NoImplicitPrelude #-} #if MIN_VERSION_base(4,4,0) module SystemEventManager ( getSystemEventManager ) where import GHC.Event ( getSystemEventManager ) #else {-# LANGUAGE UnicodeSyntax, ForeignFunctionInterface #-} module SystemEventManager ( getSystemEventManager ) where -- from base: import Data.Function ( ($) ) import Data.IORef ( IORef, newIORef, readIORef ) import Data.Maybe ( Maybe(Nothing) ) import Foreign.Ptr ( Ptr ) import GHC.Conc.Sync ( sharedCAF ) import System.Event ( EventManager ) import System.IO ( IO ) import System.IO.Unsafe ( unsafePerformIO ) getSystemEventManager ∷ IO (Maybe EventManager) getSystemEventManager = readIORef eventManager eventManager ∷ IORef (Maybe EventManager) eventManager = unsafePerformIO $ do em ← newIORef Nothing sharedCAF em getOrSetSystemEventThreadEventManagerStore {-# NOINLINE eventManager #-} foreign import ccall unsafe "getOrSetSystemEventThreadEventManagerStore" getOrSetSystemEventThreadEventManagerStore ∷ Ptr α → IO (Ptr α) #endif <|start_filename|>src/Utils.hs<|end_filename|> {-# LANGUAGE CPP , NoImplicitPrelude , BangPatterns , ScopedTypeVariables #-} module Utils where -------------------------------------------------------------------------------- -- Imports -------------------------------------------------------------------------------- -- from base: import Prelude ( ($) , Num, (+), (*), (-) , Enum, toEnum, fromEnum , Integral, fromIntegral, undefined ) #if __GLASGOW_HASKELL__ < 700 import Prelude ( fromInteger, fail ) #endif import Control.Monad ( Monad, return, (>>=), (>>) ) import Foreign.Ptr ( Ptr ) import Foreign.ForeignPtr ( withForeignPtr ) import Foreign.Storable ( Storable, peek, sizeOf ) import Foreign.Marshal.Alloc ( alloca ) import Foreign.Marshal.Utils ( copyBytes ) import Data.Bool ( Bool, otherwise, (&&) ) import Data.Ord ( Ord, (<=), (>=) ) import Data.Bits ( Bits, shiftL, shiftR, (.&.) ) import Data.Function ( (.) ) import Data.Int ( Int ) import Data.Maybe ( Maybe(Nothing, Just) ) import System.IO ( IO ) import GHC.ForeignPtr ( mallocPlainForeignPtrBytes ) -- from vector: import Data.Vector ( Vector ) import qualified Data.Vector as V ( null, unsafeHead, unsafeTail ) import qualified Data.Vector.Storable as VS ( Vector, empty, null , unsafeFromForeignPtr0 , unsafeToForeignPtr0 ) import qualified Data.Vector.Generic as VG ( Vector, mapM, convert ) -------------------------------------------------------------------------------- -- Utils -------------------------------------------------------------------------------- -- | @bits s e b@ extract bit @s@ to @e@ (including) from @b@. bits :: (Bits a, Num a) => Int -> Int -> a -> a bits s e b = ((1 `shiftL` (e - s + 1)) - 1) .&. (b `shiftR` s) -- | @between n b e@ tests if @n@ is between the given bounds @b@ and @e@ -- (including). between :: Ord a => a -> a -> a -> Bool between n b e = n >= b && n <= e -- | A generalized 'toEnum' that works on any 'Integral' type. genToEnum :: (Integral i, Enum e) => i -> e genToEnum = toEnum . fromIntegral -- | A generalized 'fromEnum' that returns any 'Integral' type. genFromEnum :: (Integral i, Enum e) => e -> i genFromEnum = fromIntegral . fromEnum -- | @mapPeekArray f n a@ applies the monadic function @f@ to each of the @n@ -- elements of the array @a@ and returns the results in a list. mapPeekArray :: (Storable a, VG.Vector v a, VG.Vector v b) => (a -> IO b) -> Int -> Ptr a -> IO (v b) mapPeekArray f n a = peekVector n a >>= VG.mapM f . VG.convert peekVector :: forall a. (Storable a) => Int -> Ptr a -> IO (VS.Vector a) peekVector size ptr | size <= 0 = return VS.empty | otherwise = do let n = (size * sizeOf (undefined :: a)) fp <- mallocPlainForeignPtrBytes n withForeignPtr fp $ \p -> copyBytes p ptr n return $ VS.unsafeFromForeignPtr0 fp size -- | Write the elements of a storable vector to the given array. pokeVector :: forall a. Storable a => Ptr a -> VS.Vector a -> IO () pokeVector ptr v | VS.null v = return () | otherwise = withForeignPtr fp $ \p -> copyBytes ptr p (size * sizeOf (undefined :: a)) where (fp, size) = VS.unsafeToForeignPtr0 v allocaPeek :: Storable a => (Ptr a -> IO ()) -> IO a allocaPeek f = alloca $ \ptr -> f ptr >> peek ptr -- | Monadic if...then...else... ifM :: Monad m => m Bool -> m a -> m a -> m a ifM cM tM eM = cM >>= \c -> if c then tM else eM uncons :: Vector a -> Maybe (a, Vector a) uncons v | V.null v = Nothing | otherwise = Just (V.unsafeHead v, V.unsafeTail v) <|start_filename|>src/System/USB/DeviceHandling.hs<|end_filename|> {-# LANGUAGE CPP #-} #if __GLASGOW_HASKELL__ >= 704 {-# LANGUAGE Trustworthy #-} #endif -------------------------------------------------------------------------------- -- | -- Module : System.USB.Devices -- Copyright : (c) 2009–2017 <NAME> -- License : BSD3 (see the file LICENSE) -- Maintainer : <NAME> <<EMAIL>> -- -- The module provides functionality for opening, closing and configuring USB -- devices. -- -------------------------------------------------------------------------------- module System.USB.DeviceHandling ( -- * Opening & closing devices DeviceHandle , openDevice , closeDevice , withDeviceHandle , getDevice -- * Getting & setting the configuration , ConfigValue , getConfig , setConfig -- * Claiming & releasing interfaces , InterfaceNumber , claimInterface , releaseInterface , withClaimedInterface -- * Setting interface alternate settings , InterfaceAltSetting , setInterfaceAltSetting -- * Clearing & Resetting devices , clearHalt , resetDevice -- * USB kernel drivers , setAutoDetachKernelDriver , kernelDriverActive , detachKernelDriver , attachKernelDriver , withDetachedKernelDriver ) where import System.USB.Base <|start_filename|>src/Poll.hsc<|end_filename|> {-# LANGUAGE NoImplicitPrelude #-} #include <poll.h> module Poll ( toEvent ) where -- from base: import Data.Bits ( (.&.) ) import Data.Bool ( otherwise ) import Data.Eq ( (/=) ) import Data.Monoid ( mempty, mappend ) import Foreign.C.Types ( CShort ) -- from usb: -- I need to import GHC.Event or System.Event based on the version of base. -- However it's currently not possible to use cabal macros in .hsc files. -- See: http://hackage.haskell.org/trac/hackage/ticket/870 -- So I use an intermediate module that makes the choice: import Event ( Event, evtRead, evtWrite ) toEvent :: CShort -> Event toEvent e = remap (#const POLLIN) evtRead `mappend` remap (#const POLLOUT) evtWrite where remap evt to | e .&. evt /= 0 = to | otherwise = mempty
chris-martin/usb
<|start_filename|>public/css/main.css<|end_filename|> html { width: 100%; height: 100%; } body { width: 100%; height: 100%; margin: 0; padding: 0; overflow: hidden; background-color: #666; } #title { position: absolute; left: 0px; right: 0px; top: 0px; bottom: 0px; z-index: 101; color: #ffffff; font-size: 3em; font-family: sans-serif; padding: 40px; -webkit-text-stroke: 1px #666; } #clock { position: absolute; bottom: 30px; right: 30px; color: #ffffff; font-size: 3em; font-family: sans-serif; padding: 20px; -webkit-text-stroke: 1px #666; } <|start_filename|>server.js<|end_filename|> const ssdp = require("peer-ssdp"), peer = ssdp.createPeer(), uuid = require('node-uuid'), myUuid = uuid.v4(), fs = require('fs'), express = require('express'), http = require('http'), app = express(), querystring = require('querystring'), request = require('superagent') logger = require('morgan') bodyParser = require('body-parser') methodOverride = require('method-override'), {exec} = require('child_process') const name = "mMusicCast" const isPi = require('detect-rpi') const WebSocketServer = require('websocket').server; const WebSocketRouter = require('websocket').router; const Apps = require('./apps/apps.js'); app.set('port', 8008); app.use((req, res, next) => { var data = ''; req.setEncoding('utf8'); req.on('data', function(chunk) { data += chunk; }); req.on('end', function() { req.rawBody = data; next(); }); }); app.disable('x-powered-by'); app.use(express.static(__dirname + '/public')); app.use(logger()); app.use(bodyParser()); app.use(methodOverride()); app.use( (req, res, next) => { res.removeHeader("Connection"); next(); }); app.disable('x-powered-by'); var server = http.createServer(app); const spotifyConnect = () => { let cmd = '' if(process.platform === 'darwin') { cmd = './spotify/librespot-darwin' } else if(process.platform === 'linux') { if(isPi()){ cmd = './spotify/librespot-pi' } else { cmd = './spotify/librespot-linux' } } exec(`${cmd} --name ${name}`) //windows not supported } spotifyConnect() server.listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); }); var wsServer = new WebSocketServer({ httpServer: server, autoAcceptConnections: false }); var wssRouter = new WebSocketRouter(); wssRouter.attachServer(wsServer); wsServer.on('request', (request) => { }); wssRouter.mount('/stage','', (request) => { global.stageConnection = request.accept(request.origin); global.stageConnection.send(JSON.stringify({ cmd: "idle" })); }); wssRouter.mount('/system/control','', (request) => { var connection = request.accept(request.origin); console.log("system/control"); }); wssRouter.mount('/connection','', (request) => { var connection = request.accept(request.origin); var name; connection.on('message', (message) => { let cmd = JSON.parse(message.utf8Data); if(cmd.type == "REGISTER") { name = cmd.name; connection.send(JSON.stringify({ type: "CHANNELREQUEST", "senderId": 1, "requestId": 1 })); wssRouter.mount("/receiver/"+cmd.name, '', function(request) { var receiverConnection = request.accept(request.origin); var appName = request.resourceURL.pathname.replace('/receiver/','').replace('Dev',''); Apps.registered[appName].registerReceiver(receiverConnection); }); } else if(cmd.type == "CHANNELRESPONSE") { connection.send(JSON.stringify({ type: "NEWCHANNEL", "senderId": 1, "requestId": 1, "URL": "ws://localhost:8008/receiver/"+name })); } }); }); var regex = new RegExp('^/session/.*$'); wssRouter.mount(regex, '', (request) => { var sessionConn = request.accept(request.origin); console.log("Session up"); var appName = request.resourceURL.pathname.replace('/session/',''); var sessionId = request.resourceURL.search.replace('?',''); var targetApp = Apps.registered[appName]; if(targetApp) { targetApp.registerSession(sessionConn); } }); const getIPAddress = () => { var n = require('os').networkInterfaces(); var ip = [] for (var k in n) { var inter = n[k]; for (var j in inter) { if (inter[j].family === 'IPv4' && !inter[j].internal) { return inter[j].address } } } } const setupApps = (addr) => { Apps.init(fs, app); Apps.registerApp(app, addr, "ChromeCast", "https://www.gstatic.com/cv/receiver.html?$query", ""); Apps.registerApp(app, addr, "YouTube", "https://www.youtube.com/tv?$query", ""); } const setupRoutes = (addr) => { app.get("/ssdp/device-desc.xml", (req, res) => { fs.readFile('./device-desc.xml', 'utf8', function (err,data) { data = data.replace("#uuid#", myUuid).replace("#base#","http://"+req.headers.host).replace("#name#", name); res.type('xml'); res.setHeader("Access-Control-Allow-Method", "GET, POST, DELETE, OPTIONS"); res.setHeader("Access-Control-Expose-Headers", "Location"); res.setHeader("Application-Url", "http://"+req.headers.host+"/apps"); res.send(data); }); }); app.post('/connection/:app', (req, res) => { console.log("Connecting App "+ req.params.app); res.setHeader("Access-Control-Allow-Method", "POST, OPTIONS"); res.setHeader("Access-Control-Allow-Headers", "Content-Type"); res.type("json"); res.send(JSON.stringify({ URL: "ws://"+addr+":8008/session/"+req.params.app+"?1", pingInterval: 3 })) }); app.get('/apps', (req, res) => { for (var key in Apps.registered) { if(Apps.registered[key].config.state == "running") { console.log("Redirecting to"+ key); res.redirect('/apps/'+key); return; } } res.setHeader("Access-Control-Allow-Method", "GET, POST, DELETE, OPTIONS"); res.setHeader("Access-Control-Expose-Headers", "Location"); res.setHeader("Content-Length", "0"); res.setHeader("Content-Type", "text/html; charset=UTF-8"); res.send(204, ""); }); } const setupSSDP = (addr) => { peer.on("ready",function(){ }); peer.on("notify",(headers, address) =>{ }); peer.on("search",(headers, address) =>{ if(headers.ST.indexOf("dial-multiscreen-org:service:dial:1") != -1) { peer.reply({ LOCATION: "http://"+addr+":8008/ssdp/device-desc.xml", ST: "urn:dial-multiscreen-org:service:dial:1", "CONFIGID.UPNP.ORG": 7337, "BOOTID.UPNP.ORG": 7337, USN: "uuid:"+myUuid }, address); } }); peer.start(); } // var addr = getIPAddress(); console.log(addr); setupApps(addr); setupRoutes(addr); setupSSDP(addr);
dothebart/mMusicCast
<|start_filename|>test/distribution_tests.jl<|end_filename|> println("**********Testing Distribution**********") facts("Creating a Distribution") do fv = FeatureVector() c = Cluster() ds = DataSet() d1 = Distribution(fv) d2 = Distribution(c) d3 = Distribution(ds) @fact typeof(d1) => Distribution{FeatureVector} @fact typeof(d2) => Distribution{Cluster} @fact typeof(d3) => Distribution{DataSet} end facts("If sent in with a FeatureVector, d.total is set") do dict1 = ["word" => 4, "another" => 3] fv1 = FeatureVector(dict1) d1 = Distribution(fv1) @fact d1.total => 7 end facts("Get probability of seeing feature in Distribution") do dict1 = ["word" => 4, "another" => 3] fv1 = FeatureVector(dict1) d1 = Distribution(fv1) value = probability(d1,"word") @fact value => 4/7 end facts("Get features of Distribution") do dict1 = ["word" => 4, "another" => 3] fv1 = FeatureVector(dict1) d1 = Distribution(fv1) @fact features(d1) => keys(d1.space) end facts("Check isempty on a Distribution") do d1 = Distribution{FeatureVector}() d2 = Distribution{Cluster}() d3 = Distribution{DataSet}() @fact isempty(d1) => isempty(d1.space) @fact isempty(d2) => isempty(d2.space) @fact isempty(d3) => isempty(d3.space) end facts("entropy(Distribution) returns 0 if empty Distribution") do d1 = Distribution{FeatureVector}() @fact entropy(d1) => 0 end facts("entropy(Distribution) returns entropy of Distribution") do dict1 = ["word" => 4, "another" => 3] fv1 = FeatureVector(dict1) d1 = Distribution(fv1) @fact entropy(d1) => 0.9852281360342515 end facts("entropy of different Distribution types") do fv1 = FeatureVector(["c"=>1,"b"=>1,"a"=>1,"d"=>1]) fv2 = FeatureVector(["f"=>1,"g"=>1,"e"=>1,"h"=>1]) fva = FeatureVector(["1"=>1,"2"=>1,"3"=>1,"4"=>1]) fvb = FeatureVector(["8"=>1,"7"=>1,"6"=>1,"5"=>1]) c1 = Cluster() c2 = Cluster() c1["fv1"] = fv1 c1["fv2"] = fv2 c2["fva"] = fva c2["fvb"] = fvb ds = DataSet() ds["c1"] = c1 ds["c2"] = c2 fv1_dist = Distribution(fv1) fv2_dist = Distribution(fv2) fva_dist = Distribution(fva) fvb_dist = Distribution(fvb) c1_dist = Distribution(c1) c2_dist = Distribution(c2) ds_dist = Distribution(ds) @fact entropy(fv1_dist) => 2 @fact entropy(fv2_dist) => 2 @fact entropy(fva_dist) => 2 @fact entropy(fvb_dist) => 2 @fact entropy(c1_dist) => 3 @fact entropy(c2_dist) => 3 @fact entropy(ds_dist) => 4 end facts("entropy of certain fv or clust") do fv1 = FeatureVector(["c"=>1,"b"=>1,"a"=>1,"d"=>1]) fv2 = FeatureVector(["f"=>1,"g"=>1,"e"=>1,"h"=>1]) fva = FeatureVector(["1"=>1,"2"=>1,"3"=>1,"4"=>1]) fvb = FeatureVector(["8"=>1,"7"=>1,"6"=>1,"5"=>1]) c1 = Cluster() c2 = Cluster() c1["fv1"] = fv1 c1["fv2"] = fv2 c2["fva"] = fva c2["fvb"] = fvb ds = DataSet() ds["c1"] = c1 ds["c2"] = c2 c1_dist = Distribution(c1) c2_dist = Distribution(c2) ds_dist = Distribution(ds) @fact fv_entropy(c1_dist) => 1 @fact fv_entropy(ds_dist) => 2 @fact fv_entropy(ds_dist, "c1") => 1 @fact clust_entropy(ds_dist) => 1 end facts("Testing prob_* functions") do fv1 = FeatureVector(["c"=>1,"b"=>1,"a"=>1,"d"=>1]) fv2 = FeatureVector(["f"=>1,"g"=>1,"e"=>1,"h"=>1]) fva = FeatureVector(["1"=>1,"2"=>1,"3"=>1,"4"=>1]) fvb = FeatureVector(["8"=>1,"7"=>1,"6"=>1,"5"=>1]) c1 = Cluster() c2 = Cluster() c1["fv1"] = fv1 c1["fv2"] = fv2 c2["fva"] = fva c2["fvb"] = fvb ds = DataSet() ds["c1"] = c1 ds["c2"] = c2 c1_dist = Distribution(c1) ds_dist = Distribution(ds) @fact prob_fv(c1_dist, "fv1") => 4/8 @fact prob_fv(ds_dist, "c1", "fv1") => 4/16 @fact prob_cl(ds_dist, "c1") => 8/16 end facts("Testing cond_prob_* functions") do fv1 = FeatureVector(["c"=>1,"b"=>1,"a"=>1,"d"=>1]) fv2 = FeatureVector(["f"=>1,"g"=>1,"e"=>1,"h"=>1]) fva = FeatureVector(["1"=>1,"2"=>1,"3"=>1,"4"=>1]) fvb = FeatureVector(["8"=>1,"7"=>1,"6"=>1,"5"=>1]) c1 = Cluster() c2 = Cluster() c1["fv1"] = fv1 c1["fv2"] = fv2 c2["fva"] = fva c2["fvb"] = fvb ds = DataSet() ds["c1"] = c1 ds["c2"] = c2 c1_dist = Distribution(c1) ds_dist = Distribution(ds) @fact cond_prob_f_given_fv(c1_dist, "fv1", "d") => 1/4 @fact cond_prob_f_given_fv(ds_dist, "c2", "fva", "3") => 1/4 @fact cond_prob_f_given_clust(ds_dist, "c1", "f") => 1/8 @fact cond_prob_fv_given_clust(ds_dist, "c2", "fva") => 4/8 end facts("info_gain(Distribution,Distribution) returns 0 if empty Distributions") do d1 = Distribution{FeatureVector}() d2 = Distribution{FeatureVector}() @fact info_gain(d1,d2) => 0 end facts("ld_info_gain rules out similar features over all decades and outliers that wouldn't tell us much") do fv1 = FeatureVector(["the"=>5, "c1"=>5]) fv2 = FeatureVector(["the"=>5, "c1"=>5, "romeo"=>100]) fv3 = FeatureVector(["the"=>5, "c1"=>5]) fv4 = FeatureVector(["the"=>5, "c1"=>5]) fv5 = FeatureVector(["the"=>5, "c2"=>5]) fv6 = FeatureVector(["the"=>5, "c2"=>5]) fv7 = FeatureVector(["the"=>5, "c2"=>5]) fv8 = FeatureVector(["the"=>5, "c2"=>5]) fv9 = FeatureVector(["the"=>5, "c3"=>5]) fv10 = FeatureVector(["the"=>5, "c3"=>5]) fv11 = FeatureVector(["the"=>5, "c3"=>5]) fv12 = FeatureVector(["the"=>5, "c3"=>5]) fv13 = FeatureVector(["the"=>5, "c4"=>5]) fv14 = FeatureVector(["the"=>5, "c4"=>5]) fv15 = FeatureVector(["the"=>5, "c4"=>5]) fv16 = FeatureVector(["the"=>5, "c4"=>5]) c1 = Cluster() c2 = Cluster() c3 = Cluster() c4 = Cluster() c1["fv1"] = fv1 c1["fv2"] = fv2 c1["fv3"] = fv3 c1["fv4"] = fv4 c2["fv5"] = fv5 c2["fv6"] = fv6 c2["fv7"] = fv7 c2["fv8"] = fv8 c3["fv9"] = fv9 c3["fv10"] = fv10 c3["fv11"] = fv11 c3["fv12"] = fv12 c4["fv13"] = fv13 c4["fv14"] = fv14 c4["fv15"] = fv15 c4["fv16"] = fv16 ds = DataSet() ds["c1"] = c1 ds["c2"] = c2 ds["c3"] = c3 ds["c4"] = c4 d = Distribution(ds) for feature in keys(d.space.vector_sum) if feature == "the" || feature == "romeo" @fact ld_info_gain(d,feature) => 0.0 else @fact ld_info_gain(d,feature) => 1.0 end end end facts("info_gain(Distribution,Distribution) returns info_gain of Distribution") do dict1 = ["word" => 4, "another" => 3] fv1 = FeatureVector(dict1) d1 = Distribution(fv1) dict2 = ["∂" => .1, "happy" => .3] fv2 = FeatureVector(dict2) d2 = Distribution(fv2) @fact info_gain(d1,d2) => 0.17395001157511858 end facts("Smoothing FeatureVector has correct probabilties before and after") do dict1 = ["word" => 7, "another" => 13] fv1 = FeatureVector(dict1) d1 = Distribution(fv1) #no smoothing @fact probability(d1,"word") => (7/20) @fact probability(d1,"another") => (13/20) @fact probability(d1,"unk") => (0/20) #delta smoothing delta_smoothing!(d1) @fact probability(d1,"word") => (8/(3+20)) @fact probability(d1,"another") => (14/(3+20)) @fact probability(d1,"unk") => (1/(3+20)) #good-turing smoothing dict3 = ["the" => 15, "of" => 16, "what" => 1, "a" => 1, "unique" => 1, "word" => 1, "twice" => 2, "two" => 2, "party" => 2, "three" => 3] fv3 = FeatureVector(dict3) d3 = Distribution(fv3) goodturing_smoothing!(d3) @fact probability(d3,"word") => (((1+1)*(3/4))/44) @fact probability(d3,"twice") => (((2+1)*(1/3))/44) @fact probability(d3,"three") => (((3+1)*(0/1))/44) @fact probability(d3,"unk") => (4/44) #removing smoothing remove_smoothing!(d1) @fact probability(d1,"word") => (7/20) @fact probability(d1,"another") => (13/20) @fact probability(d1,"unk") => (0/20) end <|start_filename|>src/TextMining-tester.jl<|end_filename|> module TextMining using ASCIIPlots, LightXML import Base: getindex, setindex!, isempty, keys, values, copy, length, haskey, display, show abstract FeatureSpace include("feature_vector.jl") include("cluster.jl") include("data_set.jl") include("clustering.jl") include("distribution.jl") include("text_processing.jl") include("naive_bayes.jl") include("tree.jl") export #types Cluster, DataSet, Distribution, FeatureSpace, FeatureVector, BinaryTree, BinaryTreeNode, EmptyTree, #functions #naive bayes get_probs_fv_in_clust, split_dataset, separate_by_class, naive_bayes, train_data, percentages, #classification knn, #cluster centroid, distance, dist_centroid, dist_matrix, #clustering random_init, max_min_init, kmeans, elbow_method, hclust, #data set #distribution get_num_texts_in_dist, get_num_texts_given_feature, probability, prob_fv, prob_cl, cond_prob_f_given_fv, cond_prob_f_given_fv, cond_prob_f_given_fv_in_clust, cond_prob_f_given_clust, cond_prob_fv_given_clust, prob_clust_in_dataset, prob_clust_given_feature, features, entropy, fv_entropy, clust_entropy, feature_entropy, clust_in_dataset_entropy, clust_given_feature_entropy, clust_info_gain, ld_info_gain, feature_info_gain, info_gain, perplexity, remove_smoothing!, delta_smoothing!, goodturing_smoothing!, #feature vector sanitize!, freq_list, find_common_type, add!, subtract!, multiply!, divide!, rationalize!, dist_cos, dist_zero, dist_zero_weighted, dist_taxicab, dist_euclidean, dist_infinite, #text processing clean, parse_xml, load_featurevector, load_cluster, load_dataset, get_metadata end <|start_filename|>src/distribution.jl<|end_filename|> type Distribution{FS<:FeatureSpace} space::FS features::Number total::Number smooth::Function smooth_data::Array mdata::Any Distribution() = new(FS(),0,0,_no_smoothing,[]) Distribution(fv::FeatureVector) = new(fv,length(fv),get_total(fv),_no_smoothing,[]) Distribution(c::Cluster) = new(c,length(c.vector_sum),get_total(c.vector_sum) ,_no_smoothing,[]) Distribution(ds::DataSet) = new(ds,length(ds.vector_sum),get_total(ds.vector_sum) ,_no_smoothing,[]) function get_total(fv::FeatureVector) total = 0 for value in values(fv) total += value end return total end end Distribution(fv::FeatureVector) = Distribution{FeatureVector}(fv) Distribution(c::Cluster) = Distribution{Cluster}(c) Distribution(ds::DataSet) = Distribution{DataSet}(ds) function getindex(d::Distribution, key) return d.space[key] end function get_num_texts_in_dist(d::Distribution{DataSet}) texts = 0 for clust in values(d.space.clusters) texts += length(clust) end return texts end function get_num_texts_given_feature(d::Distribution{DataSet}, feature) texts = 0 for clust in values(d.space.clusters) for fv in values(clust.vectors) if haskey(fv,feature) texts += 1 end end end return texts end function probability(d::Distribution, feature) return d.smooth(d, feature, d.smooth_data) end function prob_fv(d::Distribution{Cluster}, key) return d.space[key].total / d.total end function prob_fv(d::Distribution{DataSet}, clust_key, key) return d.space[clust_key][key].total / d.total end function prob_cl(d::Distribution{DataSet}, key) return d.space[key].vector_sum.total / d.total end function cond_prob_f_given_fv(d::Distribution{Cluster}, fv_key, key) return d.space[fv_key][key] / d.space[fv_key].total end function cond_prob_f_given_fv(d::Distribution{DataSet}, clust_key, fv_key, key) return d.space[clust_key][fv_key][key] / d.space[clust_key][fv_key].total end function cond_prob_f_given_fv_in_clust(d::Distribution{DataSet}, clust_key, fv_key, key) return d.space[clust_key][fv_key][key] / d.space[clust_key].vector_sum[key] end function cond_prob_f_given_clust(d::Distribution{DataSet}, clust_key, key) return d.space[clust_key].vector_sum[key] / d.space[clust_key].vector_sum.total end function cond_prob_fv_given_clust(d::Distribution{DataSet}, clust_key, key) return d.space[clust_key][key].total / d.space[clust_key].vector_sum.total end # new scannell stuff function prob_clust_in_dataset(d::Distribution{DataSet}, clust_key) return length(d.space[clust_key].vectors) / get_num_texts_in_dist(d) end function prob_clust_given_feature(d::Distribution{DataSet}, clust_key, feature) num_fvs = 0 prob = 0 for fv in values(d.space.clusters[clust_key]) if haskey(fv,feature) num_fvs += 1 end end prob = num_fvs / get_num_texts_given_feature(d,feature) return prob end # end scannell stuff function keys(d::Distribution) return keys(d.space) end function features(d::Distribution{FeatureVector}) return keys(d.space) end function features(d::Distribution) return keys(d.space.vector_sum) end function isempty(d::Distribution) return isempty(d.space) end function entropy(d::Distribution) ent = 0 for feature in features(d) ent -= probability(d,feature)*log2(probability(d,feature)) end return ent end function fv_entropy(d::Distribution{Cluster}) ent = 0 for fv in keys(d.space) ent -= prob_fv(d,fv)*log2(prob_fv(d,fv)) end return ent end function fv_entropy(d::Distribution{DataSet}) ent = 0 for clust in keys(d.space) for fv in keys(d.space[clust]) ent -= prob_fv(d,clust,fv)*log2(prob_fv(d,clust,fv)) end end return ent end function fv_entropy(d::Distribution{DataSet}, clust_key) ent = 0 for fv in keys(d.space[clust_key]) ent -= prob_fv(d,clust_key,fv)*log2(prob_fv(d,clust_key,fv)) end return ent end function clust_entropy(d::Distribution{DataSet}) ent = 0 for clust in keys(d.space) ent -= prob_cl(d,clust)*log2(prob_cl(d,clust)) end return ent end function feature_entropy(d::Distribution{Cluster},feature) ent = 0 for fv in keys(d.space.vectors) x = cond_prob_f_given_fv(d,fv,feature)*log2(cond_prob_f_given_fv(d,fv,feature)) if isnan(x) x = 0 end ent -= x end return ent end function feature_entropy(d::Distribution{DataSet},feature) ent = 0 for clust in keys(d.space.clusters) x = cond_prob_f_given_clust(d,clust,feature)*log2(cond_prob_f_given_clust(d,clust,feature)) if isnan(x) x = 0 end ent -= x end return ent end # scannell function clust_in_dataset_entropy(d::Distribution{DataSet}) ent = 0 for clust in keys(d.space) x = prob_clust_in_dataset(d,clust)*log2(prob_clust_in_dataset(d,clust)) if isnan(x) x = 0 end ent -= x end return ent end function clust_given_feature_entropy(d::Distribution{DataSet},feature) ent = 0 for clust in keys(d.space) x = prob_clust_given_feature(d,clust,feature)*log2(prob_clust_given_feature(d,clust,feature)) if isnan(x) x = 0 end ent -= x end return ent end function clust_info_gain(d1::Distribution{DataSet}, feature, weight::Bool=false) ent_of_dist = clust_in_dataset_entropy(d1) ent_of_word = clust_given_feature_entropy(d1, feature) if weight return (ent_of_dist - ent_of_word)/ent_of_dist end return ent_of_dist - ent_of_word end function ld_info_gain(d::Distribution{DataSet},feature) all_ig = 0 for clust in keys(d.space.clusters) child_ig = 0 f_in_clust_ent = 0 for fv in keys(d.space[clust].vectors) prob = cond_prob_f_given_fv_in_clust(d,clust,fv,feature) x = (prob*log2(prob)) if isnan(x) x = 0 end f_in_clust_ent -= x end child_ig = clust_in_dataset_entropy(d) - f_in_clust_ent all_ig += (child_ig*prob_clust_given_feature(d,clust,feature)/log2(length(d.space[clust].vectors))) end return (clust_info_gain(d,feature)/log2(length(d.space.clusters))) - all_ig end # end scannell function info_gain(d1::Distribution, d2::Distribution) return entropy(d1)-entropy(d2) end function feature_info_gain(d1::Distribution, word) return entropy(d1)-feature_entropy(d1, word) end function perplexity(d::Distribution) return 2^entropy(d) end function display(dist::Distribution) display(dist.space) end #helper function that sets the smoothing type function set_smooth!(d::Distribution{FeatureVector}, f::Function, sd::Array) d.smooth = f d.smooth_data = sd end #no smoothing default function remove_smoothing!(d::Distribution) set_smooth!(d,_no_smoothing,[]) end function _no_smoothing(d::Distribution{FeatureVector}, key, data::Array) return d.space[key] / d.total end function _no_smoothing(d::Distribution, feature, data::Array) return d.space.vector_sum[feature] / d.total end #add-delta smoothing, defaults to add-one smoothing function delta_smoothing!(d::Distribution, δ::Number=1) if δ <= 0 Base.warn("δ must be greater than 0") end set_smooth!(d,_δ_smoothing,[δ,d.features,d.total]) end function _δ_smoothing(d::Distribution{FeatureVector}, key, data::Array) if !haskey(d.space, key) return (data[1])/(data[1]*(data[2]+1)+data[3]) end return (d.space[key]+data[1])/(data[1]*(data[2]+1)+data[3]) end function _δ_smoothing(d::Distribution, key, data::Array) if !haskey(d.space.vector_sum, key) return (data[1])/(data[1]*(data[2]+1)+data[3]) end return (d.space[key]+data[1])/(data[1]*(data[2]+1)+data[3]) end #simple good-turing smoothing function goodturing_smoothing!(d::Distribution{FeatureVector}) freqs = FeatureVector() for value in values(d.space) freqs[value] += 1 end set_smooth!(d,_gt_smoothing, [d.total, freqs]) end function goodturing_smoothing!(d::Distribution) freqs = FeatureVector() for value in values(d.space.vector_sum) freqs[value] += 1 end set_smooth!(d,_gt_smoothing, [d.total, freqs]) end function _gt_smoothing(d::Distribution{FeatureVector}, key, data::Array) if !haskey(d.space, key) return data[2][1] / data[1] #num of keys that occur once / total number of keys end c = d.space[key] c_adjust = (c+1) * (data[2][c+1]/data[2][c]) return c_adjust / data[1] end function _gt_smoothing(d::Distribution, key, data::Array) if !haskey(d.space.vector_sum, key) return data[2][1] / data[1] #num of keys that occur once / total number of keys end c = d.space.vector_sum[key] c_adjust = (c+1) * (data[2][c+1]/data[2][c]) return c_adjust / data[1] end
ljekersey/TextMining-tester.jl
<|start_filename|>lib/Implementations/init.lua<|end_filename|> return { worldColor = require(script.worldColor), highlightColor = require(script.highlightColor), } <|start_filename|>examples/customGlassRenderImpl.client.lua<|end_filename|> -- myCustomRenderImpl.lua -- (We can pretend this is in it's own module.) -- You can create your own render implementation as well. -- This can be used to tailor the Renderer to your game's specific usecases. local myCustomRenderImpl = (function() -- This is a simple implementation that sets the highlight -- material to Glass as a visual effect. return function() -- Return our render functions. -- Unused functions do not need to be declared. return { onRender = function(_, worldPart, viewportPart, highlight) viewportPart.CFrame = worldPart.CFrame viewportPart.Color = highlight.color viewportPart.Material = Enum.Material.Glass end, } end end)() -- customGlassRenderImpl.client.lua local Players = game:GetService("Players") local ReplicatedStorage = game:GetService("ReplicatedStorage") local RunService = game:GetService("RunService") local Workspace = game:GetService("Workspace") local ObjectHighlighter = require(ReplicatedStorage:FindFirstChild("ObjectHighlighter")) -- This screen gui will contain our ViewportFrames local myScreenGui = Instance.new("ScreenGui") myScreenGui.Name = "ObjectHighlighter" myScreenGui.Parent = Players.LocalPlayer.PlayerGui -- Create a Renderer object with an alternative render implementation. -- `hightlightColor` will override the original model's colors and textures -- with the `color` field provided from `myHighlight`'s state. local myRenderer = ObjectHighlighter.createRenderer(myScreenGui) :withRenderImpl(myCustomRenderImpl) -- Assume we have a Model as a direct child of Workspace local myHighlight = ObjectHighlighter.createFromTarget(Workspace.Model) myHighlight.color = Color3.fromRGB(255, 255, 0) -- Apply our highlight object to our Renderer stack. -- We can add as many highlight objects to a renderer as we need myRenderer:addToStack(myHighlight) RunService.RenderStepped:Connect(function(dt) -- Our renderer will not render until it steps myRenderer:step(dt) end) <|start_filename|>lib/Highlight.lua<|end_filename|> local DEFAULT_PROPS = { target = nil, color = Color3.fromRGB(255, 255, 255), transparency = 0, } local Highlight = {} function Highlight.new(props) assert(type(props) == "table", "Highlight.new expects a table of props.") assert(props.target, "Highlight requires a target to be set!") assert(props.target:IsA("Model"), "Highlight requires target to be a Model!") local state = { target = props.target, color = props.color or DEFAULT_PROPS.color, transparency = props.transparency or DEFAULT_PROPS.transparency, } return setmetatable(state, Highlight) end function Highlight.fromTarget(target) assert(target and target:IsA("Model"), "Highlight.fromTarget requires a Model target to be set!") return Highlight.new({ target = target, }) end return Highlight <|start_filename|>examples/sinwave.client.lua<|end_filename|> -- sinwave.client.lua local Players = game:GetService("Players") local ReplicatedStorage = game:GetService("ReplicatedStorage") local RunService = game:GetService("RunService") local Workspace = game:GetService("Workspace") local ObjectHighlighter = require(ReplicatedStorage:FindFirstChild("ObjectHighlighter")) -- This screen gui will contain our ViewportFrames local myScreenGui = Instance.new("ScreenGui") myScreenGui.Name = "ObjectHighlighter" myScreenGui.Parent = Players.LocalPlayer.PlayerGui -- Create a Renderer object with an alternative render implementation. -- `hightlightColor` will override the original model's colors and textures -- with the `color` field provided from `myHighlight`'s state. local myRenderer = ObjectHighlighter.createRenderer(myScreenGui) :withRenderImpl(ObjectHighlighter.Implementations.highlightColor) -- Assume we have a Model as a direct child of Workspace local myHighlight = ObjectHighlighter.createFromTarget(Workspace.Model) -- Apply our highlight object to our Renderer stack. -- We can add as many highlight objects to a renderer as we need myRenderer:addToStack(myHighlight) RunService.RenderStepped:Connect(function(dt) -- Since our highlight object contains it's own state, -- we have the option to update it before stepping here. myHighlight.color = Color3.new(math.sin(time()), 0, 0) -- Our renderer will not render until it steps myRenderer:step(dt) end) <|start_filename|>rojo.json<|end_filename|> { "name": "rbx-ObjectHighlighter", "servePort": 8000, "partitions": { "lib": { "path": "lib", "target": "ReplicatedStorage.ObjectHighlighter" }, "examples": { "path": "examples", "target": "StarterPlayer.StarterPlayerScripts" } } } <|start_filename|>lib/ObjectRefMap.lua<|end_filename|> local createInstanceCopy = require(script.Parent.createInstanceCopy) local ObjectRefMap = {} function ObjectRefMap.fromModel(model) local newModel = Instance.new("Model") local alreadyHasAHumanoid = false local clonedPrimaryPart local dataModel = {} local map = {} for _, object in ipairs(model:GetDescendants()) do local clone = createInstanceCopy(object) if clone then clone.Parent = newModel if clone:IsA("BasePart") then map[object] = clone if not clonedPrimaryPart and object == model.PrimaryPart then clonedPrimaryPart = clone end elseif object:IsA("Humanoid") then if alreadyHasAHumanoid then clone:Destroy() else alreadyHasAHumanoid = true end end end end newModel.PrimaryPart = clonedPrimaryPart dataModel.map = map dataModel.rbx = newModel dataModel.worldModel = model return dataModel end return ObjectRefMap <|start_filename|>lib/createFromTarget.lua<|end_filename|> local Highlight = require(script.Parent.Highlight) return function(targetModel) return Highlight.fromTarget(targetModel) end <|start_filename|>lib/createRenderer.lua<|end_filename|> local Renderer = require(script.Parent.Renderer) return function(screenGui) return Renderer.new(screenGui) end <|start_filename|>lib/createInstanceCopy/createBasePartCopy.lua<|end_filename|> return function(basePart) assert(basePart:IsA("BasePart"), "createBasePartCopy must only receive a basePart!") local result if basePart:IsA("MeshPart") or basePart:IsA("UnionOperation") then result = basePart:Clone() else -- TODO: Manually clone simple BaseParts result = basePart:Clone() end -- TODO: Consider whitelisting children applicable to rendering instead for _, object in pairs(result:GetDescendants()) do if object:IsA("BasePart") then object:Destroy() end end return result end <|start_filename|>lib/Implementations/highlightColor.lua<|end_filename|> return function() return { onBeforeRender = function(_, _) return true end, onRender = function(_, worldPart, viewportPart, highlight) viewportPart.CFrame = worldPart.CFrame viewportPart.Color = highlight.color end, onAdded = function(_, viewportPart, highlight) local function clearTextures(instance) if instance:IsA("MeshPart") then instance.TextureID = "" elseif instance:IsA("UnionOperation") then instance.UsePartColor = true elseif instance:IsA("SpecialMesh") then instance.TextureId = "" end end local function colorObject(instance) if instance:IsA("BasePart") then instance.Color = highlight.color end end for _, object in pairs(viewportPart:GetDescendants()) do clearTextures(object) colorObject(object) end clearTextures(viewportPart) colorObject(viewportPart) end, } end <|start_filename|>lib/createInstanceCopy/init.lua<|end_filename|> local createBasePartCopy = require(script.createBasePartCopy) return function(instance) if instance:IsA("BasePart") then return createBasePartCopy(instance) elseif instance:IsA("Humanoid") then local humanoid = Instance.new("Humanoid") humanoid:ChangeState(Enum.HumanoidStateType.Physics) humanoid.DisplayDistanceType = Enum.HumanoidDisplayDistanceType.None return humanoid elseif instance:IsA("Shirt") or instance:IsA("Pants") or instance:IsA("CharacterMesh") then return instance:Clone() end end <|start_filename|>lib/Implementations/worldColor.lua<|end_filename|> return function() local connections = {} return { onBeforeRender = function(_, _) return true end, onRender = function(_, worldPart, viewportPart, _) viewportPart.CFrame = worldPart.CFrame end, onAdded = function(worldPart, viewportPart, _) viewportPart.Color = worldPart.Color connections[worldPart] = worldPart:GetPropertyChangedSignal("Color"):Connect(function() viewportPart.Color = worldPart.Color end) end, onRemoved = function(worldPart, _, _) if connections[worldPart] then connections[worldPart]:Disconnect() connections[worldPart] = nil end end, } end <|start_filename|>examples/customObstructionRenderImpl.client.lua<|end_filename|> -- myCustomRenderImpl.lua -- (We can pretend this is in it's own module.) -- You can create your own render implementation as well. -- This can be used to tailor the Renderer to your game's specific usecases. local myCustomRenderImpl = (function() -- This will check for any obstruction between the user's -- Camera and the PrimaryPart of the highlighted model. local Workspace = game:GetService("Workspace") return function() local camera = Workspace.CurrentCamera -- Return our render functions. -- Unused functions do not need to be declared. return { onBeforeRender = function(_, worldModel) -- Assumption: We have a valid PrimaryPart for our highlighted model local worldModelPosition = worldModel.PrimaryPart.Position -- This could be made much tighter in a real scenario. -- The important takeaway here is that you can cast this ray -- using IgnoreLists and rules most appropriate for your project. local myRay = Ray.new(camera.CFrame.p, (worldModelPosition - camera.CFrame.p)) local hit = Workspace:FindPartOnRay(myRay, worldModel) local shouldRender = not not hit -- Returning false will not render the viewports the current frame. return shouldRender end, onRender = function(_, worldPart, viewportPart, _) viewportPart.CFrame = worldPart.CFrame end, } end end)() -- customGlassRenderImpl.client.lua local Players = game:GetService("Players") local ReplicatedStorage = game:GetService("ReplicatedStorage") local RunService = game:GetService("RunService") local Workspace = game:GetService("Workspace") local ObjectHighlighter = require(ReplicatedStorage:FindFirstChild("ObjectHighlighter")) -- This screen gui will contain our ViewportFrames local myScreenGui = Instance.new("ScreenGui") myScreenGui.Name = "ObjectHighlighter" myScreenGui.Parent = Players.LocalPlayer.PlayerGui -- Create a Renderer object with an alternative render implementation. -- `hightlightColor` will override the original model's colors and textures -- with the `color` field provided from `myHighlight`'s state. local myRenderer = ObjectHighlighter.createRenderer(myScreenGui) :withRenderImpl(myCustomRenderImpl) -- Assume we have a Model as a direct child of Workspace local myHighlight = ObjectHighlighter.createFromTarget(Workspace.Model) -- Apply our highlight object to our Renderer stack. -- We can add as many highlight objects to a renderer as we need myRenderer:addToStack(myHighlight) RunService.RenderStepped:Connect(function(dt) -- Our renderer will not render until it steps myRenderer:step(dt) end) <|start_filename|>lib/init.lua<|end_filename|> return { createFromTarget = require(script.createFromTarget), createRenderer = require(script.createRenderer), Implementations = require(script.Implementations), } <|start_filename|>lib/ViewportFrame.lua<|end_filename|> local Workspace = game:GetService("Workspace") local ViewportFrame = {} ViewportFrame.__index = ViewportFrame function ViewportFrame.withReferences(objectRef) local state = { objectRef = objectRef, rbx = nil, } local self = setmetatable(state, ViewportFrame) local rbx = Instance.new("ViewportFrame") rbx.CurrentCamera = Workspace.CurrentCamera rbx.BackgroundTransparency = 1 rbx.Size = UDim2.new(1, 0, 1, 0) self.rbx = rbx objectRef.rbx.Parent = self.rbx return self end function ViewportFrame:getReference() return self.objectRef end function ViewportFrame:requestParent(newParent) return pcall(function() self.rbx.Parent = newParent end) end function ViewportFrame:destruct() self.rbx:Destroy() end return ViewportFrame <|start_filename|>examples/default.client.lua<|end_filename|> -- default.client.lua local Players = game:GetService("Players") local ReplicatedStorage = game:GetService("ReplicatedStorage") local RunService = game:GetService("RunService") local Workspace = game:GetService("Workspace") local ObjectHighlighter = require(ReplicatedStorage:FindFirstChild("ObjectHighlighter")) -- This screen gui will contain our ViewportFrames local myScreenGui = Instance.new("ScreenGui") myScreenGui.Name = "ObjectHighlighter" myScreenGui.Parent = Players.LocalPlayer.PlayerGui local myRenderer = ObjectHighlighter.createRenderer(myScreenGui) -- Assume we have a Model as a direct child of Workspace local myHighlight = ObjectHighlighter.createFromTarget(Workspace.Model) -- Apply our highlight object to our Renderer stack. -- We can add as many highlight objects to a renderer as we need myRenderer:addToStack(myHighlight) RunService.RenderStepped:Connect(function(dt) -- Our renderer will not render until it steps myRenderer:step(dt) end)
Imaginaerume/rbx-ObjectHighlighter
<|start_filename|>Straw/Straw-Bridging-Header.h<|end_filename|> #import "SimServiceContext.h" #import "SimDeviceSet.h" #import "SimDevice.h" #import "SimRuntime.h" <|start_filename|>Straw/CoreSimulatorHeaders/SimRuntime.h<|end_filename|> /* Generated by RuntimeBrowser Image: /Library/Developer/PrivateFrameworks/CoreSimulator.framework/Versions/A/CoreSimulator */ /* And then heavily stripped and annotated by me 🌈 */ #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @interface SimRuntime : NSObject @property (nonatomic, copy) NSString *versionString; @end NS_ASSUME_NONNULL_END <|start_filename|>Straw/CoreSimulatorHeaders/SimDevice.h<|end_filename|> /* Generated by RuntimeBrowser Image: /Library/Developer/PrivateFrameworks/CoreSimulator.framework/Versions/A/CoreSimulator */ /* And then heavily stripped and annotated by me 🌈 */ #import <Foundation/Foundation.h> @class SimRuntime; NS_ASSUME_NONNULL_BEGIN typedef NS_ENUM(NSInteger, SimDeviceState) { SimDeviceStateCreating, SimDeviceStateShutdown, SimDeviceStateBooting, SimDeviceStateBooted, SimDeviceStateShuttingDown }; @interface SimDevice : NSObject @property (nonatomic, copy) NSUUID *UDID; @property (nonatomic, readonly) NSString *name; @property (nonatomic, readonly) SimRuntime *runtime; @property (nonatomic, readonly) SimDeviceState state; - (BOOL)sendPushNotificationForBundleID:(NSString *)bundleID jsonPayload:(NSDictionary *)json error:(NSError **)error; @end NS_ASSUME_NONNULL_END <|start_filename|>Straw/CoreSimulatorHeaders/SimServiceContext.h<|end_filename|> /* Generated by RuntimeBrowser Image: /Library/Developer/PrivateFrameworks/CoreSimulator.framework/Versions/A/CoreSimulator */ /* And then heavily stripped and annotated by me 🌈 */ #import <Foundation/Foundation.h> @class SimDeviceSet; NS_ASSUME_NONNULL_BEGIN @interface SimServiceContext : NSObject + (instancetype)sharedServiceContextForDeveloperDir:(NSString *)developerDirectory error:(NSError **)error; - (SimDeviceSet *)defaultDeviceSetWithError:(NSError **)error; @end NS_ASSUME_NONNULL_END <|start_filename|>Straw/CoreSimulatorHeaders/SimDeviceSet.h<|end_filename|> /* Generated by RuntimeBrowser Image: /Library/Developer/PrivateFrameworks/CoreSimulator.framework/Versions/A/CoreSimulator */ /* And then heavily stripped and annotated by me 🌈 */ #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @class SimDevice; @interface SimDeviceSet : NSObject @property (nonatomic, readonly) NSArray <SimDevice *>*devices; - (unsigned long long)registerNotificationHandler:(void (^_Nonnull)(NSDictionary *))handler; @end NS_ASSUME_NONNULL_END
maxgoedjen/straw
<|start_filename|>src/AssetLoaderContext.cs<|end_filename|> using System; using System.IO; #if !STRIDE using Microsoft.Xna.Framework.Graphics; #else using Stride.Graphics; #endif namespace XNAssets { public class AssetLoaderContext { private readonly AssetManager _assetManager; private readonly string _baseFolder; public GraphicsDevice GraphicsDevice { get { return _assetManager.GraphicsDevice; } } public AssetManagerSettings Settings { get { return _assetManager.Settings; } } internal AssetLoaderContext(AssetManager assetManager, string baseFolder) { _assetManager = assetManager ?? throw new Exception("assetManager"); _baseFolder = baseFolder; } /// <summary> /// Opens a stream specified by asset path /// Throws an exception on failure /// </summary> /// <param name="assetName"></param> /// <returns></returns> public Stream Open(string assetName) { return _assetManager.Open(AssetManager.CombinePath(_baseFolder, assetName)); } /// <summary> /// Reads specified asset to string /// </summary> /// <param name="path"></param> /// <returns></returns> public string ReadAsText(string path) { string result; using (var input = Open(path)) { using (var textReader = new StreamReader(input)) { result = textReader.ReadToEnd(); } } return result; } /// <summary> /// Reads specified asset to string /// </summary> /// <param name="path"></param> /// <returns></returns> public byte[] ReadAsByteArray(string path) { using (var input = Open(path)) using (var ms = new MemoryStream()) { input.CopyTo(ms); return ms.ToArray(); } } public T Load<T>(string assetName) { return _assetManager.Load<T>(AssetManager.CombinePath(_baseFolder, assetName)); } } } <|start_filename|>src/Texture2DLoader.cs<|end_filename|> using XNAssets.Utility; #if !STRIDE using Microsoft.Xna.Framework.Graphics; #else using Texture2D = Stride.Graphics.Texture; #endif namespace XNAssets { internal class Texture2DLoader : IAssetLoader<Texture2D> { public Texture2D Load(AssetLoaderContext context, string assetName) { using (var stream = context.Open(assetName)) { return Texture2DExtensions.FromStream(context.GraphicsDevice, stream, context.Settings.PremultiplyAlphaForTextures); } } } } <|start_filename|>build_all.bat<|end_filename|> dotnet --version dotnet build build\XNAssets.MonoGame.sln /p:Configuration=Release --no-incremental dotnet build build\XNAssets.Stride.sln /p:Configuration=Release --no-incremental <|start_filename|>src/Utility/CrossEngineStuff.cs<|end_filename|> #if !STRIDE using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; #else using Stride.Graphics; using Texture2D = Stride.Graphics.Texture; #endif namespace XNAssets.Utility { internal static class CrossEngineStuff { public static Texture2D CreateTexture2D(GraphicsDevice graphicsDevice, int width, int height, byte[] data) { #if !STRIDE var result = new Texture2D(graphicsDevice, width, height, false, SurfaceFormat.Color); result.SetData(data); return result; #else return Texture2D.New2D(graphicsDevice, width, height, PixelFormat.R8G8B8A8_UNorm_SRgb, data); #endif } } }
rds1983/XNAssets
<|start_filename|>test/ReactBootstrapTimePicker.spec.js<|end_filename|> // We don't need to mutate props as TimePicker is stateless component import React from 'react'; import chai, { expect } from 'chai'; import chaiEnzyme from 'chai-enzyme'; import Enzyme, { shallow, mount, render } from 'enzyme'; import EnzymeAdapter from 'enzyme-adapter-react-16'; import { timeToInt } from 'time-number'; import TimePicker from '../dist/bundle'; Enzyme.configure({ adapter: new EnzymeAdapter() }); chai.use(chaiEnzyme()); describe('className and style props are propagated', () => { it('className: "temp"', () => { const component = render(<TimePicker className="temp" />); expect(component).to.have.attr('class').match(/temp/); }); it('style: {{ zIndex: "-9999" }}', () => { const component = render(<TimePicker style={{ zIndex: '-9999' }} />); expect(component).to.have.attr('style').match(/\-9999/); }); }); describe('initialValue and value', () => { it('initialValue: 3600 => "3600"', () => { const component = render(<TimePicker initialValue={3600} />); expect(component.find('option[selected]')).to.have.attr('value').equal("3600"); }); it('value: 3600 => "3600"', () => { const component = render(<TimePicker value={3600} />); expect(component.find('option[selected]')).to.have.attr('value').equal("3600"); }); it('initialValue: "undefined", value: "04:00" => 3600 * 4', () => { const component = render(<TimePicker value="04:00" />); expect(component.find('option[selected]')).to.have.attr('value').equal((4 * 3600).toString()); }); it('initialValue: "03:00", value: "04:00" => 3600 * 4', () => { const component = render(<TimePicker initialValue="03:00" value="04:00" />); expect(component.find('option[selected]')).to.have.attr('value').equal((4 * 3600).toString()); }); it('initialValue: "03:00", value: 3600 => 3600', () => { const component = render(<TimePicker initialValue="03:00" value={3600} />); expect(component.find('option[selected]')).to.have.attr('value').equal("3600"); }); it('initialValue: "03:00", value: "3600" => 3600', () => { const component = render(<TimePicker initialValue="03:00" value="3600" />); expect(component.find('option[selected]')).to.have.attr('value').equal("3600"); }); it('initialValue: undefined, value: undefined => "00:00"', () => { const component = render(<TimePicker />); expect(component.find('option[selected]')).to.have.attr('value').equal("0"); }); it('initialValue: undefined, value: undefined, min="03:00" => "03:00"', () => { const component = render(<TimePicker start="03:00" />); expect(component.find('option[selected]')).to.have.attr('value').equal((3 * 3600).toString()); }); }); describe('hour format', () => { it('format: 12, "00:00" => "12:00 AM"', () => { const component = render(<TimePicker />); expect(component.find('option[selected]')).to.have.text("12:00 AM"); }); it('format: 12, "01:00" => "01:00 AM"', () => { const component = render(<TimePicker value="01:00" />); expect(component.find('option[selected]')).to.have.text("01:00 AM"); }); it('format: 12, "12:00" => "12:00 PM"', () => { const component = render(<TimePicker value="12:00" />); expect(component.find('option[selected]')).to.have.text("12:00 PM"); }); it('format: 12, "13:00" => "01:00 PM"', () => { const component = render(<TimePicker value="13:00" />); expect(component.find('option[selected]')).to.have.text("01:00 PM"); }); it('format: 24, "00:00" => "00:00"', () => { const component = render(<TimePicker format={24} />); expect(component.find('option[selected]')).to.have.text("00:00"); }); it('format: 24, "01:00" => "01:00"', () => { const component = render(<TimePicker format={24} value="01:00" />); expect(component.find('option[selected]')).to.have.text("01:00"); }); it('format: 24, "13:00" => "13:00"', () => { const component = render(<TimePicker format={24} value="13:00" />); expect(component.find('option[selected]')).to.have.text("13:00"); }); }); describe('onChange', () => { it('onChange is called', () => { let testVal = ''; const onChangeTest = (val) => testVal = 'called'; const component = mount(<TimePicker onChange={onChangeTest} />); component.find('option[value=3600]').simulate('change', '3600'); expect(testVal).to.equal('called'); }); it('onChange changes value properly', () => { let testVal = ''; const onChangeTest = (val) => testVal = val; const component = mount(<TimePicker onChange={onChangeTest} />); component.find('option[value=3600]').simulate('change', '3600'); expect(testVal).to.equal(3600); }); }); describe('start, end and step', () => { it('number of options is equal to (end - start) / step, test 1', () => { const component = render(<TimePicker start="00:00" end="12:00" step={10} />); expect(component.find('option')).to.have.length(1 + Math.floor((timeToInt("12:00") - timeToInt("0:00")) / 600)); }); it('number of options is equal to (end - start) / step, test 2 ', () => { const component = render(<TimePicker start="00:00" end="11:59" step={10} />); expect(component.find('option')).to.have.length(1 + Math.floor((timeToInt("11:59") - timeToInt("0:00")) / 600)); }); it('first element === start', () => { const component = render(<TimePicker start="4" />); expect(component.find('option').first()).to.have.attr('value').equal((4 * 3600).toString()); }); it('last element might be equal end', () => { const component = render(<TimePicker start="3:30" end="04:00" />); expect(component.find('option').last()).to.have.attr('value').equal((4 * 3600).toString()); }); it('last element might be less than end', () => { const component = render(<TimePicker start="03:30:00" end="03:59" />); expect(component.find('option')).to.have.length(1); }); }); <|start_filename|>src/index.js<|end_filename|> import ReactBootstrapTimePicker from './ReactBootstrapTimePicker'; export default ReactBootstrapTimePicker; <|start_filename|>demo/src/index.js<|end_filename|> import React, { Component } from 'react'; import { render } from 'react-dom'; import Button from 'react-bootstrap/lib/Button'; import FormControl from 'react-bootstrap/lib/FormControl'; import { timeToInt } from 'time-number'; import TimePicker from '../../dist/bundle.js'; class App extends Component { constructor() { super(); this.filterState = this.filterState.bind(this); this.handleTimeChange = this.handleTimeChange.bind(this); this.state = { format: 12, initialValue: "00:00", start: "00:00", end: "23:59", step: 30, onChange: this.handleTimeChange, }; } handleTimeChange(value) { this.setState({ value }); } filterState() { const ret = {...this.state}; try { timeToInt(ret.start); } catch(ex) { ret.start = "00:00"; } try { timeToInt(ret.end); } catch(ex) { ret.end = "23:59"; } if (ret.step < 1) { ret.step = 30; } return ret; } render() { return ( <div> <div> <TimePicker {...this.filterState(this.state)} /> </div> <div style={{ marginTop: '40px' }}> <hr /> <h1>Configurable props</h1> <h2>format</h2> <div> <Button children="12" disabled={this.state.format === 12} onClick={() => { this.setState({ format: 12 }); }} style={{ marginRight: '15px' }} /> <Button children="24" disabled={this.state.format === 24} onClick={() => { this.setState({ format: 24 }); }} /> </div> <h2>initialValue</h2> <FormControl value={this.state.initialValue} onChange={(e) => this.setState({ initialValue: e.target.value })} /> <h2>value</h2> <FormControl value={this.state.value} onChange={(e) => this.setState({ value: e.target.value })} /> <h2>start</h2> <FormControl value={this.state.start} onChange={(e) => this.setState({ start: e.target.value })} /> <h2>end</h2> <FormControl value={this.state.end} onChange={(e) => this.setState({ end: e.target.value })} /> <h2>step</h2> <FormControl value={this.state.step} onChange={(e) => this.setState({ step: parseInt(e.target.value, 10) })} /> <hr /> <h2>Reset</h2> <Button onClick={() => { this.setState({ format: 12, initialValue: "00:00", start: "00:00", end: "23:59", step: 30, onChange: this.handleTimeChange, }); }} style={{ display: 'block' }} > Reset to initial state </Button> </div> </div> ); } } render(<App />, document.getElementById('app'));
DEMON-Dev1125/react-bootstrap-time-picker
<|start_filename|>src/GraphicsAPI/GraphicsAPI.cpp<|end_filename|> /* * Copyright (c) 2022 NVIDIA CORPORATION. All rights reserved * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "GraphicsAPI/GraphicsAPI.h" #include <assert.h> #include <cstring> namespace KickstartRT_NativeLayer::GraphicsAPI { #if defined(GRAPHICS_API_VK) /*************************************************************** * Loading vulkan extension function pointers. ***************************************************************/ namespace VK { PFN_vkCreateAccelerationStructureKHR vkCreateAccelerationStructureKHR = {}; PFN_vkDestroyAccelerationStructureKHR vkDestroyAccelerationStructureKHR = {}; PFN_vkGetAccelerationStructureBuildSizesKHR vkGetAccelerationStructureBuildSizesKHR = {}; PFN_vkCmdBuildAccelerationStructuresKHR vkCmdBuildAccelerationStructuresKHR = {}; PFN_vkSetDebugUtilsObjectNameEXT vkSetDebugUtilsObjectNameEXT = {}; PFN_vkCmdBeginDebugUtilsLabelEXT vkCmdBeginDebugUtilsLabelEXT = {}; PFN_vkCmdEndDebugUtilsLabelEXT vkCmdEndDebugUtilsLabelEXT = {}; PFN_vkCmdCopyAccelerationStructureKHR vkCmdCopyAccelerationStructureKHR = {}; PFN_vkCmdWriteAccelerationStructuresPropertiesKHR vkCmdWriteAccelerationStructuresPropertiesKHR = {}; PFN_vkGetRayTracingShaderGroupHandlesKHR vkGetRayTracingShaderGroupHandlesKHR = {}; PFN_vkCreateRayTracingPipelinesKHR vkCreateRayTracingPipelinesKHR = {}; PFN_vkCmdTraceRaysKHR vkCmdTraceRaysKHR = {}; bool GetProcAddresses(VkInstance instance) { #define GPA(VAR) \ VAR = PFN_##VAR(vkGetInstanceProcAddr(instance, #VAR)); \ if (VAR == nullptr) { \ return false; \ }; GPA(vkCreateAccelerationStructureKHR); GPA(vkDestroyAccelerationStructureKHR); GPA(vkGetAccelerationStructureBuildSizesKHR); GPA(vkCmdBuildAccelerationStructuresKHR); GPA(vkSetDebugUtilsObjectNameEXT); GPA(vkCmdBeginDebugUtilsLabelEXT); GPA(vkCmdEndDebugUtilsLabelEXT); GPA(vkCmdCopyAccelerationStructureKHR); GPA(vkCmdWriteAccelerationStructuresPropertiesKHR); GPA(vkGetRayTracingShaderGroupHandlesKHR); GPA(vkCreateRayTracingPipelinesKHR); GPA(vkCmdTraceRaysKHR); #undef GPA return true; }; } #endif /*************************************************************** * Base class for objects that are allocated with associated device in D3D12 and VK ***************************************************************/ DeviceObject::~DeviceObject() { }; /*************************************************************** * Setting debug name. VK need a object type to give a name. ***************************************************************/ #if defined(GRAPHICS_API_D3D12) void DeviceObject::SetNameInternal(ID3D12Object *obj, const wchar_t * const str) { if (str != nullptr) obj->SetName(str); } #elif defined(GRAPHICS_API_VK) void DeviceObject::SetNameInternal(VkDevice dev, VkObjectType type, uint64_t objHandle, const wchar_t* const str) { #if !defined(WIN32) std::wstring wstr = str; if (wstr.empty()) return; std::string s = std::string(wstr.begin(), wstr.end()); VkDebugUtilsObjectNameInfoEXT info = {}; info.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT; info.objectType = type; info.objectHandle = objHandle; info.pObjectName = s.c_str(); VK::vkSetDebugUtilsObjectNameEXT(dev, &info); #else size_t sLen = wcsnlen_s(str, 4096); if (sLen == 0) return; VkDebugUtilsObjectNameInfoEXT info = {}; info.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT; info.objectType = type; info.objectHandle = objHandle; std::string sBuf; { int size_needed = WideCharToMultiByte(CP_UTF8, 0, str, (int)sLen, NULL, 0, NULL, NULL); sBuf.resize(size_needed, 0); WideCharToMultiByte(CP_UTF8, 0, str, (int)sLen, sBuf.data(), size_needed, NULL, NULL); info.pObjectName = sBuf.data(); } VK::vkSetDebugUtilsObjectNameEXT(dev, &info); #endif } #endif /*************************************************************** * Device in D3D12 * Device in VK ***************************************************************/ #if defined(GRAPHICS_API_D3D12) bool Device::CreateFromApiData(const Device::ApiData &apiData) { if (m_apiData.m_device) { Log::Fatal(L"Device is already in use."); return false; } HRESULT hr = apiData.m_device->QueryInterface(IID_PPV_ARGS(&m_apiData.m_device)); if (FAILED(hr)) { Log::Fatal(L"Invalid D3D12 device detected."); return false; } return true; } Device::~Device() { if (m_apiData.m_device) m_apiData.m_device->Release(); m_apiData = {}; } #elif defined(GRAPHICS_API_VK) bool Device::CreateFromApiData(const Device::ApiData &data) { if (m_apiData.m_device || m_apiData.m_physicalDevice || m_apiData.m_instance) { Log::Fatal(L"Device is already in use."); return false; } if ((!data.m_device) || (!data.m_physicalDevice) || (!data.m_instance)) { Log::Fatal(L"Provided vkInstance, vkDevice or vkPhysicalDevice was null."); return false; } m_apiData = data; if (!VK::GetProcAddresses(m_apiData.m_instance)) { Log::Fatal(L"Faild to load proc addresses of Vulkan extensions."); return false; } { VkPhysicalDeviceMemoryProperties memProperties; vkGetPhysicalDeviceMemoryProperties(m_apiData.m_physicalDevice, &memProperties); for (uint32_t i = 0; i < (uint32_t)VulkanDeviceMemoryType::Count; ++i) { VulkanDeviceMemoryType t = (VulkanDeviceMemoryType)i; VkMemoryPropertyFlags flagBits = {}; switch (t) { case VulkanDeviceMemoryType::Default: flagBits = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT; break; case VulkanDeviceMemoryType::Upload: flagBits = VkMemoryPropertyFlagBits(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); break; case VulkanDeviceMemoryType::Readback: // On Quadro RTX 6000, there is not a memory type with coherent and cached. Unsure if this is right. //flagBits = VkMemoryPropertyFlagBits(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_HOST_CACHED_BIT); flagBits = VkMemoryPropertyFlagBits(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_CACHED_BIT); break; default: assert(0); break; } #if 0 uint32_t bits = 0; for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++) { if ((memProperties.memoryTypes[i].propertyFlags & flagBits) == flagBits) { bits |= (1 << i); } } m_deviceMemoryType[i] = bits; #else uint32_t idx = 0xFFFF'FFFF; for (uint32_t j = 0; j < memProperties.memoryTypeCount; ++j) { if (memProperties.memoryTypes[j].propertyFlags == flagBits) { idx = j; break; } } if (idx == 0xFFFF'FFFF) { // 2nd candidate is which meets the requirement but not ideal. for (uint32_t j = 0; j < memProperties.memoryTypeCount; ++j) { if ((memProperties.memoryTypes[j].propertyFlags & flagBits) == flagBits) { idx = j; break; } } if (idx == 0xFFFF'FFFF) { Log::Fatal(L"Faild to find PhysicalDeviceMemoryProperty."); return false; } } m_deviceMemoryTypeIndex[i] = idx; #endif } } return true; } Device::~Device() { // do not destruct vkDevice here since it is owned by application side. m_apiData = {}; } #endif #if 0 /*************************************************************** * CommandAllocator in D3D12 * CommandPool in VK ***************************************************************/ #if defined(GRAPHICS_API_D3D12) CommandAllocator::~CommandAllocator() { if (m_apiData.m_allocator) { m_apiData.m_allocator->Release(); } m_apiData = {}; } void CommandAllocator::SetName(const std::wstring& str) { SetNameInternal(m_apiData.m_allocator, str.c_str()); } bool CommandAllocator::Create(Device* dev, const CommandAllocator::Type& type) { if (m_apiData.m_allocator) { Log::Fatal(L"CommandAllocator is already in use."); return false; } if (FAILED(dev->m_apiData.m_device->CreateCommandAllocator(type.m_commandListType, IID_PPV_ARGS(&m_apiData.m_allocator)))) { Log::Fatal(L"Failed to create command allocator"); return false; } m_apiData.m_commandListType = type.m_commandListType; return true; } bool CommandAllocator::Reset(Device* /*dev*/) { if (FAILED(m_apiData.m_allocator->Reset())) { Log::Fatal(L"Failed to reset command allocator."); return false; } return true; }; #elif defined(GRAPHICS_API_VK) CommandAllocator::~CommandAllocator() { if (m_apiData.m_device && m_apiData.m_commandPool) vkDestroyCommandPool(m_apiData.m_device, m_apiData.m_commandPool, nullptr); m_apiData = {}; } void CommandAllocator::SetName(const std::wstring& str) { SetNameInternal(m_apiData.m_device, VkObjectType::VK_OBJECT_TYPE_COMMAND_POOL, (uint64_t)m_apiData.m_commandPool, str.c_str()); } bool CommandAllocator::Create(Device* dev, const CommandAllocator::Type& type) { uint32_t queueFamilyCount = 0; vkGetPhysicalDeviceQueueFamilyProperties(dev->m_apiData.m_physicalDevice, &queueFamilyCount, nullptr); //std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount); //vkGetPhysicalDeviceQueueFamilyProperties(dev->m_apiData.m_physicalDevice, &queueFamilyCount, queueFamilies.data()); if (type.m_queueFamilyIndex >= queueFamilyCount) { Log::Fatal(L"Invalid queue family index detected: index:%d numQFamilies:%d ", type.m_queueFamilyIndex, queueFamilyCount); return false; } VkCommandPoolCreateInfo commandPoolCreateInfo = {}; commandPoolCreateInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; commandPoolCreateInfo.flags = VK_COMMAND_POOL_CREATE_TRANSIENT_BIT | VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; commandPoolCreateInfo.queueFamilyIndex = type.m_queueFamilyIndex; if (vkCreateCommandPool(dev->m_apiData.m_device, &commandPoolCreateInfo, nullptr, &m_apiData.m_commandPool) != VK_SUCCESS) { Log::Fatal(L"Faild to create a command pool"); return false; } m_apiData.m_queueFamilyIndex = type.m_queueFamilyIndex; m_apiData.m_device = dev->m_apiData.m_device; return true; } bool CommandAllocator::Reset(Device* dev) { if (vkResetCommandPool(dev->m_apiData.m_device, m_apiData.m_commandPool, 0) != VK_SUCCESS) { Log::Fatal(L"Faild to reset a command pool"); return false; } return true; } #endif #endif /*************************************************************** * DescriptorHeap in D3D12 * DescriptorPool in VK ***************************************************************/ #if defined(GRAPHICS_API_D3D12) constexpr D3D12_DESCRIPTOR_HEAP_TYPE DescriptorHeap::nativeType(const DescriptorHeap::Type &t) { switch (t) { case Type::TextureSrv: case Type::TextureUav: case Type::RawBufferSrv: case Type::RawBufferUav: case Type::TypedBufferSrv: case Type::TypedBufferUav: case Type::StructuredBufferSrv: case Type::StructuredBufferUav: case Type::AccelerationStructureSrv: case Type::Cbv: return D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; case Type::Dsv: return D3D12_DESCRIPTOR_HEAP_TYPE_DSV; case Type::Rtv: return D3D12_DESCRIPTOR_HEAP_TYPE_RTV; case Type::Sampler: return D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER; default: break; } Log::Fatal(L"Invalid descriptor type detected."); return D3D12_DESCRIPTOR_HEAP_TYPE(-1); } DescriptorHeap::~DescriptorHeap() { for (auto& h : m_apiData.m_heaps) { if (h.m_descHeap) { h.m_descHeap->Release(); } } m_apiData = {}; } void DescriptorHeap::SetName(const std::wstring& str) { for (auto& h : m_apiData.m_heaps) { if (h.m_descHeap != nullptr) SetNameInternal(h.m_descHeap, str.c_str()); } } bool DescriptorHeap::Create(Device* dev, const DescriptorHeap::Desc& desc, bool isShaderVisible) { // Find out how many heaps we need static_assert(value(Type::Count) == 13, "Unexpected desc count, make sure all desc types are supported"); for (auto& h : m_apiData.m_heaps) { if (h.m_descHeap) { Log::Fatal(L"DescriptorHeap is already in use."); return false; } } uint32_t nativeDescCount[D3D12_DESCRIPTOR_HEAP_TYPE_NUM_TYPES] = { 0 }; m_desc = desc; for (uint32_t i = 0; i < value(Type::Count); ++i) { Type t = static_cast<Type>(i); nativeDescCount[nativeType(t)] += m_desc.m_descCount[value(t)]; } for (uint32_t i = 0; i < m_apiData.m_heaps.size(); ++i) { auto& h = m_apiData.m_heaps[i]; if (nativeDescCount[i] > 0) { D3D12_DESCRIPTOR_HEAP_TYPE type = D3D12_DESCRIPTOR_HEAP_TYPE(i); D3D12_DESCRIPTOR_HEAP_DESC hDesc = {}; hDesc.Flags = isShaderVisible ? D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE : D3D12_DESCRIPTOR_HEAP_FLAG_NONE; hDesc.Type = type; hDesc.NumDescriptors = nativeDescCount[i]; if (FAILED(dev->m_apiData.m_device->CreateDescriptorHeap(&hDesc, IID_PPV_ARGS(&h.m_descHeap)))) { Log::Fatal(L"Failed to create descriptor heap"); return false; } h.m_numDescriptors = nativeDescCount[i]; h.m_incrementSize = dev->m_apiData.m_device->GetDescriptorHandleIncrementSize(type); } } return true; } bool DescriptorHeap::ResetAllocation() { for (auto& h : m_apiData.m_heaps) h.m_currentOffset = 0; return true; } bool DescriptorHeap::Allocate(const DescriptorTableLayout* descTable, AllocationInfo* retAllocationInfo, uint32_t unboundDescTableCount) { *retAllocationInfo = {}; if ((! descTable->m_lastUnbound) && unboundDescTableCount > 0) { Log::Fatal(L"Error: Invalid unbound descriptor table count detected."); return false; } D3D12_DESCRIPTOR_HEAP_TYPE heapType = nativeType(descTable->m_ranges[0].m_type); uint32_t nbEntryToAllocate = 0; for (size_t i = 0; i < descTable->m_ranges.size(); ++i) { if (heapType != DescriptorHeap::nativeType(descTable->m_ranges[i].m_type)) { Log::Fatal(L"Different heap type entry cannot be in single descriptor table."); return false; } if (descTable->m_lastUnbound && i == descTable->m_ranges.size()-1) { // this should be only the last one. nbEntryToAllocate += unboundDescTableCount; } else { nbEntryToAllocate += descTable->m_ranges[i].m_descCount; } } auto& heapEntry = m_apiData.m_heaps[(uint32_t)heapType]; if (heapEntry.m_currentOffset + nbEntryToAllocate > heapEntry.m_numDescriptors) { Log::Fatal(L"Failed to allocate descriptor table entry. NumDesc:%d CurrentOffset:%d TriedToAllocate:%d", heapEntry.m_numDescriptors, heapEntry.m_currentOffset, nbEntryToAllocate); return false; } auto flags = heapEntry.m_descHeap->GetDesc().Flags; retAllocationInfo->m_numDescriptors = nbEntryToAllocate; retAllocationInfo->m_incrementSize = heapEntry.m_incrementSize; retAllocationInfo->m_hCPU = heapEntry.m_descHeap->GetCPUDescriptorHandleForHeapStart(); if (flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) retAllocationInfo->m_hGPU = heapEntry.m_descHeap->GetGPUDescriptorHandleForHeapStart(); else retAllocationInfo->m_hGPU.ptr = (UINT64)-1; retAllocationInfo->m_hCPU.ptr += heapEntry.m_incrementSize * heapEntry.m_currentOffset; if (flags & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) retAllocationInfo->m_hGPU.ptr += heapEntry.m_incrementSize * heapEntry.m_currentOffset; heapEntry.m_currentOffset += nbEntryToAllocate; return true; } #elif defined(GRAPHICS_API_VK) // non class enum warnings. #ifdef WIN32 #pragma warning( push ) #pragma warning( disable : 26812 ) #endif constexpr VkDescriptorType DescriptorHeap::nativeType(const DescriptorHeap::Type &type) { switch (type) { case Type::AccelerationStructureSrv: return VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR; case Type::TextureSrv: return VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; case Type::TextureUav: return VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; case Type::RawBufferSrv: case Type::TypedBufferSrv: return VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER; case Type::RawBufferUav: case Type::TypedBufferUav: return VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER; case Type::Cbv: return VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; case Type::StructuredBufferSrv: case Type::StructuredBufferUav: return VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; case Type::Dsv: case Type::Rtv: return VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; case Type::Sampler: return VK_DESCRIPTOR_TYPE_SAMPLER; default: Log::Fatal(L"Invalid descriptor type detected."); return VK_DESCRIPTOR_TYPE_MAX_ENUM; } } #ifdef WIN32 #pragma warning( pop ) #endif DescriptorHeap::~DescriptorHeap() { if (m_apiData.m_device && m_apiData.m_descPool) { vkDestroyDescriptorPool(m_apiData.m_device, m_apiData.m_descPool, nullptr); } m_apiData = {}; } void DescriptorHeap::SetName(const std::wstring& str) { SetNameInternal(m_apiData.m_device, VkObjectType::VK_OBJECT_TYPE_DESCRIPTOR_POOL, (uint64_t)m_apiData.m_descPool, str.c_str()); } bool DescriptorHeap::Create(Device* dev, const DescriptorHeap::Desc& desc, bool isShaderVisible) { uint32_t totalDescCount = 0; VkDescriptorPoolSize poolSizeForType[value(Type::Count)]; uint32_t usedSlots = 0; for (uint32_t i = 0; i < value(Type::Count); ++i) { if (desc.m_descCount[i] > 0) { poolSizeForType[usedSlots].type = nativeType((Type)i); poolSizeForType[usedSlots].descriptorCount = desc.m_descCount[i]; totalDescCount += desc.m_descCount[i]; usedSlots++; } } VkDescriptorPoolCreateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; info.maxSets = totalDescCount; info.poolSizeCount = usedSlots; info.pPoolSizes = poolSizeForType; info.flags = 0; // Currently disabled since it's not widely supported. (void)isShaderVisible; #if 0 if (!isShaderVisible) info.flags |= VK_DESCRIPTOR_POOL_CREATE_HOST_ONLY_BIT_VALVE; #endif if (vkCreateDescriptorPool(dev->m_apiData.m_device, &info, nullptr, &m_apiData.m_descPool) != VK_SUCCESS) { Log::Fatal(L"Error creating descriptor pool!"); return false; } m_apiData.m_device = dev->m_apiData.m_device; m_desc = desc; return true; } bool DescriptorHeap::ResetAllocation() { if (vkResetDescriptorPool(m_apiData.m_device, m_apiData.m_descPool, 0) != VK_SUCCESS) { Log::Fatal(L"Error: Failed to reset descriptor pool."); return false; } return true; } bool DescriptorHeap::Allocate(const DescriptorTableLayout *descTable, AllocationInfo* retAllocationInfo, uint32_t unboundDescTableCount) { *retAllocationInfo = {}; if ((! descTable->m_lastUnbound) && unboundDescTableCount > 0) { Log::Fatal(L"Error: Invalid unbound descriptor table count detected."); return false; } VkDescriptorSetAllocateInfo allocInfo = {}; std::vector<VkDescriptorSetLayout> layouts{ descTable->m_apiData.m_descriptorSetLayout }; VkDescriptorSetVariableDescriptorCountAllocateInfo valDescInfo= {}; std::vector<uint32_t> valDescCountArr(layouts.size(), 0); allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; allocInfo.descriptorPool = m_apiData.m_descPool; allocInfo.descriptorSetCount = (uint32_t)layouts.size(); allocInfo.pSetLayouts = layouts.data(); if (descTable->m_lastUnbound) { valDescInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_VARIABLE_DESCRIPTOR_COUNT_ALLOCATE_INFO; valDescCountArr.back() = unboundDescTableCount; // set unbound desc count at the last of the layout. valDescInfo.descriptorSetCount = (uint32_t)valDescCountArr.size(); valDescInfo.pDescriptorCounts = valDescCountArr.data(); allocInfo.pNext = &valDescInfo; } if (vkAllocateDescriptorSets(m_apiData.m_device, &allocInfo, &retAllocationInfo->m_descSet) != VK_SUCCESS) { Log::Fatal(L"Error: Failed to allocate descriptor set from heap."); return false; } return true; } #endif /*************************************************************** * DescriptorTableLayout(D3D12_DESCRIPTOR_RANGE) in D3D12 * DescriptorSetLayout in VK ***************************************************************/ #if defined(GRAPHICS_API_D3D12) constexpr D3D12_DESCRIPTOR_RANGE_TYPE DescriptorTableLayout::nativeType(const DescriptorHeap::Type& type) { using Type = DescriptorHeap::Type; switch (type) { case Type::TextureSrv: case Type::RawBufferSrv: case Type::TypedBufferSrv: case Type::StructuredBufferSrv: case Type::AccelerationStructureSrv: return D3D12_DESCRIPTOR_RANGE_TYPE_SRV; case Type::TextureUav: case Type::RawBufferUav: case Type::TypedBufferUav: case Type::StructuredBufferUav: return D3D12_DESCRIPTOR_RANGE_TYPE_UAV; case Type::Cbv: return D3D12_DESCRIPTOR_RANGE_TYPE_CBV; case Type::Sampler: return D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER; default: break; } Log::Fatal(L"Invalid descriptor range type detected"); return D3D12_DESCRIPTOR_RANGE_TYPE(-1); } DescriptorTableLayout::~DescriptorTableLayout() { // nothing to do in D3D12 m_apiData = {}; } void DescriptorTableLayout::SetName(const std::wstring& /*str*/) { // there is no object to be named. return; } void DescriptorTableLayout::AddRange(DescriptorHeap::Type type, uint32_t baseRegIndex, int32_t descriptorCount, uint32_t regSpace, uint32_t ) { if (m_lastUnbound) { Log::Fatal(L"It's impossible to add further range after unbound descriptor entry."); return; } if (descriptorCount < 0) m_lastUnbound = true; m_ranges.push_back({ type, baseRegIndex, (uint32_t)std::abs(descriptorCount), regSpace }); m_ranges.back().m_offsetFromTableStart = 0; if (m_ranges.size() > 1) { m_ranges[m_ranges.size() - 1].m_offsetFromTableStart = m_ranges[m_ranges.size() - 2].m_offsetFromTableStart + m_ranges[m_ranges.size() - 2].m_descCount; } } bool DescriptorTableLayout::SetAPIData(Device *) { if (m_ranges.size() < 1) { Log::Fatal(L"Invalid descriptor table detected."); return false; } // check if sampler and other type of entryies are conterminate. { D3D12_DESCRIPTOR_HEAP_TYPE heapType = DescriptorHeap::nativeType(m_ranges[0].m_type); for (size_t i = 0; i < m_ranges.size(); ++i) { if (heapType != DescriptorHeap::nativeType(m_ranges[i].m_type)) { Log::Fatal(L"Different heap type entry cannot be in single descriptor table."); return false; } } } m_apiData.m_ranges.resize(m_ranges.size()); uint32_t offsetFromStart = 0; for (size_t i = 0; i < m_ranges.size(); ++i) { auto& src = m_ranges[i]; auto& dst = m_apiData.m_ranges[i]; dst.RangeType = nativeType(src.m_type); if (m_lastUnbound && i == m_ranges.size() - 1) dst.NumDescriptors = (UINT)-1; // In D3D12 -1 means unbound desc tabele. else dst.NumDescriptors = src.m_descCount; dst.BaseShaderRegister = src.m_baseRegIndex; dst.RegisterSpace = src.m_regSpace; dst.OffsetInDescriptorsFromTableStart = offsetFromStart; offsetFromStart += src.m_descCount; } return true; }; #elif defined(GRAPHICS_API_VK) DescriptorTableLayout::~DescriptorTableLayout() { if (m_apiData.m_device && m_apiData.m_descriptorSetLayout) { vkDestroyDescriptorSetLayout(m_apiData.m_device, m_apiData.m_descriptorSetLayout, nullptr); } m_apiData = {}; } void DescriptorTableLayout::SetName(const std::wstring& str) { SetNameInternal(m_apiData.m_device, VkObjectType::VK_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT, (uint64_t)m_apiData.m_descriptorSetLayout, str.c_str()); } void DescriptorTableLayout::AddRange(DescriptorHeap::Type type, uint32_t baseRegIndex, int32_t descriptorCount, uint32_t regSpace, uint32_t offset) { if (m_lastUnbound) { Log::Fatal(L"It's impossible to add further range after unbound descriptor entry."); return; } if (descriptorCount < 0) m_lastUnbound = true; VkDescriptorSetLayoutBinding binding = {}; binding.binding = offset == 0 ? (uint32_t)m_apiData.m_bindings.size() : offset; //baseRegIndex; binding.descriptorCount = std::abs(descriptorCount); #if USE_SHADER_TABLE_RT_SHADERS binding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT | VK_SHADER_STAGE_RAYGEN_BIT_KHR | VK_SHADER_STAGE_CLOSEST_HIT_BIT_KHR | VK_SHADER_STAGE_MISS_BIT_KHR | VK_SHADER_STAGE_CALLABLE_BIT_KHR; #else binding.stageFlags = VK_SHADER_STAGE_COMPUTE_BIT; #endif binding.descriptorType = DescriptorHeap::nativeType(type); m_apiData.m_bindings.push_back(binding); // API independent part. m_ranges.push_back({ type, baseRegIndex, (uint32_t)std::abs(descriptorCount), regSpace }); m_ranges.back().m_offsetFromTableStart = 0; if (m_ranges.size() > 1) { m_ranges[m_ranges.size() - 1].m_offsetFromTableStart = m_ranges[m_ranges.size() - 2].m_offsetFromTableStart + m_ranges[m_ranges.size() - 2].m_descCount; } } bool DescriptorTableLayout::SetAPIData(Device *dev) { VkDescriptorSetLayoutCreateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; info.flags = 0; info.pBindings = m_apiData.m_bindings.data(); info.bindingCount = (uint32_t)m_apiData.m_bindings.size(); std::vector<VkDescriptorBindingFlags> bindFlags(m_apiData.m_bindings.size(), 0); VkDescriptorSetLayoutBindingFlagsCreateInfo bindInfo = {}; if (m_lastUnbound) { // Set variable desc flag bindFlags.back() = VK_DESCRIPTOR_BINDING_VARIABLE_DESCRIPTOR_COUNT_BIT; bindInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_BINDING_FLAGS_CREATE_INFO; bindInfo.bindingCount = (uint32_t)bindFlags.size(); bindInfo.pBindingFlags = bindFlags.data(); info.pNext = &bindInfo; } if (vkCreateDescriptorSetLayout(dev->m_apiData.m_device, &info, nullptr, &m_apiData.m_descriptorSetLayout) != VK_SUCCESS) { Log::Fatal(L"Failed to create descriptor set layout."); return false; } m_apiData.m_device = dev->m_apiData.m_device; uint32_t offsetFromStart = 0; for (size_t i = 0; i < m_ranges.size(); ++i) { auto& r = m_ranges[i]; r.m_offsetFromTableStart = offsetFromStart; offsetFromStart += r.m_descCount; } return true; } #endif /*************************************************************** * DescriptorTable(A portion of a desc heap) in D3D12 * DescriptorSet in VK ***************************************************************/ #if defined(GRAPHICS_API_D3D12) DescriptorTable::~DescriptorTable() { // nothing to do. } bool DescriptorTable::Allocate(DescriptorHeap* descHeap, const DescriptorTableLayout* descTableLayout, uint32_t unboundDescTableCount) { m_descTableLayout = {}; if (!descHeap->Allocate(descTableLayout, &m_apiData.m_heapAllocationInfo, unboundDescTableCount)) { Log::Fatal(L"Faild to allocate descriptor heap."); return false; } m_descTableLayout = descTableLayout; return true; } bool DescriptorTable::SetSrv(Device* dev, uint32_t rangeIndex, uint32_t indexInRange, const ShaderResourceView* srv) { if (rangeIndex >= m_descTableLayout->m_ranges.size()) { Log::Fatal(L"Range index is out of bounds."); return false; } if (indexInRange >= m_descTableLayout->m_ranges[rangeIndex].m_descCount) { Log::Fatal(L"Index in Range is out of bounds."); return false; } uint32_t tableIndex = m_descTableLayout->m_ranges[rangeIndex].m_offsetFromTableStart + indexInRange; if (tableIndex >= m_apiData.m_heapAllocationInfo.m_numDescriptors) { Log::Fatal(L"Table index is out of bounds."); return false; } auto cpuH = m_apiData.m_heapAllocationInfo.m_hCPU; cpuH.ptr += m_apiData.m_heapAllocationInfo.m_incrementSize * tableIndex; auto res = srv->m_apiData.m_resource; if (res == nullptr) { // null descriptor dev->m_apiData.m_device->CreateShaderResourceView(nullptr, &srv->m_apiData.m_desc, cpuH); } else { if (srv->m_apiData.m_desc.ViewDimension == D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE) dev->m_apiData.m_device->CreateShaderResourceView(nullptr, &srv->m_apiData.m_desc, cpuH); // resource must be null for AS. else dev->m_apiData.m_device->CreateShaderResourceView(res, &srv->m_apiData.m_desc, cpuH); } return true; } bool DescriptorTable::SetUav(Device* dev, uint32_t rangeIndex, uint32_t indexInRange, const UnorderedAccessView* uav) { if (rangeIndex >= m_descTableLayout->m_ranges.size()) { Log::Fatal(L"Range index is out of bounds."); return false; } if (indexInRange >= m_descTableLayout->m_ranges[rangeIndex].m_descCount) { Log::Fatal(L"Index in Range is out of bounds."); return false; } uint32_t tableIndex = m_descTableLayout->m_ranges[rangeIndex].m_offsetFromTableStart + indexInRange; if (tableIndex >= m_apiData.m_heapAllocationInfo.m_numDescriptors) { Log::Fatal(L"Table index is out of bounds."); return false; } auto cpuH = m_apiData.m_heapAllocationInfo.m_hCPU; cpuH.ptr += m_apiData.m_heapAllocationInfo.m_incrementSize * tableIndex; auto res = uav->m_apiData.m_resource; if (res == nullptr) { // null descriptor dev->m_apiData.m_device->CreateUnorderedAccessView(nullptr, nullptr, &uav->m_apiData.m_desc, cpuH); } else { if (uav->m_apiData.m_desc.ViewDimension == (D3D12_UAV_DIMENSION)-1) { Log::Fatal(L"Binding AS resource as an UAV is not supported."); return false; } dev->m_apiData.m_device->CreateUnorderedAccessView(res, nullptr, &uav->m_apiData.m_desc, cpuH); } return true; } bool DescriptorTable::SetCbv(Device* dev, uint32_t rangeIndex, uint32_t indexInRange, const ConstantBufferView* cbv) { if (rangeIndex >= m_descTableLayout->m_ranges.size()) { Log::Fatal(L"Range index is out of bounds."); return false; } if (indexInRange >= m_descTableLayout->m_ranges[rangeIndex].m_descCount) { Log::Fatal(L"Index in Range is out of bounds."); return false; } uint32_t tableIndex = m_descTableLayout->m_ranges[rangeIndex].m_offsetFromTableStart + indexInRange; if (tableIndex >= m_apiData.m_heapAllocationInfo.m_numDescriptors) { Log::Fatal(L"Table index is out of bounds."); return false; } auto cpuH = m_apiData.m_heapAllocationInfo.m_hCPU; cpuH.ptr += m_apiData.m_heapAllocationInfo.m_incrementSize * tableIndex; dev->m_apiData.m_device->CreateConstantBufferView(&cbv->m_apiData.m_desc, cpuH); return true; } bool DescriptorTable::SetSampler(Device* dev, uint32_t rangeIndex, uint32_t indexInRange, const Sampler* smp) { if (rangeIndex >= m_descTableLayout->m_ranges.size()) { Log::Fatal(L"Range index is out of bounds."); return false; } if (indexInRange >= m_descTableLayout->m_ranges[rangeIndex].m_descCount) { Log::Fatal(L"Index in Range is out of bounds."); return false; } uint32_t tableIndex = m_descTableLayout->m_ranges[rangeIndex].m_offsetFromTableStart + indexInRange; if (tableIndex >= m_apiData.m_heapAllocationInfo.m_numDescriptors) { Log::Fatal(L"Table index is out of bounds."); return false; } auto cpuH = m_apiData.m_heapAllocationInfo.m_hCPU; cpuH.ptr += m_apiData.m_heapAllocationInfo.m_incrementSize * tableIndex; dev->m_apiData.m_device->CreateSampler(&smp->m_apiData.m_desc, cpuH); return true; } bool DescriptorTable::Copy(Device* dev, uint32_t rangeIndex, uint32_t indexInRange, DescriptorTable* descTable, uint32_t explicitCopySize) { uint32_t nbEntriesToCopy = descTable->m_descTableLayout->m_ranges[0].m_descCount; if (explicitCopySize != 0xFFFF'FFFF) { // table layout was smaller than the requested copy size. if (nbEntriesToCopy < explicitCopySize) { Log::Fatal(L"Explicit copy size was larger than the desc table layout size."); return false; } nbEntriesToCopy = explicitCopySize; } D3D12_DESCRIPTOR_HEAP_TYPE srcHeapType = DescriptorHeap::nativeType(descTable->m_descTableLayout->m_ranges[0].m_type); D3D12_DESCRIPTOR_HEAP_TYPE dstHeapType = DescriptorHeap::nativeType(m_descTableLayout->m_ranges[rangeIndex].m_type); if (srcHeapType != dstHeapType) { Log::Fatal(L"Different heap type detected."); return false; } if (rangeIndex >= m_descTableLayout->m_ranges.size()) { Log::Fatal(L"Range index is out of bounds."); return false; } if ((indexInRange + nbEntriesToCopy) > m_descTableLayout->m_ranges[rangeIndex].m_descCount) { Log::Fatal(L"Index in Range is out of bounds."); return false; } uint32_t tableIndex = m_descTableLayout->m_ranges[rangeIndex].m_offsetFromTableStart + indexInRange; if (tableIndex >= m_apiData.m_heapAllocationInfo.m_numDescriptors) { Log::Fatal(L"Table index is out of bounds."); return false; } auto cpuH = m_apiData.m_heapAllocationInfo.m_hCPU; cpuH.ptr += m_apiData.m_heapAllocationInfo.m_incrementSize * tableIndex; // source is always from beggining of the allocation. auto srcCpuH = descTable->m_apiData.m_heapAllocationInfo.m_hCPU; dev->m_apiData.m_device->CopyDescriptorsSimple(nbEntriesToCopy, cpuH, srcCpuH, srcHeapType); return true; } #elif defined(GRAPHICS_API_VK) DescriptorTable::~DescriptorTable() { // nothing to do. // it doesn't destroy allocated VkDescriptorSet from pool, since the pool will be reset at the beggining of a frame. } bool DescriptorTable::Allocate(DescriptorHeap* descHeap, const DescriptorTableLayout* descTableLayout, uint32_t unboundDescTableCount) { if (!descHeap->Allocate(descTableLayout, &m_apiData.m_heapAllocationInfo, unboundDescTableCount)) { Log::Fatal(L"Faild to allocate descriptor heap."); return false; } m_descTableLayout = descTableLayout; return true; } bool DescriptorTable::SetSrv(Device* dev, uint32_t rangeIndex, uint32_t indexInRange, const ShaderResourceView* srv) { VkWriteDescriptorSet write = {}; VkWriteDescriptorSetAccelerationStructureKHR descASInfo = {}; VkDescriptorBufferInfo rawBufInfo = {}; VkDescriptorImageInfo imageInfo = {}; VkDescriptorType descType = VK_DESCRIPTOR_TYPE_MAX_ENUM; if (srv->m_isNullView) { // Nulldesc extension need to be supported before using. if (srv->m_nullViewType == Resource::Type::Buffer) { bool isAS = false; if (isAS) { descType = VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR; descASInfo.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_ACCELERATION_STRUCTURE_KHR; descASInfo.accelerationStructureCount = 1; descASInfo.pAccelerationStructures = nullptr; write.pNext = &descASInfo; } else if (! srv->m_nullIsTypedBuffer) { descType = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER; // rawBuffer rawBufInfo.buffer = nullptr; rawBufInfo.offset = 0; rawBufInfo.range = 0; write.pBufferInfo = &rawBufInfo; } else { descType = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER; // typed buffer write.pTexelBufferView = nullptr; } } else { descType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; // texture resource imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; imageInfo.imageView = nullptr; imageInfo.sampler = nullptr; write.pImageInfo = &imageInfo; } } else { if (srv->m_apiData.m_accelerationStructure) { descType = VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR; descASInfo.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_ACCELERATION_STRUCTURE_KHR; descASInfo.accelerationStructureCount = 1; descASInfo.pAccelerationStructures = &srv->m_apiData.m_accelerationStructure; write.pNext = &descASInfo; } else if (srv->m_apiData.m_rawBuffer) { descType = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER; // rawBuffer rawBufInfo.buffer = srv->m_apiData.m_rawBuffer; rawBufInfo.offset = srv->m_apiData.m_rawOffsetInBytes; rawBufInfo.range = srv->m_apiData.m_rawSizeInBytes; write.pBufferInfo = &rawBufInfo; } else if (srv->m_apiData.m_isTypedBufferView && srv->m_apiData.m_typedBufferView) { descType = VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER; // typed buffer write.pTexelBufferView = &srv->m_apiData.m_typedBufferView; } else { descType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; // texture resource imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; imageInfo.imageView = srv->m_apiData.m_imageView; imageInfo.sampler = nullptr; write.pImageInfo = &imageInfo; } } write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; write.descriptorType = descType; write.dstSet = m_apiData.m_heapAllocationInfo.m_descSet; write.dstBinding = rangeIndex; write.dstArrayElement = indexInRange; write.descriptorCount = 1; vkUpdateDescriptorSets(dev->m_apiData.m_device, 1, &write, 0, nullptr); return true; } bool DescriptorTable::SetUav(Device* dev, uint32_t rangeIndex, uint32_t indexInRange, const UnorderedAccessView* uav) { VkWriteDescriptorSet write = {}; #if 0 VkWriteDescriptorSetAccelerationStructureKHR descASInfo = {}; #endif VkDescriptorBufferInfo rawBufInfo = {}; VkDescriptorImageInfo imageInfo = {}; VkDescriptorType descType = VK_DESCRIPTOR_TYPE_MAX_ENUM; if (uav->m_isNullView) { // Nulldesc extension need to be supported before using. if (uav->m_nullViewType == Resource::Type::Buffer) { #if 0 bool isAS = false; if (isAS) { descType = VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR; descASInfo.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_ACCELERATION_STRUCTURE_KHR; descASInfo.accelerationStructureCount = 1; descASInfo.pAccelerationStructures = nullptr; write.pNext = &descASInfo; } else #endif if (! uav->m_nullIsTypedBuffer) { // rawBuffer descType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; rawBufInfo.buffer = nullptr; rawBufInfo.offset = 0; rawBufInfo.range = 0; write.pBufferInfo = &rawBufInfo; } else { // typedBuffer descType = VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER; write.pTexelBufferView = nullptr; } } else { descType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; // texture resource imageInfo.imageLayout = VK_IMAGE_LAYOUT_GENERAL; imageInfo.imageView = nullptr; imageInfo.sampler = nullptr; write.pImageInfo = &imageInfo; } } else { #if 0 if (uav->m_apiData.m_accelerationStructure) { descType = VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR; descASInfo.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_ACCELERATION_STRUCTURE_KHR; descASInfo.accelerationStructureCount = 1; descASInfo.pAccelerationStructures = &uav->m_apiData.m_accelerationStructure; write.pNext = &descASInfo; } else #endif if (uav->m_apiData.m_rawBuffer) { // rawBuffer descType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; rawBufInfo.buffer = uav->m_apiData.m_rawBuffer; rawBufInfo.offset = uav->m_apiData.m_rawOffsetInBytes; rawBufInfo.range = uav->m_apiData.m_rawSizeInBytes; write.pBufferInfo = &rawBufInfo; } else if (uav->m_apiData.m_isTypedBufferView && uav->m_apiData.m_typedBufferView) { // typedBuffer descType = VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER; write.pTexelBufferView = &uav->m_apiData.m_typedBufferView; } else { descType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; // texture resource imageInfo.imageLayout = VK_IMAGE_LAYOUT_GENERAL; imageInfo.imageView = uav->m_apiData.m_imageView; imageInfo.sampler = nullptr; write.pImageInfo = &imageInfo; } } write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; write.descriptorType = descType; write.dstSet = m_apiData.m_heapAllocationInfo.m_descSet; write.dstBinding = rangeIndex; write.dstArrayElement = indexInRange; write.descriptorCount = 1; vkUpdateDescriptorSets(dev->m_apiData.m_device, 1, &write, 0, nullptr); return true; } bool DescriptorTable::SetCbv(Device* dev, uint32_t rangeIndex, uint32_t indexInRange, const ConstantBufferView* cbv) { VkDescriptorBufferInfo info; info.buffer = cbv->m_apiData.m_buffer; info.offset = cbv->m_apiData.m_offsetInBytes; info.range = cbv->m_apiData.m_sizeInBytes; VkWriteDescriptorSet write = {}; write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; write.dstSet = m_apiData.m_heapAllocationInfo.m_descSet; write.dstBinding = rangeIndex; write.dstArrayElement = indexInRange; write.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; write.descriptorCount = 1; write.pBufferInfo = &info; vkUpdateDescriptorSets(dev->m_apiData.m_device, 1, &write, 0, nullptr); return true; } bool DescriptorTable::SetSampler(Device* dev, uint32_t rangeIndex, uint32_t indexInRange, const Sampler* sampler) { VkDescriptorImageInfo info; info.imageLayout = VK_IMAGE_LAYOUT_GENERAL; info.imageView = nullptr; info.sampler = sampler->m_apiData.m_sampler; VkWriteDescriptorSet write = {}; write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; write.dstSet = m_apiData.m_heapAllocationInfo.m_descSet; write.dstBinding = rangeIndex; write.dstArrayElement = indexInRange; write.descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER; write.descriptorCount = 1; write.pImageInfo = &info; vkUpdateDescriptorSets(dev->m_apiData.m_device, 1, &write, 0, nullptr); return true; } bool DescriptorTable::Copy(Device* dev, uint32_t rangeIndex, uint32_t indexInRange, DescriptorTable* descTable, uint32_t explicitCopySize) { uint32_t nbEntriesToCopy = descTable->m_descTableLayout->m_ranges[0].m_descCount; if (explicitCopySize != 0xFFFF'FFFF) { // table layout was smaller than the requested copy size. if (nbEntriesToCopy < explicitCopySize) { Log::Fatal(L"Explicit copy size was larger than the desc table layout size."); return false; } nbEntriesToCopy = explicitCopySize; } VkDescriptorType srcHeapType = DescriptorHeap::nativeType(descTable->m_descTableLayout->m_ranges[0].m_type); VkDescriptorType dstHeapType = DescriptorHeap::nativeType(m_descTableLayout->m_ranges[rangeIndex].m_type); if (srcHeapType != dstHeapType) { Log::Fatal(L"Different heap type detected."); return false; } if (rangeIndex >= m_descTableLayout->m_ranges.size()) { Log::Fatal(L"Range index is out of bounds."); return false; } if ((indexInRange + nbEntriesToCopy) > m_descTableLayout->m_ranges[rangeIndex].m_descCount) { Log::Fatal(L"Index in Range is out of bounds."); return false; } VkCopyDescriptorSet copy = {}; copy.sType = VK_STRUCTURE_TYPE_COPY_DESCRIPTOR_SET; copy.srcSet = descTable->m_apiData.m_heapAllocationInfo.m_descSet; copy.srcBinding = 0; copy.srcArrayElement = 0; copy.dstSet = m_apiData.m_heapAllocationInfo.m_descSet; copy.dstBinding = rangeIndex; copy.dstArrayElement = indexInRange; copy.descriptorCount = nbEntriesToCopy; vkUpdateDescriptorSets(dev->m_apiData.m_device, 0, nullptr, 1, &copy); return true; } #endif /*************************************************************** * RootSignature in D3D12 * VkPipelineLayout in VK ***************************************************************/ #if defined(GRAPHICS_API_D3D12) RootSignature::~RootSignature() { if (m_apiData.m_rootSignature) m_apiData.m_rootSignature->Release(); m_apiData = {}; } void RootSignature::SetName(const std::wstring& str) { SetNameInternal(m_apiData.m_rootSignature, str.c_str()); } bool RootSignature::Init(Device* dev, const std::vector<DescriptorTableLayout*>& descLayout) { std::vector<D3D12_ROOT_PARAMETER> params; params.reserve(descLayout.size()); for (auto& tl : descLayout) { D3D12_ROOT_PARAMETER prm = {}; prm.ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; prm.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; prm.DescriptorTable.NumDescriptorRanges = (uint32_t)tl->m_apiData.m_ranges.size(); prm.DescriptorTable.pDescriptorRanges = &tl->m_apiData.m_ranges[0]; params.push_back(prm); } D3D12_ROOT_SIGNATURE_DESC rootDesc = {}; rootDesc.NumParameters = (uint32_t)descLayout.size(); rootDesc.pParameters = &params[0]; rootDesc.Flags = D3D12_ROOT_SIGNATURE_FLAG_NONE; { ID3DBlob* serializedRS = nullptr; ID3DBlob* error = nullptr; HRESULT hr = D3D12SerializeRootSignature(&rootDesc, D3D_ROOT_SIGNATURE_VERSION_1, &serializedRS, &error); if (error) { const char* errorMsg = (const char*)error->GetBufferPointer(); std::wstring wErrorMsg = Log::ToWideString(std::string(errorMsg)); Log::Error(L"SerializeRootSignature error: %s", wErrorMsg.c_str()); } if (FAILED(hr)) { Log::Fatal(L"Failed to serialize rootSignature"); if (serializedRS) serializedRS->Release(); if (error) error->Release(); return false; } hr = dev->m_apiData.m_device->CreateRootSignature(0, serializedRS->GetBufferPointer(), serializedRS->GetBufferSize(), IID_PPV_ARGS(&m_apiData.m_rootSignature)); if (serializedRS) serializedRS->Release(); if (error) error->Release(); if (FAILED(hr)) { Log::Fatal(L"Failed to create rootSignature"); return false; } } return true; }; #elif defined(GRAPHICS_API_VK) RootSignature::~RootSignature() { if (m_apiData.m_device && m_apiData.m_pipelineLayout) vkDestroyPipelineLayout(m_apiData.m_device, m_apiData.m_pipelineLayout, nullptr); m_apiData = {}; } void RootSignature::SetName(const std::wstring& str) { SetNameInternal(m_apiData.m_device, VkObjectType::VK_OBJECT_TYPE_PIPELINE_LAYOUT, (uint64_t)m_apiData.m_pipelineLayout, str.c_str()); } bool RootSignature::Init(Device* dev, const std::vector<DescriptorTableLayout*>& descLayout) { std::vector<VkDescriptorSetLayout> lArr; for (auto& l : descLayout) lArr.push_back(l->m_apiData.m_descriptorSetLayout); VkPipelineLayoutCreateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; info.setLayoutCount = (uint32_t)lArr.size(); info.pSetLayouts = lArr.data(); if (vkCreatePipelineLayout(dev->m_apiData.m_device, &info, nullptr, &m_apiData.m_pipelineLayout) != VK_SUCCESS) { Log::Fatal(L"Failed to create rootSignature (vkPipelineLayout)"); return false; } m_apiData.m_device = dev->m_apiData.m_device; return true; } #endif /*************************************************************** * ShaderByteCode in D3D12 * VkShaderModule in VK * compute only for simplicity. ***************************************************************/ #if defined(GRAPHICS_API_D3D12) ComputeShader::~ComputeShader() { } bool ComputeShader::Init(const void* shaderByteCode, size_t size) { m_apiData.m_shaderByteCode.resize(size); memcpy(m_apiData.m_shaderByteCode.data(), shaderByteCode, size); return true; } #elif defined(GRAPHICS_API_VK) ComputeShader::~ComputeShader() { } bool ComputeShader::Init(const void* shaderByteCode, size_t size) { m_apiData.m_shaderByteCode.resize(size); memcpy(m_apiData.m_shaderByteCode.data(), shaderByteCode, size); return true; } #endif /*************************************************************** * ID3D12PipelineState in D3D12 * VkPipeline in VK * compute only for simplicity. ***************************************************************/ #if defined(GRAPHICS_API_D3D12) ComputePipelineState::~ComputePipelineState() { if (m_apiData.m_pipelineState) m_apiData.m_pipelineState->Release(); m_apiData = {}; } void ComputePipelineState::SetName(const std::wstring& str) { SetNameInternal(m_apiData.m_pipelineState, str.c_str()); } bool ComputePipelineState::Init(Device *dev, RootSignature* rootSig, ComputeShader* shader) { D3D12_COMPUTE_PIPELINE_STATE_DESC desc = {}; desc.pRootSignature = rootSig->m_apiData.m_rootSignature; desc.CS = { shader->m_apiData.m_shaderByteCode.data(), shader->m_apiData.m_shaderByteCode.size() }; HRESULT hr = dev->m_apiData.m_device->CreateComputePipelineState(&desc, IID_PPV_ARGS(&m_apiData.m_pipelineState)); if (FAILED(hr)) { Log::Fatal(L"Failed to create PSO"); return false; } return true; } #elif defined(GRAPHICS_API_VK) ComputePipelineState::~ComputePipelineState() { if (m_apiData.m_device && m_apiData.m_pipeline) vkDestroyPipeline(m_apiData.m_device, m_apiData.m_pipeline, nullptr); if (m_apiData.m_device && m_apiData.m_module_CS) vkDestroyShaderModule(m_apiData.m_device, m_apiData.m_module_CS, nullptr); m_apiData = {}; } void ComputePipelineState::SetName(const std::wstring& str) { SetNameInternal(m_apiData.m_device, VkObjectType::VK_OBJECT_TYPE_PIPELINE, (uint64_t)m_apiData.m_pipeline, str.c_str()); } bool ComputePipelineState::Init(Device* dev, RootSignature* rootSig, ComputeShader* shader) { { VkShaderModuleCreateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; info.codeSize = shader->m_apiData.m_shaderByteCode.size(); info.pCode = (uint32_t *)shader->m_apiData.m_shaderByteCode.data(); if (vkCreateShaderModule(dev->m_apiData.m_device, &info, nullptr, &m_apiData.m_module_CS) != VK_SUCCESS) { Log::Fatal(L"Failed to create a ShaderModule (invalid SPIRV?)"); return false; } } { VkComputePipelineCreateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO; info.stage.pName = "main"; info.stage.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; info.stage.module = m_apiData.m_module_CS; info.layout = rootSig->m_apiData.m_pipelineLayout; if (vkCreateComputePipelines(dev->m_apiData.m_device, nullptr, 1, &info, nullptr, &m_apiData.m_pipeline) != VK_SUCCESS) { Log::Fatal(L"Failed to create PSO (vkPipeline)"); return false; } } m_apiData.m_device = dev->m_apiData.m_device; return true; } #endif /*************************************************************** * ID3D12StateObject in D3D12 ***************************************************************/ #if defined(GRAPHICS_API_D3D12) RaytracingPipelineState::~RaytracingPipelineState() { if (m_apiData.m_rtPSO) m_apiData.m_rtPSO->Release(); m_apiData = {}; } void RaytracingPipelineState::SetName(const std::wstring& str) { SetNameInternal(m_apiData.m_rtPSO, str.c_str()); } #elif defined(GRAPHICS_API_VK) RaytracingPipelineState::~RaytracingPipelineState() { } void RaytracingPipelineState::SetName(const std::wstring& str) { SetNameInternal(m_apiData.m_device, VkObjectType::VK_OBJECT_TYPE_PIPELINE, (uint64_t)m_apiData.m_pipeline, str.c_str()); } #endif /*************************************************************** * Abstraction for samplers. * D3D12_SAMPLER_DESC in D3D12 * VkSamplers in VK ***************************************************************/ #if defined(GRAPHICS_API_D3D12) Sampler::~Sampler() { // nothing to do in D3D12 } bool Sampler::CreateLinearClamp(Device* /*dev*/) { m_apiData.m_desc = {}; m_apiData.m_desc.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR; m_apiData.m_desc.AddressU = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; m_apiData.m_desc.AddressV = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; m_apiData.m_desc.AddressW = D3D12_TEXTURE_ADDRESS_MODE_CLAMP; m_apiData.m_desc.MipLODBias = 0.f; m_apiData.m_desc.MaxAnisotropy = 1; m_apiData.m_desc.ComparisonFunc = D3D12_COMPARISON_FUNC_ALWAYS; m_apiData.m_desc.BorderColor[0] = 0.f; m_apiData.m_desc.BorderColor[1] = 0.f; m_apiData.m_desc.BorderColor[2] = 0.f; m_apiData.m_desc.BorderColor[3] = 0.f; m_apiData.m_desc.MinLOD = 0.f; m_apiData.m_desc.MaxLOD = D3D12_FLOAT32_MAX; return true; } #elif defined(GRAPHICS_API_VK) Sampler::~Sampler() { if (m_apiData.m_device && m_apiData.m_sampler) { vkDestroySampler(m_apiData.m_device, m_apiData.m_sampler, nullptr); } m_apiData = {}; } bool Sampler::CreateLinearClamp(Device* dev) { VkSamplerCreateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; info.magFilter = VK_FILTER_LINEAR; info.minFilter = VK_FILTER_LINEAR; info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; info.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; info.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; info.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; info.mipLodBias = 0.f; info.anisotropyEnable = false; info.maxAnisotropy = 1.f; info.compareEnable = false; info.compareOp = VK_COMPARE_OP_NEVER; info.minLod = 0.f; info.maxLod = VK_LOD_CLAMP_NONE; info.borderColor = VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK; info.unnormalizedCoordinates = false; if (vkCreateSampler(dev->m_apiData.m_device, &info, nullptr, &m_apiData.m_sampler) != VK_SUCCESS) { Log::Fatal(L"Faild to create a sampler"); return false; } m_apiData.m_device = dev->m_apiData.m_device; return true; } #endif /*************************************************************** * Abstraction for all resource types. * D3D12Resource in D3D12 * VkResource in VK ***************************************************************/ const std::array<Resource::FormatDesc, (uint32_t)Resource::Format::Count> Resource::m_formatDescs = { { // Format Name, BytesPerBlock ChannelCount Type {bDepth, bStencil, bCompressed}, {CompressionRatio.Width, CompressionRatio.Height} {numChannelBits.x, numChannelBits.y, numChannelBits.z, numChannelBits.w} {Resource::Format::Unknown, "Unknown", 0, 0, Resource::FormatType::Unknown, false, false, false, {1, 1}, {0, 0, 0, 0 }}, {Resource::Format::R8Unorm, "R8Unorm", 1, 1, Resource::FormatType::Unorm, false, false, false, {1, 1}, {8, 0, 0, 0 }}, {Resource::Format::R8Snorm, "R8Snorm", 1, 1, Resource::FormatType::Snorm, false, false, false, {1, 1}, {8, 0, 0, 0 }}, {Resource::Format::R16Unorm, "R16Unorm", 2, 1, Resource::FormatType::Unorm, false, false, false, {1, 1}, {16, 0, 0, 0 }}, {Resource::Format::R16Snorm, "R16Snorm", 2, 1, Resource::FormatType::Snorm, false, false, false, {1, 1}, {16, 0, 0, 0 }}, {Resource::Format::RG8Unorm, "RG8Unorm", 2, 2, Resource::FormatType::Unorm, false, false, false, {1, 1}, {8, 8, 0, 0 }}, {Resource::Format::RG8Snorm, "RG8Snorm", 2, 2, Resource::FormatType::Snorm, false, false, false, {1, 1}, {8, 8, 0, 0 }}, {Resource::Format::RG16Unorm, "RG16Unorm", 4, 2, Resource::FormatType::Unorm, false, false, false, {1, 1}, {16, 16, 0, 0 }}, {Resource::Format::RG16Snorm, "RG16Snorm", 4, 2, Resource::FormatType::Snorm, false, false, false, {1, 1}, {16, 16, 0, 0 }}, {Resource::Format::RGB16Unorm, "RGB16Unorm", 6, 3, Resource::FormatType::Unorm, false, false, false, {1, 1}, {16, 16, 16, 0 }}, {Resource::Format::RGB16Snorm, "RGB16Snorm", 6, 3, Resource::FormatType::Snorm, false, false, false, {1, 1}, {16, 16, 16, 0 }}, {Resource::Format::R24UnormX8, "R24UnormX8", 4, 2, Resource::FormatType::Unorm, false, false, false, {1, 1}, {24, 8, 0, 0 }}, {Resource::Format::RGB5A1Unorm, "RGB5A1Unorm", 2, 4, Resource::FormatType::Unorm, false, false, false, {1, 1}, {5, 5, 5, 1 }}, {Resource::Format::RGBA8Unorm, "RGBA8Unorm", 4, 4, Resource::FormatType::Unorm, false, false, false, {1, 1}, {8, 8, 8, 8 }}, {Resource::Format::RGBA8Snorm, "RGBA8Snorm", 4, 4, Resource::FormatType::Snorm, false, false, false, {1, 1}, {8, 8, 8, 8 }}, {Resource::Format::RGB10A2Unorm, "RGB10A2Unorm", 4, 4, Resource::FormatType::Unorm, false, false, false, {1, 1}, {10, 10, 10, 2 }}, {Resource::Format::RGB10A2Uint, "RGB10A2Uint", 4, 4, Resource::FormatType::Uint, false, false, false, {1, 1}, {10, 10, 10, 2 }}, {Resource::Format::RGBA16Unorm, "RGBA16Unorm", 8, 4, Resource::FormatType::Unorm, false, false, false, {1, 1}, {16, 16, 16, 16}}, {Resource::Format::RGBA8UnormSrgb, "RGBA8UnormSrgb", 4, 4, Resource::FormatType::UnormSrgb, false, false, false, {1, 1}, {8, 8, 8, 8 }}, // Format Name, BytesPerBlock ChannelCount Type {bDepth, bStencil, bCompressed}, {CompressionRatio.Width, CompressionRatio.Height} {Resource::Format::R16Float, "R16Float", 2, 1, Resource::FormatType::Float, false, false, false, {1, 1}, {16, 0, 0, 0 }}, {Resource::Format::RG16Float, "RG16Float", 4, 2, Resource::FormatType::Float, false, false, false, {1, 1}, {16, 16, 0, 0 }}, {Resource::Format::RGB16Float, "RGB16Float", 6, 3, Resource::FormatType::Float, false, false, false, {1, 1}, {16, 16, 16, 0 }}, {Resource::Format::RGBA16Float, "RGBA16Float", 8, 4, Resource::FormatType::Float, false, false, false, {1, 1}, {16, 16, 16, 16}}, {Resource::Format::R32Float, "R32Float", 4, 1, Resource::FormatType::Float, false, false, false, {1, 1}, {32, 0, 0, 0 }}, {Resource::Format::R32FloatX32, "R32FloatX32", 8, 2, Resource::FormatType::Float, false, false, false, {1, 1}, {32, 32, 0, 0 }}, {Resource::Format::RG32Float, "RG32Float", 8, 2, Resource::FormatType::Float, false, false, false, {1, 1}, {32, 32, 0, 0 }}, {Resource::Format::RGB32Float, "RGB32Float", 12, 3, Resource::FormatType::Float, false, false, false, {1, 1}, {32, 32, 32, 0 }}, {Resource::Format::RGBA32Float, "RGBA32Float", 16, 4, Resource::FormatType::Float, false, false, false, {1, 1}, {32, 32, 32, 32}}, {Resource::Format::R11G11B10Float, "R11G11B10Float", 4, 3, Resource::FormatType::Float, false, false, false, {1, 1}, {11, 11, 10, 0 }}, {Resource::Format::RGB9E5Float, "RGB9E5Float", 4, 3, Resource::FormatType::Float, false, false, false, {1, 1}, {9, 9, 9, 5 }}, {Resource::Format::R8Int, "R8Int", 1, 1, Resource::FormatType::Sint, false, false, false, {1, 1}, {8, 0, 0, 0 }}, {Resource::Format::R8Uint, "R8Uint", 1, 1, Resource::FormatType::Uint, false, false, false, {1, 1}, {8, 0, 0, 0 }}, {Resource::Format::R16Int, "R16Int", 2, 1, Resource::FormatType::Sint, false, false, false, {1, 1}, {16, 0, 0, 0 }}, {Resource::Format::R16Uint, "R16Uint", 2, 1, Resource::FormatType::Uint, false, false, false, {1, 1}, {16, 0, 0, 0 }}, {Resource::Format::R32Int, "R32Int", 4, 1, Resource::FormatType::Sint, false, false, false, {1, 1}, {32, 0, 0, 0 }}, {Resource::Format::R32Uint, "R32Uint", 4, 1, Resource::FormatType::Uint, false, false, false, {1, 1}, {32, 0, 0, 0 }}, {Resource::Format::RG8Int, "RG8Int", 2, 2, Resource::FormatType::Sint, false, false, false, {1, 1}, {8, 8, 0, 0 }}, {Resource::Format::RG8Uint, "RG8Uint", 2, 2, Resource::FormatType::Uint, false, false, false, {1, 1}, {8, 8, 0, 0 }}, {Resource::Format::RG16Int, "RG16Int", 4, 2, Resource::FormatType::Sint, false, false, false, {1, 1}, {16, 16, 0, 0 }}, {Resource::Format::RG16Uint, "RG16Uint", 4, 2, Resource::FormatType::Uint, false, false, false, {1, 1}, {16, 16, 0, 0 }}, {Resource::Format::RG32Int, "RG32Int", 8, 2, Resource::FormatType::Sint, false, false, false, {1, 1}, {32, 32, 0, 0 }}, {Resource::Format::RG32Uint, "RG32Uint", 8, 2, Resource::FormatType::Uint, false, false, false, {1, 1}, {32, 32, 0, 0 }}, // Format Name, BytesPerBlock ChannelCount Type {bDepth, bStencil, bCompressed}, {CompressionRatio.Width, CompressionRatio.Height} {Resource::Format::RGB16Int, "RGB16Int", 6, 3, Resource::FormatType::Sint, false, false, false, {1, 1}, {16, 16, 16, 0 }}, {Resource::Format::RGB16Uint, "RGB16Uint", 6, 3, Resource::FormatType::Uint, false, false, false, {1, 1}, {16, 16, 16, 0 }}, {Resource::Format::RGB32Int, "RGB32Int", 12, 3, Resource::FormatType::Sint, false, false, false, {1, 1}, {32, 32, 32, 0 }}, {Resource::Format::RGB32Uint, "RGB32Uint", 12, 3, Resource::FormatType::Uint, false, false, false, {1, 1}, {32, 32, 32, 0 }}, {Resource::Format::RGBA8Int, "RGBA8Int", 4, 4, Resource::FormatType::Sint, false, false, false, {1, 1}, {8, 8, 8, 8 }}, {Resource::Format::RGBA8Uint, "RGBA8Uint", 4, 4, Resource::FormatType::Uint, false, false, false, {1, 1}, {8, 8, 8, 8 }}, {Resource::Format::RGBA16Int, "RGBA16Int", 8, 4, Resource::FormatType::Sint, false, false, false, {1, 1}, {16, 16, 16, 16}}, {Resource::Format::RGBA16Uint, "RGBA16Uint", 8, 4, Resource::FormatType::Uint, false, false, false, {1, 1}, {16, 16, 16, 16}}, {Resource::Format::RGBA32Int, "RGBA32Int", 16, 4, Resource::FormatType::Sint, false, false, false, {1, 1}, {32, 32, 32, 32}}, {Resource::Format::RGBA32Uint, "RGBA32Uint", 16, 4, Resource::FormatType::Uint, false, false, false, {1, 1}, {32, 32, 32, 32}}, {Resource::Format::BGRA8Unorm, "BGRA8Unorm", 4, 4, Resource::FormatType::Unorm, false, false, false, {1, 1}, {8, 8, 8, 8 }}, {Resource::Format::BGRA8UnormSrgb, "BGRA8UnormSrgb", 4, 4, Resource::FormatType::UnormSrgb, false, false, false, {1, 1}, {8, 8, 8, 8 }}, {Resource::Format::BGRX8Unorm, "BGRX8Unorm", 4, 4, Resource::FormatType::Unorm, false, false, false, {1, 1}, {8, 8, 8, 8 }}, {Resource::Format::BGRX8UnormSrgb, "BGRX8UnormSrgb", 4, 4, Resource::FormatType::UnormSrgb, false, false, false, {1, 1}, {8, 8, 8, 8 }}, {Resource::Format::Alpha8Unorm, "Alpha8Unorm", 1, 1, Resource::FormatType::Unorm, false, false, false, {1, 1}, {0, 0, 0, 8 }}, {Resource::Format::Alpha32Float, "Alpha32Float", 4, 1, Resource::FormatType::Float, false, false, false, {1, 1}, {0, 0, 0, 32 }}, // Format Name, BytesPerBlock ChannelCount Type {bDepth, bStencil, bCompressed}, {CompressionRatio.Width, CompressionRatio.Height} {Resource::Format::R5G6B5Unorm, "R5G6B5Unorm", 2, 3, Resource::FormatType::Unorm, false, false, false, {1, 1}, {5, 6, 5, 0 }}, {Resource::Format::D32Float, "D32Float", 4, 1, Resource::FormatType::Float, true, false, false, {1, 1}, {32, 0, 0, 0 }}, {Resource::Format::D16Unorm, "D16Unorm", 2, 1, Resource::FormatType::Unorm, true, false, false, {1, 1}, {16, 0, 0, 0 }}, {Resource::Format::D32FloatS8X24, "D32FloatS8X24", 8, 2, Resource::FormatType::Float, true, true, false, {1, 1}, {32, 8, 24, 0 }}, {Resource::Format::D24UnormS8, "D24UnormS8", 4, 2, Resource::FormatType::Unorm, true, true, false, {1, 1}, {24, 8, 0, 0 }}, {Resource::Format::BC1Unorm, "BC1Unorm", 8, 3, Resource::FormatType::Unorm, false, false, true, {4, 4}, {64, 0, 0, 0 }}, {Resource::Format::BC1UnormSrgb, "BC1UnormSrgb", 8, 3, Resource::FormatType::UnormSrgb, false, false, true, {4, 4}, {64, 0, 0, 0 }}, {Resource::Format::BC2Unorm, "BC2Unorm", 16, 4, Resource::FormatType::Unorm, false, false, true, {4, 4}, {128, 0, 0, 0 }}, {Resource::Format::BC2UnormSrgb, "BC2UnormSrgb", 16, 4, Resource::FormatType::UnormSrgb, false, false, true, {4, 4}, {128, 0, 0, 0 }}, {Resource::Format::BC3Unorm, "BC3Unorm", 16, 4, Resource::FormatType::Unorm, false, false, true, {4, 4}, {128, 0, 0, 0 }}, {Resource::Format::BC3UnormSrgb, "BC3UnormSrgb", 16, 4, Resource::FormatType::UnormSrgb, false, false, true, {4, 4}, {128, 0, 0, 0 }}, {Resource::Format::BC4Unorm, "BC4Unorm", 8, 1, Resource::FormatType::Unorm, false, false, true, {4, 4}, {64, 0, 0, 0 }}, {Resource::Format::BC4Snorm, "BC4Snorm", 8, 1, Resource::FormatType::Snorm, false, false, true, {4, 4}, {64, 0, 0, 0 }}, {Resource::Format::BC5Unorm, "BC5Unorm", 16, 2, Resource::FormatType::Unorm, false, false, true, {4, 4}, {128, 0, 0, 0 }}, {Resource::Format::BC5Snorm, "BC5Snorm", 16, 2, Resource::FormatType::Snorm, false, false, true, {4, 4}, {128, 0, 0, 0 }}, {Resource::Format::BC6HS16, "BC6HS16", 16, 3, Resource::FormatType::Float, false, false, true, {4, 4}, {128, 0, 0, 0 }}, {Resource::Format::BC6HU16, "BC6HU16", 16, 3, Resource::FormatType::Float, false, false, true, {4, 4}, {128, 0, 0, 0 }}, {Resource::Format::BC7Unorm, "BC7Unorm", 16, 4, Resource::FormatType::Unorm, false, false, true, {4, 4}, {128, 0, 0, 0 }}, {Resource::Format::BC7UnormSrgb, "BC7UnormSrgb", 16, 4, Resource::FormatType::UnormSrgb, false, false, true, {4, 4}, {128, 0, 0, 0 }}, } }; #if defined(GRAPHICS_API_D3D12) ResourceState::State ResourceState::GetResourceState(D3D12_RESOURCE_STATES state) { switch (+state) // to avoid warning at the case which is a composited enum values. to make an integer. { case D3D12_RESOURCE_STATE_COMMON: //case D3D12_RESOURCE_STATE_PRESENT: return ResourceState::State::Common; //return ResourceState::State::Present; case D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER: return ResourceState::State::ConstantBuffer; //return ResourceState::State::VertexBuffer; case D3D12_RESOURCE_STATE_COPY_DEST: return ResourceState::State::CopyDest; case D3D12_RESOURCE_STATE_COPY_SOURCE: return ResourceState::State::CopySource; case D3D12_RESOURCE_STATE_DEPTH_WRITE: return ResourceState::State::DepthStencil; case D3D12_RESOURCE_STATE_INDEX_BUFFER: return ResourceState::State::IndexBuffer; case D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT: //case D3D12_RESOURCE_STATE_PREDICATION: return ResourceState::State::IndirectArg; // return ResourceState::State::Predication; case D3D12_RESOURCE_STATE_RENDER_TARGET: return ResourceState::State::RenderTarget; case D3D12_RESOURCE_STATE_RESOLVE_DEST: return ResourceState::State::ResolveDest; case D3D12_RESOURCE_STATE_RESOLVE_SOURCE: return ResourceState::State::ResolveSource; case D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE: return ResourceState::State::ShaderResource; case D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE: return ResourceState::State::PixelShader; case D3D12_RESOURCE_STATE_STREAM_OUT: return ResourceState::State::StreamOut; case D3D12_RESOURCE_STATE_UNORDERED_ACCESS: return ResourceState::State::UnorderedAccess; case D3D12_RESOURCE_STATE_GENERIC_READ: return ResourceState::State::GenericRead; case D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE: return ResourceState::State::NonPixelShader; case D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE: return ResourceState::State::AccelerationStructure; default: break; } Log::Fatal(L"Invalid resource state detected."); return ResourceState::State(-1); } D3D12_RESOURCE_STATES ResourceState::GetD3D12ResourceState(ResourceState::State state) { switch (state) { case ResourceState::State::Undefined: case ResourceState::State::Common: return D3D12_RESOURCE_STATE_COMMON; case ResourceState::State::ConstantBuffer: case ResourceState::State::VertexBuffer: return D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER; case ResourceState::State::CopyDest: return D3D12_RESOURCE_STATE_COPY_DEST; case ResourceState::State::CopySource: return D3D12_RESOURCE_STATE_COPY_SOURCE; case ResourceState::State::DepthStencil: return D3D12_RESOURCE_STATE_DEPTH_WRITE; // If depth-writes are disabled, return D3D12_RESOURCE_STATE_DEPTH_WRITE case ResourceState::State::IndexBuffer: return D3D12_RESOURCE_STATE_INDEX_BUFFER; case ResourceState::State::IndirectArg: return D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; case ResourceState::State::Predication: return D3D12_RESOURCE_STATE_PREDICATION; case ResourceState::State::Present: return D3D12_RESOURCE_STATE_PRESENT; case ResourceState::State::RenderTarget: return D3D12_RESOURCE_STATE_RENDER_TARGET; case ResourceState::State::ResolveDest: return D3D12_RESOURCE_STATE_RESOLVE_DEST; case ResourceState::State::ResolveSource: return D3D12_RESOURCE_STATE_RESOLVE_SOURCE; case ResourceState::State::ShaderResource: #if 0 // this will hit error when SDK uses COMPUTE queue. return D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; // TODO: Need the shader usage mask to set state more optimally #else return D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; #endif case ResourceState::State::StreamOut: return D3D12_RESOURCE_STATE_STREAM_OUT; case ResourceState::State::UnorderedAccess: return D3D12_RESOURCE_STATE_UNORDERED_ACCESS; case ResourceState::State::GenericRead: return D3D12_RESOURCE_STATE_GENERIC_READ; case ResourceState::State::PixelShader: return D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; case ResourceState::State::NonPixelShader: return D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; case ResourceState::State::AccelerationStructure: return D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE; default: break; } Log::Fatal(L"Invalid resource state detected."); return D3D12_RESOURCE_STATES(-1); } #endif uint32_t SubresourceRange::CalcSubresource(uint32_t mipSlice, uint32_t arraySlice, uint32_t MipLevels) { return mipSlice + (arraySlice * MipLevels); } void ResourceState::SetState(ResourceState::State state, Subresource subresource) { m_isTrackingPerSubresource |= subresource != SubresourceAll; if (subresource == SubresourceAll) { static_assert(sizeof(state) == 1, "Expects small state enum size for memset to work"); memset(m_state, (int)state, sizeof(m_state)); } else m_state[subresource] = state; } ResourceState::State ResourceState::GetState(Subresource subresource) { return subresource == SubresourceAll ? m_state[0] : m_state[subresource]; } bool ResourceState::IsTrackingPerSubresource() const { return m_isTrackingPerSubresource; } void Resource::SetGlobalState(ResourceState::State state, ResourceState::Subresource subresource) { m_globalState.SetState(state, subresource); } ResourceState::State Resource::GetGlobalState(ResourceState::Subresource subresource) { return m_globalState.GetState(subresource); } #if defined(GRAPHICS_API_D3D12) Resource::ApiResourceID Resource::GetApiResourceID() const { return reinterpret_cast<Resource::ApiResourceID>(m_apiData.m_resource); } const std::array<Resource::DxgiFormatDesc, uint32_t(Resource::Format::Count)> Resource::m_DxgiFormatDesc = { { {Resource::Format::Unknown, DXGI_FORMAT_UNKNOWN}, {Resource::Format::R8Unorm, DXGI_FORMAT_R8_UNORM}, {Resource::Format::R8Snorm, DXGI_FORMAT_R8_SNORM}, {Resource::Format::R16Unorm, DXGI_FORMAT_R16_UNORM}, {Resource::Format::R16Snorm, DXGI_FORMAT_R16_SNORM}, {Resource::Format::RG8Unorm, DXGI_FORMAT_R8G8_UNORM}, {Resource::Format::RG8Snorm, DXGI_FORMAT_R8G8_SNORM}, {Resource::Format::RG16Unorm, DXGI_FORMAT_R16G16_UNORM}, {Resource::Format::RG16Snorm, DXGI_FORMAT_R16G16_SNORM}, {Resource::Format::RGB16Unorm, DXGI_FORMAT_UNKNOWN}, {Resource::Format::RGB16Snorm, DXGI_FORMAT_UNKNOWN}, {Resource::Format::R24UnormX8, DXGI_FORMAT_R24_UNORM_X8_TYPELESS}, {Resource::Format::RGB5A1Unorm, DXGI_FORMAT_B5G5R5A1_UNORM}, {Resource::Format::RGBA8Unorm, DXGI_FORMAT_R8G8B8A8_UNORM}, {Resource::Format::RGBA8Snorm, DXGI_FORMAT_R8G8B8A8_SNORM}, {Resource::Format::RGB10A2Unorm, DXGI_FORMAT_R10G10B10A2_UNORM}, {Resource::Format::RGB10A2Uint, DXGI_FORMAT_R10G10B10A2_UINT}, {Resource::Format::RGBA16Unorm, DXGI_FORMAT_R16G16B16A16_UNORM}, {Resource::Format::RGBA8UnormSrgb, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB}, {Resource::Format::R16Float, DXGI_FORMAT_R16_FLOAT}, {Resource::Format::RG16Float, DXGI_FORMAT_R16G16_FLOAT}, {Resource::Format::RGB16Float, DXGI_FORMAT_UNKNOWN}, {Resource::Format::RGBA16Float, DXGI_FORMAT_R16G16B16A16_FLOAT}, {Resource::Format::R32Float, DXGI_FORMAT_R32_FLOAT}, {Resource::Format::R32FloatX32, DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS}, {Resource::Format::RG32Float, DXGI_FORMAT_R32G32_FLOAT}, {Resource::Format::RGB32Float, DXGI_FORMAT_R32G32B32_FLOAT}, {Resource::Format::RGBA32Float, DXGI_FORMAT_R32G32B32A32_FLOAT}, {Resource::Format::R11G11B10Float, DXGI_FORMAT_R11G11B10_FLOAT}, {Resource::Format::RGB9E5Float, DXGI_FORMAT_R9G9B9E5_SHAREDEXP}, {Resource::Format::R8Int, DXGI_FORMAT_R8_SINT}, {Resource::Format::R8Uint, DXGI_FORMAT_R8_UINT}, {Resource::Format::R16Int, DXGI_FORMAT_R16_SINT}, {Resource::Format::R16Uint, DXGI_FORMAT_R16_UINT}, {Resource::Format::R32Int, DXGI_FORMAT_R32_SINT}, {Resource::Format::R32Uint, DXGI_FORMAT_R32_UINT}, {Resource::Format::RG8Int, DXGI_FORMAT_R8G8_SINT}, {Resource::Format::RG8Uint, DXGI_FORMAT_R8G8_UINT}, {Resource::Format::RG16Int, DXGI_FORMAT_R16G16_SINT}, {Resource::Format::RG16Uint, DXGI_FORMAT_R16G16_UINT}, {Resource::Format::RG32Int, DXGI_FORMAT_R32G32_SINT}, {Resource::Format::RG32Uint, DXGI_FORMAT_R32G32_UINT}, {Resource::Format::RGB16Int, DXGI_FORMAT_UNKNOWN}, {Resource::Format::RGB16Uint, DXGI_FORMAT_UNKNOWN}, {Resource::Format::RGB32Int, DXGI_FORMAT_R32G32B32_SINT}, {Resource::Format::RGB32Uint, DXGI_FORMAT_R32G32B32_UINT}, {Resource::Format::RGBA8Int, DXGI_FORMAT_R8G8B8A8_SINT}, {Resource::Format::RGBA8Uint, DXGI_FORMAT_R8G8B8A8_UINT}, {Resource::Format::RGBA16Int, DXGI_FORMAT_R16G16B16A16_SINT}, {Resource::Format::RGBA16Uint, DXGI_FORMAT_R16G16B16A16_UINT}, {Resource::Format::RGBA32Int, DXGI_FORMAT_R32G32B32A32_SINT}, {Resource::Format::RGBA32Uint, DXGI_FORMAT_R32G32B32A32_UINT}, {Resource::Format::BGRA8Unorm, DXGI_FORMAT_B8G8R8A8_UNORM}, {Resource::Format::BGRA8UnormSrgb, DXGI_FORMAT_B8G8R8A8_UNORM_SRGB}, {Resource::Format::BGRX8Unorm, DXGI_FORMAT_B8G8R8X8_UNORM}, {Resource::Format::BGRX8UnormSrgb, DXGI_FORMAT_B8G8R8X8_UNORM_SRGB}, {Resource::Format::Alpha8Unorm, DXGI_FORMAT_A8_UNORM}, {Resource::Format::Alpha32Float, DXGI_FORMAT_UNKNOWN}, {Resource::Format::R5G6B5Unorm, DXGI_FORMAT_B5G6R5_UNORM}, {Resource::Format::D32Float, DXGI_FORMAT_D32_FLOAT}, {Resource::Format::D16Unorm, DXGI_FORMAT_D16_UNORM}, {Resource::Format::D32FloatS8X24, DXGI_FORMAT_D32_FLOAT_S8X24_UINT}, {Resource::Format::D24UnormS8, DXGI_FORMAT_D24_UNORM_S8_UINT}, {Resource::Format::BC1Unorm, DXGI_FORMAT_BC1_UNORM}, {Resource::Format::BC1UnormSrgb, DXGI_FORMAT_BC1_UNORM_SRGB}, {Resource::Format::BC2Unorm, DXGI_FORMAT_BC2_UNORM}, {Resource::Format::BC2UnormSrgb, DXGI_FORMAT_BC2_UNORM_SRGB}, {Resource::Format::BC3Unorm, DXGI_FORMAT_BC3_UNORM}, {Resource::Format::BC3UnormSrgb, DXGI_FORMAT_BC3_UNORM_SRGB}, {Resource::Format::BC4Unorm, DXGI_FORMAT_BC4_UNORM}, {Resource::Format::BC4Snorm, DXGI_FORMAT_BC4_SNORM}, {Resource::Format::BC5Unorm, DXGI_FORMAT_BC5_UNORM}, {Resource::Format::BC5Snorm, DXGI_FORMAT_BC5_SNORM}, {Resource::Format::BC6HS16, DXGI_FORMAT_BC6H_SF16}, {Resource::Format::BC6HU16, DXGI_FORMAT_BC6H_UF16}, {Resource::Format::BC7Unorm, DXGI_FORMAT_BC7_UNORM}, {Resource::Format::BC7UnormSrgb, DXGI_FORMAT_BC7_UNORM_SRGB}, } }; DXGI_FORMAT Resource::GetTypelessFormat(Resource::Format format) { using Format = Resource::Format; switch (format) { case Format::D16Unorm: return DXGI_FORMAT_R16_TYPELESS; case Format::D32FloatS8X24: return DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS; case Format::D24UnormS8: return DXGI_FORMAT_R24G8_TYPELESS; case Format::D32Float: return DXGI_FORMAT_R32_TYPELESS; case Format::RGBA32Float: case Format::RGBA32Uint: case Format::RGBA32Int: return DXGI_FORMAT_R32G32B32A32_TYPELESS; case Format::RGB32Float: case Format::RGB32Uint: case Format::RGB32Int: return DXGI_FORMAT_R32G32B32_TYPELESS; case Format::RG32Float: case Format::RG32Uint: case Format::RG32Int: return DXGI_FORMAT_R32G32_TYPELESS; case Format::R32Float: case Format::R32Uint: case Format::R32Int: return DXGI_FORMAT_R32_TYPELESS; case Format::RGBA16Float: case Format::RGBA16Int: case Format::RGBA16Uint: case Format::RGBA16Unorm: return DXGI_FORMAT_R16G16B16A16_TYPELESS; case Format::RG16Float: case Format::RG16Int: case Format::RG16Uint: case Format::RG16Unorm: return DXGI_FORMAT_R16G16_TYPELESS; case Format::R16Float: case Format::R16Int: case Format::R16Uint: case Format::R16Unorm: return DXGI_FORMAT_R16_TYPELESS; case Format::RGBA8Int: case Format::RGBA8Snorm: case Format::RGBA8Uint: case Format::RGBA8Unorm: case Format::RGBA8UnormSrgb: return DXGI_FORMAT_R8G8B8A8_TYPELESS; case Format::RG8Int: case Format::RG8Snorm: case Format::RG8Uint: case Format::RG8Unorm: return DXGI_FORMAT_R8G8_TYPELESS; case Format::R8Int: case Format::R8Snorm: case Format::R8Uint: case Format::R8Unorm: return DXGI_FORMAT_R8_TYPELESS; case Format::RGB10A2Unorm: case Format::RGB10A2Uint: return DXGI_FORMAT_R10G10B10A2_TYPELESS; default: break; } Log::Fatal(L"Invalid format for typless format."); return DXGI_FORMAT_UNKNOWN; } D3D12_RESOURCE_FLAGS Resource::GetD3D12ResourceFlags(Resource::BindFlags flags) { using BindFlags = Resource::BindFlags; D3D12_RESOURCE_FLAGS d3d = D3D12_RESOURCE_FLAG_NONE; bool uavRequired = is_set(flags, BindFlags::UnorderedAccess) || is_set(flags, BindFlags::AccelerationStructure); if (uavRequired) { d3d |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; } if (is_set(flags, BindFlags::DepthStencil)) { if (is_set(flags, BindFlags::ShaderResource) == false) { d3d |= D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE; } d3d |= D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; } if (is_set(flags, BindFlags::RenderTarget)) { d3d |= D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; } return d3d; } Resource::BindFlags Resource::GetBindFlags(D3D12_RESOURCE_FLAGS resourceFlags) { Resource::BindFlags bindFlags = Resource::BindFlags::None; if (resourceFlags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) { bindFlags |= BindFlags::RenderTarget; resourceFlags &= ~D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; } if (resourceFlags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL) { bindFlags |= BindFlags::DepthStencil; resourceFlags &= ~D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; } if (resourceFlags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) { bindFlags |= BindFlags::UnorderedAccess; resourceFlags &= ~D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; } if (resourceFlags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) { bindFlags |= BindFlags::ShaderResource; resourceFlags &= ~D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE; } constexpr D3D12_RESOURCE_FLAGS NOP = D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER | D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS | D3D12_RESOURCE_FLAG_VIDEO_DECODE_REFERENCE_ONLY; if (resourceFlags & NOP) { resourceFlags &= ~NOP; } assert(resourceFlags == 0 && "Not all shader flags accounted for."); return bindFlags; } D3D12_RESOURCE_DIMENSION Resource::GetResourceDimension(Resource::Type type) { using Type = Resource::Type; switch (type) { case Type::Buffer: return D3D12_RESOURCE_DIMENSION_BUFFER; case Type::Texture1D: return D3D12_RESOURCE_DIMENSION_TEXTURE1D; case Type::Texture2D: case Type::Texture2DMultisample: case Type::TextureCube: return D3D12_RESOURCE_DIMENSION_TEXTURE2D; case Type::Texture3D: return D3D12_RESOURCE_DIMENSION_TEXTURE3D; default: break; } Log::Fatal(L"Invalid resouce dimension detected."); return D3D12_RESOURCE_DIMENSION(-1); } Resource::Type Resource::GetResourceType(D3D12_RESOURCE_DIMENSION dimension) { switch (dimension) { case D3D12_RESOURCE_DIMENSION_BUFFER: return Resource::Type::Buffer; case D3D12_RESOURCE_DIMENSION_TEXTURE1D: return Resource::Type::Texture1D; case D3D12_RESOURCE_DIMENSION_TEXTURE2D: return Resource::Type::Texture2D; case D3D12_RESOURCE_DIMENSION_TEXTURE3D: return Resource::Type::Texture3D; default: break; } Log::Fatal(L"Invalid resouce dimension detected."); return Resource::Type(-1); } const D3D12_HEAP_PROPERTIES Resource::m_defaultHeapProps = { D3D12_HEAP_TYPE_DEFAULT, D3D12_CPU_PAGE_PROPERTY_UNKNOWN, D3D12_MEMORY_POOL_UNKNOWN, 0, 0 }; const D3D12_HEAP_PROPERTIES Resource::m_uploadHeapProps = { D3D12_HEAP_TYPE_UPLOAD, D3D12_CPU_PAGE_PROPERTY_UNKNOWN, D3D12_MEMORY_POOL_UNKNOWN, 0, 0, }; const D3D12_HEAP_PROPERTIES Resource::m_readbackHeapProps = { D3D12_HEAP_TYPE_READBACK, D3D12_CPU_PAGE_PROPERTY_UNKNOWN, D3D12_MEMORY_POOL_UNKNOWN, 0, 0 }; bool Resource::IsTexture(Resource::Type type) { return type == Type::Texture1D || type == Type::Texture2D || type == Type::Texture3D || type == Type::TextureCube || type == Type::Texture2DMultisample; } bool Resource::IsBuffer(Resource::Type type){ return type == Type::Buffer; } Resource::~Resource() { if (m_apiData.m_resource) { Log::Fatal(L"ID3D12Resource was not released properly."); } } void Resource::SetName(const std::wstring& str) { SetNameInternal(m_apiData.m_resource, str.c_str()); } #else Resource::ApiResourceID Resource::GetApiResourceID() const { return reinterpret_cast<Resource::ApiResourceID>(m_apiData.m_image); } const std::array<Resource::VkFormatDesc, uint32_t(Resource::Format::Count)> Resource::m_VkFormatDesc = { { { Resource::Format::Unknown, VK_FORMAT_UNDEFINED }, { Resource::Format::R8Unorm, VK_FORMAT_R8_UNORM }, { Resource::Format::R8Snorm, VK_FORMAT_R8_SNORM }, { Resource::Format::R16Unorm, VK_FORMAT_R16_UNORM }, { Resource::Format::R16Snorm, VK_FORMAT_R16_SNORM }, { Resource::Format::RG8Unorm, VK_FORMAT_R8G8_UNORM }, { Resource::Format::RG8Snorm, VK_FORMAT_R8G8_SNORM }, { Resource::Format::RG16Unorm, VK_FORMAT_R16G16_UNORM }, { Resource::Format::RG16Snorm, VK_FORMAT_R16G16_SNORM }, { Resource::Format::RGB16Unorm, VK_FORMAT_R16G16B16_UNORM }, { Resource::Format::RGB16Snorm, VK_FORMAT_R16G16B16_SNORM }, { Resource::Format::R24UnormX8, VK_FORMAT_UNDEFINED }, { Resource::Format::RGB5A1Unorm, VK_FORMAT_B5G5R5A1_UNORM_PACK16 }, // VK different component order? { Resource::Format::RGBA8Unorm, VK_FORMAT_R8G8B8A8_UNORM }, { Resource::Format::RGBA8Snorm, VK_FORMAT_R8G8B8A8_SNORM }, { Resource::Format::RGB10A2Unorm, VK_FORMAT_A2R10G10B10_UNORM_PACK32 }, // VK different component order? { Resource::Format::RGB10A2Uint, VK_FORMAT_A2R10G10B10_UINT_PACK32 }, // VK different component order? { Resource::Format::RGBA16Unorm, VK_FORMAT_R16G16B16A16_UNORM }, { Resource::Format::RGBA8UnormSrgb, VK_FORMAT_R8G8B8A8_SRGB }, { Resource::Format::R16Float, VK_FORMAT_R16_SFLOAT }, { Resource::Format::RG16Float, VK_FORMAT_R16G16_SFLOAT }, { Resource::Format::RGB16Float, VK_FORMAT_R16G16B16_SFLOAT }, { Resource::Format::RGBA16Float, VK_FORMAT_R16G16B16A16_SFLOAT }, { Resource::Format::R32Float, VK_FORMAT_R32_SFLOAT }, { Resource::Format::R32FloatX32, VK_FORMAT_UNDEFINED }, { Resource::Format::RG32Float, VK_FORMAT_R32G32_SFLOAT }, { Resource::Format::RGB32Float, VK_FORMAT_R32G32B32_SFLOAT }, { Resource::Format::RGBA32Float, VK_FORMAT_R32G32B32A32_SFLOAT }, { Resource::Format::R11G11B10Float, VK_FORMAT_B10G11R11_UFLOAT_PACK32 }, // Unsigned in VK { Resource::Format::RGB9E5Float, VK_FORMAT_E5B9G9R9_UFLOAT_PACK32 }, // Unsigned in VK { Resource::Format::R8Int, VK_FORMAT_R8_SINT }, { Resource::Format::R8Uint, VK_FORMAT_R8_UINT }, { Resource::Format::R16Int, VK_FORMAT_R16_SINT }, { Resource::Format::R16Uint, VK_FORMAT_R16_UINT }, { Resource::Format::R32Int, VK_FORMAT_R32_SINT }, { Resource::Format::R32Uint, VK_FORMAT_R32_UINT }, { Resource::Format::RG8Int, VK_FORMAT_R8G8_SINT }, { Resource::Format::RG8Uint, VK_FORMAT_R8G8_UINT }, { Resource::Format::RG16Int, VK_FORMAT_R16G16_SINT }, { Resource::Format::RG16Uint, VK_FORMAT_R16G16_UINT }, { Resource::Format::RG32Int, VK_FORMAT_R32G32_SINT }, { Resource::Format::RG32Uint, VK_FORMAT_R32G32_UINT }, { Resource::Format::RGB16Int, VK_FORMAT_R16G16B16_SINT }, { Resource::Format::RGB16Uint, VK_FORMAT_R16G16B16_UINT }, { Resource::Format::RGB32Int, VK_FORMAT_R32G32B32_SINT }, { Resource::Format::RGB32Uint, VK_FORMAT_R32G32B32_UINT }, { Resource::Format::RGBA8Int, VK_FORMAT_R8G8B8A8_SINT }, { Resource::Format::RGBA8Uint, VK_FORMAT_R8G8B8A8_UINT }, { Resource::Format::RGBA16Int, VK_FORMAT_R16G16B16A16_SINT }, { Resource::Format::RGBA16Uint, VK_FORMAT_R16G16B16A16_UINT }, { Resource::Format::RGBA32Int, VK_FORMAT_R32G32B32A32_SINT }, { Resource::Format::RGBA32Uint, VK_FORMAT_R32G32B32A32_UINT }, { Resource::Format::BGRA8Unorm, VK_FORMAT_B8G8R8A8_UNORM }, { Resource::Format::BGRA8UnormSrgb, VK_FORMAT_B8G8R8A8_SRGB }, { Resource::Format::BGRX8Unorm, VK_FORMAT_B8G8R8A8_UNORM }, { Resource::Format::BGRX8UnormSrgb, VK_FORMAT_B8G8R8A8_SRGB }, { Resource::Format::Alpha8Unorm, VK_FORMAT_UNDEFINED }, { Resource::Format::Alpha32Float, VK_FORMAT_UNDEFINED }, { Resource::Format::R5G6B5Unorm, VK_FORMAT_R5G6B5_UNORM_PACK16 }, { Resource::Format::D32Float, VK_FORMAT_D32_SFLOAT }, { Resource::Format::D16Unorm, VK_FORMAT_D16_UNORM }, { Resource::Format::D32FloatS8X24, VK_FORMAT_D32_SFLOAT_S8_UINT }, { Resource::Format::D24UnormS8, VK_FORMAT_D24_UNORM_S8_UINT }, { Resource::Format::BC1Unorm, VK_FORMAT_BC1_RGB_UNORM_BLOCK }, { Resource::Format::BC1UnormSrgb, VK_FORMAT_BC1_RGB_SRGB_BLOCK }, { Resource::Format::BC2Unorm, VK_FORMAT_BC2_UNORM_BLOCK }, { Resource::Format::BC2UnormSrgb, VK_FORMAT_BC2_SRGB_BLOCK }, { Resource::Format::BC3Unorm, VK_FORMAT_BC3_UNORM_BLOCK }, { Resource::Format::BC3UnormSrgb, VK_FORMAT_BC3_SRGB_BLOCK }, { Resource::Format::BC4Unorm, VK_FORMAT_BC4_UNORM_BLOCK }, { Resource::Format::BC4Snorm, VK_FORMAT_BC4_SNORM_BLOCK }, { Resource::Format::BC5Unorm, VK_FORMAT_BC5_UNORM_BLOCK }, { Resource::Format::BC5Snorm, VK_FORMAT_BC5_SNORM_BLOCK }, { Resource::Format::BC6HS16, VK_FORMAT_BC6H_SFLOAT_BLOCK }, { Resource::Format::BC6HU16, VK_FORMAT_BC6H_UFLOAT_BLOCK }, { Resource::Format::BC7Unorm, VK_FORMAT_BC7_UNORM_BLOCK }, { Resource::Format::BC7UnormSrgb, VK_FORMAT_BC7_SRGB_BLOCK }, } }; VkBufferUsageFlags Resource::GetBufferUsageFlag(Resource::BindFlags bindFlags) { // Assume every buffer can be read from and written into VkBufferUsageFlags flags = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; auto setBit = [&flags, &bindFlags](BindFlags f, VkBufferUsageFlags vkBit) {if (is_set(bindFlags, f)) flags |= vkBit; }; setBit(BindFlags::Vertex, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT); setBit(BindFlags::Index, VK_BUFFER_USAGE_INDEX_BUFFER_BIT); setBit(BindFlags::UnorderedAccess, VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT); setBit(BindFlags::ShaderResource, VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT); setBit(BindFlags::IndirectArg, VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT); setBit(BindFlags::Constant, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT); setBit(BindFlags::AccelerationStructureBuildInput, VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR); setBit(BindFlags::AccelerationStructure, VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR); setBit(BindFlags::ShaderDeviceAddress, VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT); return flags; } VkImageUsageFlags Resource::GetImageUsageFlag(Resource::BindFlags bindFlags) { // Assume that every image can be updated/cleared, read from, and sampled VkImageUsageFlags flags = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; auto setBit = [&flags, &bindFlags](BindFlags f, VkImageUsageFlags vkBit) {if (is_set(bindFlags, f)) flags |= vkBit; }; setBit(BindFlags::UnorderedAccess, VK_IMAGE_USAGE_STORAGE_BIT); setBit(BindFlags::ShaderResource, VK_IMAGE_USAGE_SAMPLED_BIT); setBit(BindFlags::RenderTarget, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT); setBit(BindFlags::DepthStencil, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT); return flags; } VkImageType Resource::GetVkImageType(Resource::Type type) { switch (type) { case Texture::Type::Texture1D: return VK_IMAGE_TYPE_1D; case Texture::Type::Texture2D: case Texture::Type::Texture2DMultisample: case Texture::Type::TextureCube: return VK_IMAGE_TYPE_2D; case Texture::Type::Texture3D: return VK_IMAGE_TYPE_3D; default: break; } Log::Fatal(L"Invalid image type detected."); return VkImageType(-1); } Texture::Type Resource::GetImageType(VkImageViewType type) { switch (type) { case VK_IMAGE_VIEW_TYPE_1D: return Texture::Type::Texture1D; case VK_IMAGE_VIEW_TYPE_2D: return Texture::Type::Texture2D; case VK_IMAGE_VIEW_TYPE_3D: return Texture::Type::Texture3D; case VK_IMAGE_VIEW_TYPE_CUBE: return Texture::Type::TextureCube; case VK_IMAGE_VIEW_TYPE_1D_ARRAY: case VK_IMAGE_VIEW_TYPE_2D_ARRAY: case VK_IMAGE_VIEW_TYPE_CUBE_ARRAY: default: break; } Log::Fatal(L"Invalid image type detected."); return Texture::Type(-1); } VkImageLayout Resource::GetVkImageLayout(ResourceState::State state) { switch (state) { case ResourceState::State::Undefined: return VK_IMAGE_LAYOUT_UNDEFINED; case ResourceState::State::PreInitialized: return VK_IMAGE_LAYOUT_PREINITIALIZED; case ResourceState::State::Common: case ResourceState::State::UnorderedAccess: return VK_IMAGE_LAYOUT_GENERAL; case ResourceState::State::RenderTarget: return VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; case ResourceState::State::DepthStencil: return VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; case ResourceState::State::ShaderResource: case ResourceState::State::NonPixelShader: return VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; case ResourceState::State::ResolveDest: case ResourceState::State::CopyDest: return VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; case ResourceState::State::ResolveSource: case ResourceState::State::CopySource: return VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; break; case ResourceState::State::Present: return VK_IMAGE_LAYOUT_PRESENT_SRC_KHR; default: break; } Log::Fatal(L"Invalid resource state detected."); return VkImageLayout(-1); } VkAccessFlagBits Resource::GetVkAccessMask(ResourceState::State state) { switch (state) { case ResourceState::State::Undefined: case ResourceState::State::Present: case ResourceState::State::Common: case ResourceState::State::PreInitialized: case ResourceState::State::GenericRead: return VkAccessFlagBits(0); case ResourceState::State::VertexBuffer: return VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT; case ResourceState::State::ConstantBuffer: return VK_ACCESS_UNIFORM_READ_BIT; case ResourceState::State::IndexBuffer: return VK_ACCESS_INDEX_READ_BIT; case ResourceState::State::RenderTarget: return VkAccessFlagBits(VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_READ_BIT); case ResourceState::State::UnorderedAccess: return VK_ACCESS_SHADER_WRITE_BIT; case ResourceState::State::DepthStencil: return VkAccessFlagBits(VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT); case ResourceState::State::ShaderResource: case ResourceState::State::NonPixelShader: return VK_ACCESS_SHADER_READ_BIT; // modified here. case ResourceState::State::IndirectArg: return VK_ACCESS_INDIRECT_COMMAND_READ_BIT; case ResourceState::State::ResolveDest: case ResourceState::State::CopyDest: return VK_ACCESS_TRANSFER_WRITE_BIT; case ResourceState::State::ResolveSource: case ResourceState::State::CopySource: return VK_ACCESS_TRANSFER_READ_BIT; default: break; } Log::Fatal(L"Invalid resource state detected."); return VkAccessFlagBits(-1); } VkPipelineStageFlags Resource::GetVkPipelineStageMask(ResourceState::State state, bool src) { switch (state) { case ResourceState::State::Undefined: case ResourceState::State::PreInitialized: case ResourceState::State::Common: case ResourceState::State::VertexBuffer: case ResourceState::State::IndexBuffer: case ResourceState::State::UnorderedAccess: case ResourceState::State::ConstantBuffer: case ResourceState::State::ShaderResource: case ResourceState::State::RenderTarget: case ResourceState::State::DepthStencil: case ResourceState::State::IndirectArg: case ResourceState::State::CopyDest: case ResourceState::State::CopySource: case ResourceState::State::ResolveDest: case ResourceState::State::ResolveSource: case ResourceState::State::Present: // SDK only uses compute so there is no strong reason to specify fine grained pipeline stage. return src ? VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT : VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; default: break; } Log::Fatal(L"Invalid resource state detected."); return VkPipelineStageFlags(-1); } VkImageAspectFlags Resource::GetVkImageAspectFlags(Resource::Format format, bool ignoreStencil) { VkImageAspectFlags flags = 0; if (Resource::IsDepthFormat(format)) flags |= VK_IMAGE_ASPECT_DEPTH_BIT; if (ignoreStencil == false) { if (Resource::IsStencilFormat(format)) flags |= VK_IMAGE_ASPECT_STENCIL_BIT; } if (Resource::IsDepthStencilFormat(format) == false) flags |= VK_IMAGE_ASPECT_COLOR_BIT; return flags; } bool Resource::AllocateDeviceMemory(Device *dev, Device::VulkanDeviceMemoryType memType, uint32_t /*memoryTypeBits*/, bool enableDeviceAddress, size_t size, VkDeviceMemory *mem) { VkMemoryAllocateInfo allocInfo = {}; allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; allocInfo.allocationSize = size; allocInfo.memoryTypeIndex = dev->m_deviceMemoryTypeIndex[(uint32_t)memType]; VkMemoryAllocateFlagsInfo flagInfo = {}; flagInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO; flagInfo.flags = 0; if (enableDeviceAddress) flagInfo.flags |= VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; allocInfo.pNext = &flagInfo; if (vkAllocateMemory(dev->m_apiData.m_device, &allocInfo, nullptr, mem) != VK_SUCCESS) { Log::Fatal(L"Failed to allocate vk memory."); return false; } return true; } Resource::~Resource() { #if 0 if (m_apiData.m_device || m_apiData.m_buffer || m_apiData.m_image || m_apiData.m_accelerationStructure || m_apiData.m_deviceMemory || m_apiData.m_deviceAddress) { #else if (m_apiData.m_device || m_apiData.m_buffer || m_apiData.m_image || m_apiData.m_deviceMemory || m_apiData.m_deviceAddress) { #endif Log::Fatal(L"Vk resource was not destroyed properly."); } } void Resource::SetName(const std::wstring& str) { if (m_apiData.m_buffer != 0) SetNameInternal(m_apiData.m_device, VkObjectType::VK_OBJECT_TYPE_BUFFER, (uint64_t)m_apiData.m_buffer, str.c_str()); if (m_apiData.m_image != 0) SetNameInternal(m_apiData.m_device, VkObjectType::VK_OBJECT_TYPE_IMAGE, (uint64_t)m_apiData.m_image, str.c_str()); #if 0 if (m_apiData.m_accelerationStructure != 0) SetNameInternal(m_apiData.m_device, VkObjectType::VK_OBJECT_TYPE_ACCELERATION_STRUCTURE_KHR, (uint64_t)m_apiData.m_accelerationStructure, str.c_str()); #endif if (m_apiData.m_deviceMemory != 0) SetNameInternal(m_apiData.m_device, VkObjectType::VK_OBJECT_TYPE_DEVICE_MEMORY, (uint64_t)m_apiData.m_deviceMemory, str.c_str()); } #endif /*************************************************************** * Abstraction for heaps. * D3D12Heap in D3D12 * VkDeviceMemory in VK ***************************************************************/ #if defined(GRAPHICS_API_D3D12) Heap::~Heap() { if (m_apiData.m_heap) m_apiData.m_heap->Release(); } bool Heap::Create(Device *dev, uint64_t sizeInBytes, Buffer::CpuAccess cpuAccess) { D3D12_HEAP_DESC desc = {}; desc.SizeInBytes = sizeInBytes; if (cpuAccess == Buffer::CpuAccess::Write) { desc.Properties = Resource::m_uploadHeapProps; } else if (cpuAccess == Buffer::CpuAccess::Read) { desc.Properties = Resource::m_readbackHeapProps; } else { desc.Properties = Resource::m_defaultHeapProps; } m_cpuAccess = cpuAccess; desc.Alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT; desc.Flags = D3D12_HEAP_FLAG_CREATE_NOT_ZEROED; HRESULT hr = dev->m_apiData.m_device->CreateHeap(&desc, IID_PPV_ARGS(&m_apiData.m_heap)); if (FAILED(hr)) { Log::Fatal(L"Failed to create heap."); return false; } m_sizeInBytes = sizeInBytes; return true; } #endif #if defined(GRAPHICS_API_VK) Heap::~Heap() { if (m_apiData.m_deviceMemory && m_apiData.m_device) vkFreeMemory(m_apiData.m_device, m_apiData.m_deviceMemory, nullptr); m_apiData.m_deviceMemory = {}; m_apiData.m_device = {}; } bool Heap::Create(Device* dev, uint64_t sizeInBytes, Buffer::CpuAccess cpuAccess) { Device::VulkanDeviceMemoryType memType; if (cpuAccess == Buffer::CpuAccess::Write) { memType = Device::VulkanDeviceMemoryType::Upload; } else if (cpuAccess == Buffer::CpuAccess::Read) { memType = Device::VulkanDeviceMemoryType::Readback; } else { memType = Device::VulkanDeviceMemoryType::Default; } m_cpuAccess = cpuAccess; VkMemoryAllocateInfo allocInfo = {}; allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; allocInfo.allocationSize = sizeInBytes; allocInfo.memoryTypeIndex = dev->m_deviceMemoryTypeIndex[(uint32_t)memType]; VkMemoryAllocateFlagsInfo flagInfo = {}; if (cpuAccess == Buffer::CpuAccess::None) { // always enable address bit for default heaps. flagInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO; flagInfo.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; allocInfo.pNext = &flagInfo; } if (vkAllocateMemory(dev->m_apiData.m_device, &allocInfo, nullptr, &m_apiData.m_deviceMemory) != VK_SUCCESS) { Log::Fatal(L"Failed to allocate vk memory."); return false; } m_apiData.m_device = dev->m_apiData.m_device; m_sizeInBytes = sizeInBytes; return true; } #endif /*************************************************************** * Abstraction for texture resources. ***************************************************************/ #if defined(GRAPHICS_API_D3D12) Texture::~Texture() { if (m_apiData.m_resource && m_destructWithDestructor) m_apiData.m_resource->Release(); m_apiData.m_resource = nullptr; } bool Texture::Create(Device* dev, Resource::Type type, Resource::Format format, Resource::BindFlags bindFlags, uint32_t width, uint32_t height, uint32_t depth, uint32_t arraySize, uint32_t mipLevels, uint32_t sampleCount) { m_type = type; m_format = format; m_bindFlags = bindFlags; SetGlobalState(ResourceState::State::Common); m_width = width; m_height = height; m_depth = depth; m_arraySize = arraySize; m_mipLevels = mipLevels; m_sampleCount = sampleCount; m_subresourceCount = SubresourceRange::CalcSubresource(mipLevels - 1, arraySize - 1, m_mipLevels) + 1; D3D12_RESOURCE_DESC desc = {}; desc.MipLevels = (UINT16)m_mipLevels; desc.Format = Resource::GetDxgiFormat(m_format); desc.Width = m_width; desc.Height = m_height; desc.Flags = Resource::GetD3D12ResourceFlags(m_bindFlags); desc.SampleDesc.Count = m_sampleCount; desc.SampleDesc.Quality = 0; desc.Dimension = Resource::GetResourceDimension(m_type); desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; desc.Alignment = 0; if (m_type == Resource::Type::TextureCube) { desc.DepthOrArraySize = (UINT16)(m_arraySize * 6); } else if (m_type == Resource::Type::Texture3D) { desc.DepthOrArraySize = (UINT16)m_depth; } else { desc.DepthOrArraySize = (UINT16)m_arraySize; } assert(desc.Width > 0 && desc.Height > 0); assert(desc.MipLevels > 0 && desc.DepthOrArraySize > 0 && desc.SampleDesc.Count > 0); D3D12_CLEAR_VALUE clearValue = {}; D3D12_CLEAR_VALUE* pClearVal = nullptr; if ((m_bindFlags & (Resource::BindFlags::RenderTarget | Resource::BindFlags::DepthStencil)) != Resource::BindFlags::None) { clearValue.Format = desc.Format; if ((m_bindFlags & Texture::BindFlags::DepthStencil) != Texture::BindFlags::None) { clearValue.DepthStencil.Depth = 1.0f; } pClearVal = &clearValue; } //If depth and either ua or sr, set to typeless if (Resource::IsDepthFormat(m_format) && is_set(m_bindFlags, Texture::BindFlags::ShaderResource | Texture::BindFlags::UnorderedAccess)) { desc.Format = Resource::GetTypelessFormat(m_format); pClearVal = nullptr; } D3D12_HEAP_FLAGS heapFlags = is_set(m_bindFlags, Resource::BindFlags::Shared) ? D3D12_HEAP_FLAG_SHARED : D3D12_HEAP_FLAG_NONE; HRESULT hr = dev->m_apiData.m_device->CreateCommittedResource(&Resource::m_defaultHeapProps, heapFlags, &desc, D3D12_RESOURCE_STATE_COMMON, pClearVal, IID_PPV_ARGS(&m_apiData.m_resource)); if (FAILED(hr)) { Log::Fatal(L"Failed to create a comitted resource"); return false; } return true; }; bool Texture::InitFromApiData(ApiData apiData, ResourceState::State state) { m_destructWithDestructor = false; m_apiData = apiData; D3D12_RESOURCE_DESC desc = m_apiData.m_resource->GetDesc(); m_type = GetResourceType(desc.Dimension); m_bindFlags = GetBindFlags(desc.Flags); m_width = (uint32_t)desc.Width; m_height = (uint32_t)desc.Height; m_mipLevels = desc.MipLevels; m_sampleCount = desc.SampleDesc.Count; m_format = Resource::GetResourceFormat(desc.Format); // assert(m_format != Format::Unknown && "Unknown format"); assert(desc.DepthOrArraySize == 1 && "We can distinquish between depth and array slices here..."); m_depth = 1; m_arraySize = 1; m_subresourceCount = SubresourceRange::CalcSubresource(m_mipLevels - 1, m_arraySize - 1, m_mipLevels) + 1; SetGlobalState(state); return true; } bool Texture::GetUploadBufferFootplint(Device *dev, uint32_t /*subresourceIndex*/, uint32_t* rowPitchInBytes, uint32_t* totalSizeInBytes) { D3D12_RESOURCE_DESC desc = {}; desc.MipLevels = (UINT16)m_mipLevels; desc.Format = Resource::GetDxgiFormat(m_format); desc.Width = m_width; desc.Height = m_height; desc.Flags = Resource::GetD3D12ResourceFlags(m_bindFlags); desc.SampleDesc.Count = m_sampleCount; desc.SampleDesc.Quality = 0; desc.Dimension = Resource::GetResourceDimension(m_type); desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; desc.Alignment = 0; if (m_type == Resource::Type::TextureCube) { desc.DepthOrArraySize = (UINT16)(m_arraySize * 6); } else if (m_type == Resource::Type::Texture3D) { desc.DepthOrArraySize = (UINT16)m_depth; } else { desc.DepthOrArraySize = (UINT16)m_arraySize; } assert(desc.Width > 0 && desc.Height > 0); assert(desc.MipLevels > 0 && desc.DepthOrArraySize > 0 && desc.SampleDesc.Count > 0); D3D12_PLACED_SUBRESOURCE_FOOTPRINT uploadBufferFootprint; UINT numRows; UINT64 rowSizeInBytes, totalBytes; dev->m_apiData.m_device->GetCopyableFootprints(&desc, 0, 1, 0, &uploadBufferFootprint, &numRows, &rowSizeInBytes, &totalBytes); *rowPitchInBytes = uploadBufferFootprint.Footprint.RowPitch; *totalSizeInBytes = (uint32_t)totalBytes; return true; } #elif defined(GRAPHICS_API_VK) Texture::~Texture() { if (m_destructWithDestructor) { if (m_apiData.m_device && m_apiData.m_image) vkDestroyImage(m_apiData.m_device, m_apiData.m_image, nullptr); if (m_apiData.m_deviceMemory && m_apiData.m_device) vkFreeMemory(m_apiData.m_device, m_apiData.m_deviceMemory, nullptr); m_apiData.m_image = {}; m_apiData.m_deviceMemory = {}; m_apiData.m_device = {}; } } static VkFormatFeatureFlags getFormatFeatureBitsFromUsage(VkImageUsageFlags usage) { VkFormatFeatureFlags bits = 0; if (usage & VK_IMAGE_USAGE_TRANSFER_SRC_BIT) bits |= VK_FORMAT_FEATURE_TRANSFER_SRC_BIT; if (usage & VK_IMAGE_USAGE_TRANSFER_DST_BIT) bits |= VK_FORMAT_FEATURE_TRANSFER_DST_BIT; if (usage & VK_IMAGE_USAGE_SAMPLED_BIT) bits |= VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT; if (usage & VK_IMAGE_USAGE_STORAGE_BIT) bits |= VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT; if (usage & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) bits |= VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT; if (usage & VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) bits |= VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT; assert((usage & VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) == 0); assert((usage & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) == 0); return bits; } static VkImageTiling getFormatImageTiling(VkPhysicalDevice phDev, VkFormat format, VkImageUsageFlags usage) { VkFormatProperties p; vkGetPhysicalDeviceFormatProperties(phDev, format, &p); auto featureBits = getFormatFeatureBitsFromUsage(usage); if ((p.optimalTilingFeatures & featureBits) == featureBits) return VK_IMAGE_TILING_OPTIMAL; if ((p.linearTilingFeatures & featureBits) == featureBits) return VK_IMAGE_TILING_LINEAR; Log::Fatal(L"Invalid tiling feature detected."); return VkImageTiling(-1); } bool Texture::Create(Device* dev, Resource::Type type, Resource::Format format, Resource::BindFlags bindFlags, uint32_t width, uint32_t height, uint32_t depth, uint32_t arraySize, uint32_t mipLevels, uint32_t sampleCount) { VkImageCreateInfo imageInfo = {}; imageInfo.arrayLayers = arraySize; imageInfo.extent.depth = depth; imageInfo.extent.height = height; imageInfo.extent.width = width; imageInfo.format = Resource::GetVkFormat(format); imageInfo.imageType = Resource::GetVkImageType(type); imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; //pData ? VK_IMAGE_LAYOUT_PREINITIALIZED : VK_IMAGE_LAYOUT_UNDEFINED; imageInfo.mipLevels = mipLevels; imageInfo.pQueueFamilyIndices = nullptr; imageInfo.queueFamilyIndexCount = 0; imageInfo.samples = (VkSampleCountFlagBits)sampleCount; imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; imageInfo.usage = Resource::GetImageUsageFlag(bindFlags); imageInfo.tiling = getFormatImageTiling(dev->m_apiData.m_physicalDevice, imageInfo.format, imageInfo.usage); if (type == Resource::Type::TextureCube) { imageInfo.flags = VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT; imageInfo.arrayLayers *= 6; } if (vkCreateImage(dev->m_apiData.m_device, &imageInfo, nullptr, &m_apiData.m_image) != VK_SUCCESS) { Log::Fatal(L"Failed to create a vkImage"); return false; } // Allocate the GPU memory VkMemoryRequirements memRequirements; vkGetImageMemoryRequirements(dev->m_apiData.m_device, m_apiData.m_image, &memRequirements); if (! Resource::AllocateDeviceMemory(dev, Device::VulkanDeviceMemoryType::Default, memRequirements.memoryTypeBits, false, memRequirements.size, &m_apiData.m_deviceMemory)) { Log::Fatal(L"Failed to allocate vk device memory"); return false; } if (vkBindImageMemory(dev->m_apiData.m_device, m_apiData.m_image, m_apiData.m_deviceMemory, 0) != VK_SUCCESS) { Log::Fatal(L"Failed to bind vk device memory to an image"); return false; } m_apiData.m_device = dev->m_apiData.m_device; m_type = type; m_bindFlags = bindFlags; SetGlobalState(ResourceState::State::Undefined); // pData ? ResourceState::State::PreInitialized : ResourceState::State::Undefined; m_width = width; m_height = height; m_depth = depth; m_mipLevels = mipLevels; m_sampleCount = sampleCount; m_arraySize = arraySize; m_format = format; return true; } bool Texture::InitFromApiData( VkDevice device, VkImage image, VkImageViewType imageViewType, VkFormat format, uint32_t mipCount, uint32_t layerCount, ResourceState::State state) { m_destructWithDestructor = false; m_apiData.m_device = device; m_apiData.m_image = image; m_type = Resource::GetImageType(imageViewType); m_bindFlags = (BindFlags)0;// Resource::GetImageUsageFlag(bindFlags);; SetGlobalState(state); m_width = 0xffffffff; m_height = 0xffffffff; m_depth = 0xffffffff; m_mipLevels = mipCount; m_sampleCount = 1; m_arraySize = layerCount; m_format = GetResourceFormat(format); return true; } bool Texture::GetUploadBufferFootplint(Device* /*dev*/, uint32_t subresourceIndex, uint32_t* rowPitchInBytes, uint32_t* totalSizeInBytes) { if (subresourceIndex != 0) { Log::Fatal(L"subresourceIndex != 0 is unsupported."); return false; } switch (m_type) { case Type::Texture1D: case Type::Texture2D: case Type::Texture3D: break; default: Log::Fatal(L"Unsupported dimension (type) detected."); return false; } uint32_t pixelInBytes = GetFormatBytesPerBlock(m_format); if (pixelInBytes <= 0) { Log::Fatal(L"Invalid format detected."); return false; } *rowPitchInBytes = m_width * pixelInBytes; *totalSizeInBytes = *rowPitchInBytes * m_height * m_depth * m_arraySize; return true; } #endif /*************************************************************** * Abstraction for buffer resources. ***************************************************************/ #if defined(GRAPHICS_API_D3D12) Buffer::~Buffer() { if (m_apiData.m_resource && m_destructWithDestructor) m_apiData.m_resource->Release(); m_apiData.m_resource = nullptr; } bool Buffer::Create(Device* dev, uint64_t sizeInBytesOrNumberOfElements, Resource::Format format, Heap* heap, uint64_t heapOffsetInBytes, uint64_t heapAllocatedSizeInByte, Resource::BindFlags bindFlags, Buffer::CpuAccess cpuAccess) { if (cpuAccess != CpuAccess::None && is_set(bindFlags, BindFlags::Shared)) { Log::Fatal(L"Can't create shared resource with CPU access other than 'None'."); return false; } size_t size = sizeInBytesOrNumberOfElements; if (format != Resource::Format::Unknown) { size *= Resource::GetFormatBytesPerBlock(format); } if (heap != nullptr) { // restrictions for placed buffer. if (heap->m_cpuAccess != cpuAccess) { Log::Fatal(L"Cpu access flag was inconsistent."); return false; } if (is_set(bindFlags, BindFlags::Constant)) { Log::Fatal(L"Constant buffer isn't supported by placed resource."); return false; } if (is_set(m_bindFlags, Resource::BindFlags::Shared)) { Log::Fatal(L"Shared resource buffer isn't supported by placed resource."); return false; } if (heapAllocatedSizeInByte < size) { Log::Fatal(L"Heap allocation was insufficient."); return false; } } if (bindFlags == BindFlags::Constant) { m_sizeInBytes = ALIGN((uint64_t)D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT, size); } else { m_sizeInBytes = size; } m_bindFlags = bindFlags; m_cpuAccess = cpuAccess; m_format = Format::Unknown; const D3D12_HEAP_PROPERTIES *hp = nullptr; if (cpuAccess == CpuAccess::Write) { SetGlobalState(ResourceState::State::GenericRead); hp = &Resource::m_uploadHeapProps; } else if (cpuAccess == CpuAccess::Read && bindFlags == BindFlags::None) { SetGlobalState(ResourceState::State::CopyDest); hp = &Resource::m_readbackHeapProps; } else { SetGlobalState(ResourceState::State::Common); if (is_set(bindFlags, BindFlags::AccelerationStructure)) SetGlobalState(ResourceState::State::AccelerationStructure); else if (is_set(bindFlags, BindFlags::UnorderedAccess)) SetGlobalState(ResourceState::State::UnorderedAccess); hp = &Resource::m_defaultHeapProps; } { // Create the buffer D3D12_RESOURCE_DESC bufDesc = {}; bufDesc.Alignment = 0; bufDesc.DepthOrArraySize = 1; bufDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; bufDesc.Flags = Resource::GetD3D12ResourceFlags(m_bindFlags); bufDesc.Format = DXGI_FORMAT_UNKNOWN; bufDesc.Height = 1; bufDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; bufDesc.MipLevels = 1; bufDesc.SampleDesc.Count = 1; bufDesc.SampleDesc.Quality = 0; bufDesc.Width = m_sizeInBytes; assert(bufDesc.Width > 0); D3D12_RESOURCE_STATES d3dState = ResourceState::GetD3D12ResourceState(GetGlobalState()); D3D12_HEAP_FLAGS heapFlags = is_set(m_bindFlags, Resource::BindFlags::Shared) ? D3D12_HEAP_FLAG_SHARED : D3D12_HEAP_FLAG_NONE; if (is_set(m_bindFlags, Resource::BindFlags::AllowShaderAtomics)) heapFlags |= D3D12_HEAP_FLAG_ALLOW_SHADER_ATOMICS; HRESULT hr; if (heap == nullptr) { hr = dev->m_apiData.m_device->CreateCommittedResource(hp, heapFlags, &bufDesc, d3dState, nullptr, IID_PPV_ARGS(&m_apiData.m_resource)); } else { hr = dev->m_apiData.m_device->CreatePlacedResource(heap->m_apiData.m_heap, heapOffsetInBytes, &bufDesc, d3dState, nullptr, IID_PPV_ARGS(&m_apiData.m_resource)); } if (FAILED(hr)) { Log::Fatal(L"Faild to allocate a buffer"); return false; } } if (format != Resource::Format::Unknown) { // set format and element count here for SRV/UAV. m_format = format; m_elementCount = (uint32_t)sizeInBytesOrNumberOfElements; } else { m_format = Resource::Format::Unknown; m_elementCount = 0; } return true; } bool Buffer::Create(Device* dev, uint64_t sizeInBytesOrNumberOfElements, Resource::Format format, Resource::BindFlags bindFlags, Buffer::CpuAccess cpuAccess) { return Create(dev, sizeInBytesOrNumberOfElements, format, nullptr, 0, 0, bindFlags, cpuAccess); } #if 0 bool Buffer::CreateStructured(Device* dev, uint32_t structSize, uint32_t elementCount, Resource::BindFlags bindFlags, CpuAccess cpuAccess) { uint32_t size = structSize * elementCount; if (!Create(dev, size, bindFlags, cpuAccess)) { Log::Fatal(L"Faild to create structured buffer."); return false; } m_elementCount = elementCount; m_structSizeInBytes = structSize; return true; } #endif uint64_t Buffer::GetGpuAddress() const { D3D12_GPU_VIRTUAL_ADDRESS adr = m_apiData.m_resource->GetGPUVirtualAddress(); return adr; } void* Buffer::Map(Device* /*dev*/, Buffer::MapType type, uint32_t subResourceIndex, uint64_t readRangeBegin, uint64_t readRangeEnd) { void* mappedPtr = nullptr; D3D12_RANGE readRange = { 0, 0 }; switch (type) { case MapType::Read: case MapType::Write: readRange = { readRangeBegin, readRangeEnd }; break; case MapType::WriteDiscard: default: break; } if (FAILED(m_apiData.m_resource->Map(subResourceIndex, &readRange, &mappedPtr))) { Log::Fatal(L"Faild to map buffer, probably device has been removed for some reason."); return nullptr; } #if 0 return mappedPtr; #else // D3D12 doesn't make offset for readrange, on the other hand, VK does. intptr_t offsetPtr = reinterpret_cast<intptr_t>(mappedPtr) + readRangeBegin; return reinterpret_cast<void *>(offsetPtr); #endif } /** Unmap the buffer */ void Buffer::Unmap(Device* /*dev*/, uint32_t subResourceIndex, uint64_t writeRangeBegin, uint64_t writeRangeEnd) { D3D12_RANGE wroteRange = { writeRangeBegin, writeRangeEnd }; m_apiData.m_resource->Unmap(subResourceIndex, &wroteRange); } #elif defined(GRAPHICS_API_VK) Buffer::~Buffer() { if (m_destructWithDestructor) { #if 0 if (m_apiData.m_accelerationStructure && m_apiData.m_device) VK::vkDestroyAccelerationStructureKHR(m_apiData.m_device, m_apiData.m_accelerationStructure, nullptr); #endif if (m_apiData.m_buffer && m_apiData.m_device) vkDestroyBuffer(m_apiData.m_device, m_apiData.m_buffer, nullptr); if (m_apiData.m_deviceMemory && m_apiData.m_device && m_apiData.m_deviceMemoryOffset == uint64_t(-1)) vkFreeMemory(m_apiData.m_device, m_apiData.m_deviceMemory, nullptr); #if 0 m_apiData.m_accelerationStructure = {}; #endif m_apiData.m_buffer = {}; m_apiData.m_deviceMemory = {}; m_apiData.m_deviceAddress = {}; m_apiData.m_device = {}; } } bool Buffer::Create(Device* dev, uint64_t sizeInBytesOrNumberOfElements, Resource::Format format, Heap* heap, uint64_t heapOffsetInBytes, uint64_t heapAllocatedSizeInByte, Resource::BindFlags bindFlags, CpuAccess cpuAccess) { uint64_t sizeInBytes = sizeInBytesOrNumberOfElements; if (format != Resource::Format::Unknown) { sizeInBytes *= Resource::GetFormatBytesPerBlock(format); } if (heap != nullptr) { if (heap->m_cpuAccess != cpuAccess) { Log::Fatal(L"Cpu access flag was inconsistent."); return false; } if (is_set(bindFlags, BindFlags::Constant)) { Log::Fatal(L"Constant buffer isn't supported by placed resource."); return false; } if (is_set(m_bindFlags, Resource::BindFlags::Shared)) { Log::Fatal(L"Shared resource buffer isn't supported by placed resource."); return false; } } VkBufferCreateInfo bufferInfo = {}; bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; bufferInfo.flags = 0; bufferInfo.size = sizeInBytes; bufferInfo.usage = Resource::GetBufferUsageFlag(bindFlags); bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; bufferInfo.queueFamilyIndexCount = 0; bufferInfo.pQueueFamilyIndices = nullptr; if (vkCreateBuffer(dev->m_apiData.m_device, &bufferInfo, nullptr, &m_apiData.m_buffer) != VK_SUCCESS) { Log::Fatal(L"Faild to create vkBuffer."); return false; } // Get the required buffer size VkMemoryRequirements reqs; vkGetBufferMemoryRequirements(dev->m_apiData.m_device, m_apiData.m_buffer, &reqs); Device::VulkanDeviceMemoryType memType; if (cpuAccess == CpuAccess::Write) { SetGlobalState(ResourceState::State::GenericRead); memType = Device::VulkanDeviceMemoryType::Upload; } else if (cpuAccess == CpuAccess::Read && bindFlags == BindFlags::None) { SetGlobalState(ResourceState::State::CopyDest); memType = Device::VulkanDeviceMemoryType::Readback; } else { SetGlobalState(ResourceState::State::Common); if (is_set(bindFlags, BindFlags::AccelerationStructure)) SetGlobalState(ResourceState::State::AccelerationStructure); else if (is_set(bindFlags, BindFlags::UnorderedAccess)) SetGlobalState(ResourceState::State::UnorderedAccess); memType = Device::VulkanDeviceMemoryType::Default; } bool enableDeviceAddress = is_set(bindFlags, Resource::BindFlags::ShaderDeviceAddress); if (heap != nullptr) { if (reqs.size > heapAllocatedSizeInByte) { Log::Fatal(L"Heap allocation was insufficient."); return false; } if (heapAllocatedSizeInByte % reqs.alignment > 0 || heapOffsetInBytes % reqs.alignment > 0) { Log::Fatal(L"Heap allocation alignment was not meet the request."); return false; } if (vkBindBufferMemory(dev->m_apiData.m_device, m_apiData.m_buffer, heap->m_apiData.m_deviceMemory, heapOffsetInBytes) != VK_SUCCESS) { Log::Fatal(L"Faild to bind buffer memory."); return false; } m_apiData.m_deviceMemory = heap->m_apiData.m_deviceMemory; m_apiData.m_deviceMemoryOffset = heapOffsetInBytes; } else { if (!Resource::AllocateDeviceMemory(dev, memType, reqs.memoryTypeBits, enableDeviceAddress, reqs.size, &m_apiData.m_deviceMemory)) { Log::Fatal(L"Faild to allocate device memory."); return false; } if (vkBindBufferMemory(dev->m_apiData.m_device, m_apiData.m_buffer, m_apiData.m_deviceMemory, 0) != VK_SUCCESS) { Log::Fatal(L"Faild to bind buffer memory."); return false; } m_apiData.m_deviceMemoryOffset = uint64_t(-1); } m_apiData.m_device = dev->m_apiData.m_device; m_sizeInBytes = sizeInBytes; m_bindFlags = bindFlags; m_cpuAccess = cpuAccess; m_format = format; m_type = Type::Buffer; // set format and element count here for SRV/UAV. if (format != Resource::Format::Unknown) { m_elementCount = (uint32_t)sizeInBytesOrNumberOfElements; } else { m_elementCount = 0; } if (enableDeviceAddress) { VkBufferDeviceAddressInfo info = {}; info.sType = VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO; info.buffer = m_apiData.m_buffer; m_apiData.m_deviceAddress = vkGetBufferDeviceAddress(dev->m_apiData.m_device, &info); } else { m_apiData.m_deviceAddress = 0xFFFF'FFFF'FFFF'FFFFull; } #if 0 if (is_set(bindFlags, Resource::BindFlags::AccelerationStructure)) { VkAccelerationStructureCreateInfoKHR acInfo = {}; acInfo.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_KHR; acInfo.createFlags = VK_ACCELERATION_STRUCTURE_CREATE_DEVICE_ADDRESS_CAPTURE_REPLAY_BIT_KHR; acInfo.buffer = m_apiData.m_buffer; acInfo.offset = 0; acInfo.size = m_sizeInBytes; acInfo.type = VK_ACCELERATION_STRUCTURE_TYPE_GENERIC_KHR; acInfo.deviceAddress = m_apiData.m_deviceAddress; if (VK::vkCreateAccelerationStructureKHR(dev->m_apiData.m_device, &acInfo, nullptr, &m_apiData.m_accelerationStructure) != VK_SUCCESS) { Log::Fatal(L"Faild to create a acceleration structure."); return false; } } #endif return true; } bool Buffer::Create(Device* dev, uint64_t sizeInBytesOrNumberOfElements, Resource::Format format, Resource::BindFlags bindFlags, Buffer::CpuAccess cpuAccess) { return Create(dev, sizeInBytesOrNumberOfElements, format, nullptr, 0, 0, bindFlags, cpuAccess); } uint64_t Buffer::GetGpuAddress() const { return m_apiData.m_deviceAddress; } void* Buffer::Map(Device *dev, Buffer::MapType type, uint32_t subResourceIndex, uint64_t readRangeBegin, uint64_t readRangeEnd) { if (subResourceIndex > 0) { Log::Fatal(L"Mapping subresourceIndex != 0 isn't supported."); return nullptr; } void* mappedPtr = nullptr; VkDeviceSize offset = 0; VkDeviceSize size = VK_WHOLE_SIZE; switch (type) { case MapType::Read: case MapType::Write: offset = readRangeBegin; size = readRangeEnd - readRangeBegin; break; case MapType::WriteDiscard: default: break; }; if (m_apiData.m_deviceMemoryOffset != uint64_t(-1)) { offset += m_apiData.m_deviceMemoryOffset; if (type == MapType::WriteDiscard) { Log::Fatal(L"Placed resource doesn't support wirte discard map()."); return nullptr; } } if (vkMapMemory(dev->m_apiData.m_device, m_apiData.m_deviceMemory, offset, size, 0, &mappedPtr) != VK_SUCCESS) { Log::Fatal(L"Faild to map buffer."); return nullptr; } return mappedPtr; } void Buffer::Unmap(Device* dev, uint32_t subResourceIndex, uint64_t /*writeRangeBegin*/, uint64_t /*writeRangeEnd*/) { if (subResourceIndex > 0) { Log::Fatal(L"Mapping subresourceIndex != 0 isn't supported."); } vkUnmapMemory(dev->m_apiData.m_device, m_apiData.m_deviceMemory); } #endif /*************************************************************** * Abstraction for shader resource view ***************************************************************/ #if defined(GRAPHICS_API_D3D12) ShaderResourceView::~ShaderResourceView() { }; bool ShaderResourceView::InitNullView(Resource::Type type, bool isArray) { m_apiData = {}; m_isNullView = true; m_nullViewType = type; m_nullIsArray = isArray; auto GetSRVResourceDimension = [&]() -> D3D12_SRV_DIMENSION { using Type = Resource::Type; switch (type) { case Type::Buffer: return D3D12_SRV_DIMENSION_BUFFER; break; case Type::Texture1D: if (!isArray) return D3D12_SRV_DIMENSION_TEXTURE1D; else return D3D12_SRV_DIMENSION_TEXTURE1DARRAY; case Type::Texture2D: if (!isArray) return D3D12_SRV_DIMENSION_TEXTURE2D; else return D3D12_SRV_DIMENSION_TEXTURE2DARRAY; case Type::TextureCube: if (!isArray) return D3D12_SRV_DIMENSION_TEXTURECUBE; else return D3D12_SRV_DIMENSION_TEXTURECUBEARRAY; case Type::Texture3D: return D3D12_SRV_DIMENSION_TEXTURE3D; default: break; } Log::Fatal(L"Invalid UAV dimension detected."); return D3D12_SRV_DIMENSION(-1); }; m_apiData.m_desc = { DXGI_FORMAT_R8G8B8A8_UNORM, GetSRVResourceDimension(), D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING }; return true; } void ShaderResourceView::InitFromApiData(ID3D12Resource *resource, const D3D12_SHADER_RESOURCE_VIEW_DESC* desc) { m_apiData.m_resource = resource; m_apiData.m_desc = *desc; m_isNullView = false; } bool ShaderResourceView::Init(Device* /*dev*/, Texture *tex, uint32_t mostDetailedMip, uint32_t mipCount, uint32_t firstArraySlice, uint32_t arraySize) { auto GetSRVResourceDimension = [&]() -> D3D12_SRV_DIMENSION { using Type = Resource::Type; switch (tex->m_type) { case Type::Buffer: //return D3D12_SRV_DIMENSION_BUFFER; break; case Type::Texture1D: if (tex->m_arraySize == 1) return D3D12_SRV_DIMENSION_TEXTURE1D; else return D3D12_SRV_DIMENSION_TEXTURE1DARRAY; case Type::Texture2D: if (tex->m_arraySize == 1) return D3D12_SRV_DIMENSION_TEXTURE2D; else return D3D12_SRV_DIMENSION_TEXTURE2DARRAY; case Type::Texture2DMultisample: if (tex->m_arraySize == 1) return D3D12_SRV_DIMENSION_TEXTURE2DMS; else return D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY; case Type::TextureCube: if (tex->m_arraySize == 1) return D3D12_SRV_DIMENSION_TEXTURECUBE; else return D3D12_SRV_DIMENSION_TEXTURECUBEARRAY; case Type::Texture3D: return D3D12_SRV_DIMENSION_TEXTURE3D; default: break; } Log::Fatal(L"Invalid SRV dimension detected."); return D3D12_SRV_DIMENSION(-1); }; D3D12_SHADER_RESOURCE_VIEW_DESC desc = {Resource::GetDxgiFormat(tex->m_format), GetSRVResourceDimension(), D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING }; switch (desc.ViewDimension) { case D3D12_SRV_DIMENSION_TEXTURE1D: desc.Texture1D.MostDetailedMip = mostDetailedMip; desc.Texture1D.MipLevels = mipCount; desc.Texture1D.ResourceMinLODClamp = 0.f; break; case D3D12_SRV_DIMENSION_TEXTURE1DARRAY: desc.Texture1DArray.MostDetailedMip = mostDetailedMip; desc.Texture1DArray.MipLevels = mipCount; desc.Texture1DArray.ResourceMinLODClamp = 0.f; desc.Texture1DArray.FirstArraySlice = firstArraySlice; desc.Texture1DArray.ArraySize = arraySize; break; case D3D12_SRV_DIMENSION_TEXTURE2D: desc.Texture2D.MostDetailedMip = mostDetailedMip; desc.Texture2D.MipLevels = mipCount; desc.Texture2D.ResourceMinLODClamp = 0.f; break; case D3D12_SRV_DIMENSION_TEXTURE2DARRAY: desc.Texture2DArray.MostDetailedMip = mostDetailedMip; desc.Texture2DArray.MipLevels = mipCount; desc.Texture2DArray.ResourceMinLODClamp = 0.f; desc.Texture2DArray.FirstArraySlice = firstArraySlice; desc.Texture2DArray.ArraySize = arraySize; break; case D3D12_SRV_DIMENSION_TEXTURE2DMS: break; case D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY: desc.Texture2DMSArray.ArraySize = arraySize; desc.Texture2DMSArray.FirstArraySlice = firstArraySlice; break; case D3D12_SRV_DIMENSION_TEXTURE3D: desc.Texture3D.MostDetailedMip = mostDetailedMip; desc.Texture3D.MipLevels = mipCount; desc.Texture3D.ResourceMinLODClamp = 0.f; break; case D3D12_SRV_DIMENSION_TEXTURECUBE: desc.TextureCube.MipLevels = mipCount; desc.TextureCube.MostDetailedMip = mostDetailedMip; break; case D3D12_SRV_DIMENSION_TEXTURECUBEARRAY: desc.TextureCubeArray.First2DArrayFace = 0; desc.TextureCubeArray.NumCubes = arraySize; desc.TextureCubeArray.MipLevels = mipCount; desc.TextureCubeArray.MostDetailedMip = mostDetailedMip; break; default: Log::Fatal(L"Invalid SRV dimension detected."); return false; }; m_apiData.m_desc = desc; m_apiData.m_resource = tex->m_apiData.m_resource; m_isNullView = false; return true; } bool ShaderResourceView::Init(Device *dev, Texture *tex) { // SRV for entire resource. return Init(dev, tex, 0, tex->m_mipLevels, 0, tex->m_arraySize); } bool ShaderResourceView::Init(Device* /*dev*/, Buffer *buf, uint32_t firstElement, uint32_t elementCount) { D3D12_SHADER_RESOURCE_VIEW_DESC desc = {}; uint32_t bufferElementSize = 0; uint32_t bufferElementCount = 0; if (is_set(buf->m_bindFlags, Resource::BindFlags::AccelerationStructure)) { bufferElementSize = buf->m_format == Resource::Format::Unknown ? 1 : Resource::GetFormatBytesPerBlock(buf->m_format); bufferElementCount = buf->m_elementCount; desc.ViewDimension = D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE; desc.Format = DXGI_FORMAT_UNKNOWN; desc.RaytracingAccelerationStructure.Location = buf->GetGpuAddress() + (uint64_t)bufferElementSize * (uint64_t)firstElement; } else if (buf->m_format != Resource::Format::Unknown) { // typed bufferElementSize = Resource::GetFormatBytesPerBlock(buf->m_format); bufferElementCount = buf->m_elementCount; desc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; desc.Format = Resource::GetDxgiFormat(buf->m_format); } else if (buf->m_structSizeInBytes > 0) { // structured bufferElementSize = buf->m_structSizeInBytes; bufferElementCount = buf->m_elementCount; desc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; desc.Format = DXGI_FORMAT_UNKNOWN; desc.Buffer.StructureByteStride = buf->m_structSizeInBytes; } else { // raw bufferElementSize = sizeof(uint32_t); bufferElementCount = (uint32_t)(buf->m_sizeInBytes / sizeof(uint32_t)); desc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; desc.Format = DXGI_FORMAT_R32_TYPELESS; desc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; } if (elementCount == 0xFFFFFFFF) { // to the last element. elementCount = bufferElementCount - firstElement; } // check range. assert((firstElement + elementCount) <= bufferElementCount); assert(bufferElementSize > 0); // set element range for buffer view. if (desc.ViewDimension == D3D12_SRV_DIMENSION_BUFFER) { desc.Buffer.FirstElement = firstElement; desc.Buffer.NumElements = elementCount; } desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; m_apiData.m_desc = desc; m_apiData.m_resource = buf->m_apiData.m_resource; m_isNullView = false; return true; } bool ShaderResourceView::Init(Device *dev, Buffer *buf) { return Init(dev, buf, 0, 0xFFFFFFFF); } #elif defined(GRAPHICS_API_VK) ShaderResourceView::~ShaderResourceView() { if (m_apiData.m_device && m_apiData.m_typedBufferView) { vkDestroyBufferView(m_apiData.m_device, m_apiData.m_typedBufferView, nullptr); } if (m_apiData.m_device && m_apiData.m_imageView) { vkDestroyImageView(m_apiData.m_device, m_apiData.m_imageView, nullptr); } if (m_apiData.m_device && m_apiData.m_accelerationStructure) { VK::vkDestroyAccelerationStructureKHR(m_apiData.m_device, m_apiData.m_accelerationStructure, nullptr); } m_apiData = {}; } void ShaderResourceView::InitFromApiData(VkBuffer rawBuffer, uint64_t rawOffsetInBytes, uint64_t rawSizeInBytes) { m_apiData.m_device = {}; m_apiData.m_rawBuffer = rawBuffer; m_apiData.m_isTypedBufferView = false; m_apiData.m_typedBufferView = {}; m_apiData.m_imageView = {}; m_apiData.m_rawOffsetInBytes = rawOffsetInBytes; m_apiData.m_rawSizeInBytes = rawSizeInBytes; m_isNullView = false; } bool ShaderResourceView::InitFromApiData(Device *dev, VkBuffer typedBuffer, VkFormat nativeFmt, uint64_t offsetInBytes, uint64_t sizeInBytes) { // Create views for TypedBuffers Resource::Format fmt = Resource::GetResourceFormat(nativeFmt); uint32_t bufferElementSize = Resource::GetFormatBytesPerBlock(fmt); m_apiData.m_rawOffsetInBytes = offsetInBytes; m_apiData.m_rawSizeInBytes = sizeInBytes; if (sizeInBytes % bufferElementSize != 0) { Log::Fatal(L"Faild to init SRV. Buffer size was not a multiple of element size. ElmSize:%d BufSize:%d", bufferElementSize, sizeInBytes); return false; } VkBufferViewCreateInfo cInfo = {}; cInfo.sType = VK_STRUCTURE_TYPE_BUFFER_VIEW_CREATE_INFO; cInfo.buffer = typedBuffer; cInfo.offset = m_apiData.m_rawOffsetInBytes; cInfo.range = m_apiData.m_rawSizeInBytes; cInfo.format = nativeFmt; //assert(m_apiData.m_rawOffsetInBytes % 16 == 0); if (vkCreateBufferView(dev->m_apiData.m_device, &cInfo, nullptr, &m_apiData.m_typedBufferView) != VK_SUCCESS) { Log::Fatal(L"Failed to create a typed buffer view"); return false; } m_apiData.m_isTypedBufferView = true; m_apiData.m_device = dev->m_apiData.m_device; m_isNullView = false; return true; }; bool ShaderResourceView::InitFromApiData(Device* dev, VkImage image, VkImageViewType imageType, VkFormat fmt, VkImageAspectFlags aspectMask, uint32_t baseMipLevel, uint32_t mipCount, uint32_t baseArrayLayer, uint32_t layerCount) { VkImageViewCreateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; info.image = image; info.viewType = imageType; info.format = fmt; info.subresourceRange.aspectMask = aspectMask; info.subresourceRange.baseMipLevel = baseMipLevel; info.subresourceRange.levelCount = mipCount; info.subresourceRange.baseArrayLayer = baseArrayLayer; info.subresourceRange.layerCount = layerCount; if (vkCreateImageView(dev->m_apiData.m_device, &info, nullptr, &m_apiData.m_imageView) != VK_SUCCESS) { Log::Fatal(L"Failed to create a image view (SRV)"); return false; } m_apiData.m_device = dev->m_apiData.m_device; m_isNullView = false; return true; } bool ShaderResourceView::InitNullView(Device* /*dev*/, Resource::Type type, Resource::Format fmt, bool isArray) { m_isNullView = true; m_nullViewType = type; m_nullIsArray = isArray; m_nullIsTypedBuffer = (type == Resource::Type::Buffer && fmt == Resource::Format::Unknown); return true; }; bool ShaderResourceView::Init(Device* dev, Texture* tex, uint32_t mostDetailedMip, uint32_t mipCount, uint32_t firstArraySlice, uint32_t arraySize) { VkImageViewCreateInfo info = {}; auto getViewType = [](Resource::Type type, bool isArray) -> VkImageViewType { switch (type) { case Resource::Type::Texture1D: return isArray ? VK_IMAGE_VIEW_TYPE_1D_ARRAY : VK_IMAGE_VIEW_TYPE_1D; case Resource::Type::Texture2D: case Resource::Type::Texture2DMultisample: return isArray ? VK_IMAGE_VIEW_TYPE_2D_ARRAY : VK_IMAGE_VIEW_TYPE_2D; case Resource::Type::Texture3D: if (isArray) break; return VK_IMAGE_VIEW_TYPE_3D; case Resource::Type::TextureCube: return isArray ? VK_IMAGE_VIEW_TYPE_CUBE_ARRAY : VK_IMAGE_VIEW_TYPE_CUBE; default: break; } Log::Fatal(L"Unsupported resource type for a shader resource view."); return VkImageViewType(-1); }; info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; info.image = tex->m_apiData.m_image; info.viewType = getViewType(tex->m_type, tex->m_arraySize > 1); info.format = Resource::GetVkFormat(tex->m_format); info.subresourceRange.aspectMask = Resource::GetVkImageAspectFlags(tex->m_format, true); info.subresourceRange.baseMipLevel = mostDetailedMip; info.subresourceRange.levelCount = mipCount; if (tex->m_type == Resource::Type::TextureCube) { firstArraySlice *= 6; arraySize *= 6; } info.subresourceRange.baseArrayLayer = firstArraySlice; info.subresourceRange.layerCount = arraySize; if (vkCreateImageView(dev->m_apiData.m_device, &info, nullptr, &m_apiData.m_imageView) != VK_SUCCESS) { Log::Fatal(L"Failed to create a image view (SRV)"); return false; } m_apiData.m_device = dev->m_apiData.m_device; m_isNullView = false; return true; } bool ShaderResourceView::Init(Device* dev, Texture* tex) { return Init(dev, tex, 0, tex->m_mipLevels, 0, tex->m_arraySize); } bool ShaderResourceView::Init(Device* dev, Buffer* buf, uint32_t firstElement, uint32_t elementCount) { uint32_t bufferElementSize = buf->m_format == Resource::Format::Unknown ? 1 : Resource::GetFormatBytesPerBlock(buf->m_format); m_apiData.m_rawOffsetInBytes = (uint64_t)firstElement * bufferElementSize; m_apiData.m_rawSizeInBytes = elementCount == 0xFFFFFFFF ? buf->m_sizeInBytes : (uint64_t)elementCount * bufferElementSize; //assert(m_apiData.m_rawOffsetInBytes % 16 == 0); if (is_set(buf->m_bindFlags, Resource::BindFlags::AccelerationStructure)) { // create an AS for the region. VkAccelerationStructureCreateInfoKHR acInfo = {}; acInfo.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_KHR; #if 0 acInfo.createFlags = VK_ACCELERATION_STRUCTURE_CREATE_DEVICE_ADDRESS_CAPTURE_REPLAY_BIT_KHR; #endif acInfo.buffer = buf->m_apiData.m_buffer; acInfo.offset = m_apiData.m_rawOffsetInBytes; acInfo.size = m_apiData.m_rawSizeInBytes; acInfo.type = VK_ACCELERATION_STRUCTURE_TYPE_GENERIC_KHR; #if 0 acInfo.deviceAddress = buf->m_apiData.m_deviceAddress; #endif if (VK::vkCreateAccelerationStructureKHR(dev->m_apiData.m_device, &acInfo, nullptr, &m_apiData.m_accelerationStructure) != VK_SUCCESS) { Log::Fatal(L"Faild to create a acceleration structure."); return false; } m_apiData.m_isTypedBufferView = false; m_apiData.m_device = dev->m_apiData.m_device; } else { if (buf->m_format == Resource::Format::Unknown) { // Raw buffer don't need a view. m_apiData.m_isTypedBufferView = false; m_apiData.m_device = {}; m_apiData.m_rawBuffer = buf->m_apiData.m_buffer; } else { // Create a view for TypedBuffers VkBufferViewCreateInfo cInfo = {}; cInfo.sType = VK_STRUCTURE_TYPE_BUFFER_VIEW_CREATE_INFO; cInfo.buffer = buf->m_apiData.m_buffer; cInfo.offset = m_apiData.m_rawOffsetInBytes; cInfo.range = m_apiData.m_rawSizeInBytes; cInfo.format = Resource::GetVkFormat(buf->m_format); if (vkCreateBufferView(dev->m_apiData.m_device, &cInfo, nullptr, &m_apiData.m_typedBufferView) != VK_SUCCESS) { Log::Fatal(L"Failed to create a typed buffer view"); return false; } m_apiData.m_isTypedBufferView = true; m_apiData.m_device = dev->m_apiData.m_device; } } m_isNullView = false; return true; } bool ShaderResourceView::Init(Device *dev, Buffer* buf) { return Init(dev, buf, 0, 0xFFFFFFFF); } #endif /*************************************************************** * Abstraction for unordered access view ***************************************************************/ #if defined(GRAPHICS_API_D3D12) UnorderedAccessView::~UnorderedAccessView() { }; void UnorderedAccessView::InitFromApiData(ID3D12Resource *resource, const D3D12_UNORDERED_ACCESS_VIEW_DESC* desc) { m_apiData.m_resource = resource; m_apiData.m_desc = *desc; m_isNullView = false; } bool UnorderedAccessView::InitNullView(Resource::Type type, bool isArray) { m_apiData = {}; m_isNullView = true; m_nullViewType = type; m_nullIsArray = isArray; auto GetUAVResourceDimension = [&]() -> D3D12_UAV_DIMENSION { using Type = Resource::Type; switch (type) { case Type::Buffer: return D3D12_UAV_DIMENSION_BUFFER; break; case Type::Texture1D: if (! isArray) return D3D12_UAV_DIMENSION_TEXTURE1D; else return D3D12_UAV_DIMENSION_TEXTURE1DARRAY; case Type::Texture2D: if (! isArray) return D3D12_UAV_DIMENSION_TEXTURE2D; else return D3D12_UAV_DIMENSION_TEXTURE2DARRAY; case Type::TextureCube: return D3D12_UAV_DIMENSION_TEXTURE2DARRAY; case Type::Texture3D: return D3D12_UAV_DIMENSION_TEXTURE3D; default: break; } Log::Fatal(L"Invalid UAV dimension detected."); return D3D12_UAV_DIMENSION(-1); }; m_apiData.m_desc = { DXGI_FORMAT_R8G8B8A8_UNORM, GetUAVResourceDimension() }; return true; } bool UnorderedAccessView::Init(Device* /*dev*/, Texture *tex, uint32_t mipLevel, uint32_t firstArraySlice, uint32_t arraySize) { auto GetUAVResourceDimension = [&]() -> D3D12_UAV_DIMENSION { using Type = Resource::Type; switch (tex->m_type) { case Type::Buffer: return D3D12_UAV_DIMENSION_BUFFER; break; case Type::Texture1D: if (tex->m_arraySize == 1) return D3D12_UAV_DIMENSION_TEXTURE1D; else return D3D12_UAV_DIMENSION_TEXTURE1DARRAY; case Type::Texture2D: if (tex->m_arraySize == 1) return D3D12_UAV_DIMENSION_TEXTURE2D; else return D3D12_UAV_DIMENSION_TEXTURE2DARRAY; case Type::TextureCube: return D3D12_UAV_DIMENSION_TEXTURE2DARRAY; case Type::Texture3D: return D3D12_UAV_DIMENSION_TEXTURE3D; default: break; } Log::Fatal(L"Invalid UAV dimension detected."); return D3D12_UAV_DIMENSION(-1); }; uint32_t arrayMultiplier = (tex->m_type == Resource::Type::TextureCube) ? 6 : 1; D3D12_UNORDERED_ACCESS_VIEW_DESC desc = { Resource::GetDxgiFormat(tex->m_format), GetUAVResourceDimension() }; switch (desc.ViewDimension) { case D3D12_UAV_DIMENSION_TEXTURE1D: desc.Texture1D.MipSlice = mipLevel; break; case D3D12_UAV_DIMENSION_TEXTURE1DARRAY: desc.Texture1DArray.MipSlice = mipLevel; desc.Texture1DArray.FirstArraySlice = firstArraySlice; desc.Texture1DArray.ArraySize = arraySize; break; case D3D12_UAV_DIMENSION_TEXTURE2D: desc.Texture2D.MipSlice = mipLevel; break; case D3D12_UAV_DIMENSION_TEXTURE2DARRAY: desc.Texture2DArray.MipSlice = mipLevel; desc.Texture2DArray.FirstArraySlice = firstArraySlice * arrayMultiplier; desc.Texture2DArray.ArraySize = arraySize * arrayMultiplier; break; case D3D12_UAV_DIMENSION_TEXTURE3D: desc.Texture3D.MipSlice = mipLevel; desc.Texture3D.FirstWSlice = 0; desc.Texture3D.WSize = std::max(1U, tex->m_depth >> mipLevel); break; default: Log::Fatal(L"Invalid UAV dimension detected."); return false; } m_apiData.m_desc = desc; m_apiData.m_resource = tex->m_apiData.m_resource; m_isNullView = false; return true; } bool UnorderedAccessView::Init(Device *dev, Texture *tex) { return Init(dev, tex, 0, 0, tex->m_arraySize); } bool UnorderedAccessView::Init(Device* /*dev*/, Buffer *buf, uint32_t firstElement, uint32_t elementCount) { D3D12_UNORDERED_ACCESS_VIEW_DESC desc = {}; uint32_t bufferElementSize = 0; uint32_t bufferElementCount = 0; if (is_set(buf->m_bindFlags, Resource::BindFlags::AccelerationStructure)) { // In D3D12, there is no UAV for AS. bufferElementSize = buf->m_format == Resource::Format::Unknown ? 1 : Resource::GetFormatBytesPerBlock(buf->m_format); bufferElementCount = buf->m_elementCount; desc.ViewDimension = (D3D12_UAV_DIMENSION)-1; desc.Format = DXGI_FORMAT_UNKNOWN; } else if (buf->m_format != Resource::Format::Unknown) { // typed bufferElementSize = Resource::GetFormatBytesPerBlock(buf->m_format); bufferElementCount = buf->m_elementCount; desc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; desc.Format = Resource::GetDxgiFormat(buf->m_format); } else if (buf->m_structSizeInBytes > 0) { bufferElementSize = buf->m_structSizeInBytes; bufferElementCount = buf->m_elementCount; desc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; desc.Format = DXGI_FORMAT_UNKNOWN; desc.Buffer.StructureByteStride = buf->m_structSizeInBytes; } else { bufferElementSize = sizeof(uint32_t); bufferElementCount = (uint32_t)(buf->m_sizeInBytes / sizeof(uint32_t)); desc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; desc.Format = DXGI_FORMAT_R32_TYPELESS; desc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; } if (elementCount == 0xFFFFFFFF) { // to the last element. elementCount = bufferElementCount - firstElement; } // check range. assert((firstElement + elementCount) <= bufferElementCount); assert(bufferElementSize > 0); if (desc.ViewDimension == D3D12_UAV_DIMENSION_BUFFER) { desc.Buffer.FirstElement = firstElement; desc.Buffer.NumElements = elementCount; } m_apiData.m_desc = desc; m_apiData.m_resource = buf->m_apiData.m_resource; m_isNullView = false; return true; } bool UnorderedAccessView::Init(Device *dev, Buffer *buf) { return Init(dev, buf, 0, 0xFFFFFFFF); } #elif defined(GRAPHICS_API_VK) UnorderedAccessView::~UnorderedAccessView() { if (m_apiData.m_device && m_apiData.m_typedBufferView) { vkDestroyBufferView(m_apiData.m_device, m_apiData.m_typedBufferView, nullptr); } if (m_apiData.m_device && m_apiData.m_imageView) { vkDestroyImageView(m_apiData.m_device, m_apiData.m_imageView, nullptr); } if (m_apiData.m_device && m_apiData.m_accelerationStructure) { VK::vkDestroyAccelerationStructureKHR(m_apiData.m_device, m_apiData.m_accelerationStructure, nullptr); } m_apiData = {}; } bool UnorderedAccessView::InitFromApiData(Device* dev, VkImage image, VkImageViewType imageType, VkFormat fmt, VkImageAspectFlags aspectMask, uint32_t baseMipLevel, uint32_t baseArrayLayer, uint32_t layerCount) { VkImageViewCreateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; info.image = image; info.viewType = imageType; info.format = fmt; info.subresourceRange.aspectMask = aspectMask; info.subresourceRange.baseMipLevel = baseMipLevel; info.subresourceRange.levelCount = 1; info.subresourceRange.baseArrayLayer = baseArrayLayer; info.subresourceRange.layerCount = layerCount; if (vkCreateImageView(dev->m_apiData.m_device, &info, nullptr, &m_apiData.m_imageView) != VK_SUCCESS) { Log::Fatal(L"Failed to create a image view (UAV)"); return false; } m_apiData.m_device = dev->m_apiData.m_device; m_isNullView = false; return true; } bool UnorderedAccessView::InitNullView(Device* /*dev*/, Resource::Type type, Resource::Format fmt, bool isArray) { m_isNullView = true; m_nullViewType = type; m_nullIsArray = isArray; m_nullIsTypedBuffer = (type == Resource::Type::Buffer && fmt == Resource::Format::Unknown); return true; } bool UnorderedAccessView::Init(Device* dev, Texture* tex, uint32_t mipLevel, uint32_t firstArraySlice, uint32_t arraySize) { VkImageViewCreateInfo info = {}; auto getViewType = [](Resource::Type type, bool isArray) -> VkImageViewType { switch (type) { case Resource::Type::Texture1D: return isArray ? VK_IMAGE_VIEW_TYPE_1D_ARRAY : VK_IMAGE_VIEW_TYPE_1D; case Resource::Type::Texture2D: case Resource::Type::Texture2DMultisample: return isArray ? VK_IMAGE_VIEW_TYPE_2D_ARRAY : VK_IMAGE_VIEW_TYPE_2D; case Resource::Type::Texture3D: if (isArray) break; return VK_IMAGE_VIEW_TYPE_3D; case Resource::Type::TextureCube: return isArray ? VK_IMAGE_VIEW_TYPE_CUBE_ARRAY : VK_IMAGE_VIEW_TYPE_CUBE; default: break; } Log::Fatal(L"Unsupported resource type for a shader resource view."); return VkImageViewType(-1); }; info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; info.image = tex->m_apiData.m_image; info.viewType = getViewType(tex->m_type, tex->m_arraySize > 1); info.format = Resource::GetVkFormat(tex->m_format); info.subresourceRange.aspectMask = Resource::GetVkImageAspectFlags(tex->m_format, true); info.subresourceRange.baseMipLevel = mipLevel; info.subresourceRange.levelCount = 1;; if (tex->m_type == Resource::Type::TextureCube) { firstArraySlice *= 6; arraySize *= 6; } info.subresourceRange.baseArrayLayer = firstArraySlice; info.subresourceRange.layerCount = arraySize; if (vkCreateImageView(dev->m_apiData.m_device, &info, nullptr, &m_apiData.m_imageView) != VK_SUCCESS) { Log::Fatal(L"Failed to create a image view (UAV)"); return false; } m_apiData.m_device = dev->m_apiData.m_device; m_isNullView = false; return true; } bool UnorderedAccessView::Init(Device* dev, Texture* tex) { return Init(dev, tex, 0, 0, tex->m_arraySize); } bool UnorderedAccessView::Init(Device* dev, Buffer* buf, uint32_t firstElement, uint32_t elementCount) { #if 0 if (buf->GetGlobalState() == ResourceState::State::AccelerationStructure) { Log::Fatal(L"AccelerationStructure detected. nee to check SDK source code to support it."); return false; } #endif uint32_t bufferElementSize = buf->m_format == Resource::Format::Unknown ? 1 : Resource::GetFormatBytesPerBlock(buf->m_format); m_apiData.m_rawOffsetInBytes = (uint64_t)firstElement * bufferElementSize; m_apiData.m_rawSizeInBytes = elementCount == 0xFFFFFFFF ? buf->m_sizeInBytes : (uint64_t)elementCount * bufferElementSize; //assert(m_apiData.m_rawOffsetInBytes % 16 == 0); if (is_set(buf->m_bindFlags, Resource::BindFlags::AccelerationStructure)) { // create an AS for the region. VkAccelerationStructureCreateInfoKHR acInfo = {}; acInfo.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_KHR; #if 0 acInfo.createFlags = VK_ACCELERATION_STRUCTURE_CREATE_DEVICE_ADDRESS_CAPTURE_REPLAY_BIT_KHR; #endif acInfo.buffer = buf->m_apiData.m_buffer; acInfo.offset = m_apiData.m_rawOffsetInBytes; acInfo.size = m_apiData.m_rawSizeInBytes; acInfo.type = VK_ACCELERATION_STRUCTURE_TYPE_GENERIC_KHR; #if 0 acInfo.deviceAddress = buf->m_apiData.m_deviceAddress; #endif if (VK::vkCreateAccelerationStructureKHR(dev->m_apiData.m_device, &acInfo, nullptr, &m_apiData.m_accelerationStructure) != VK_SUCCESS) { Log::Fatal(L"Faild to create a acceleration structure."); return false; } m_apiData.m_isTypedBufferView = false; m_apiData.m_device = dev->m_apiData.m_device; } else { if (buf->m_format == Resource::Format::Unknown) { // raw buffer don't need a view. m_apiData.m_isTypedBufferView = false; m_apiData.m_device = {}; m_apiData.m_rawBuffer = buf->m_apiData.m_buffer; } else { // Create views for TypedBuffers VkBufferViewCreateInfo cInfo = {}; cInfo.sType = VK_STRUCTURE_TYPE_BUFFER_VIEW_CREATE_INFO; cInfo.buffer = buf->m_apiData.m_buffer; cInfo.offset = m_apiData.m_rawOffsetInBytes; cInfo.range = m_apiData.m_rawSizeInBytes; cInfo.format = Resource::GetVkFormat(buf->m_format); if (vkCreateBufferView(dev->m_apiData.m_device, &cInfo, nullptr, &m_apiData.m_typedBufferView) != VK_SUCCESS) { Log::Fatal(L"Failed to create a typed buffer view"); return false; } m_apiData.m_isTypedBufferView = true; m_apiData.m_device = dev->m_apiData.m_device; } } m_isNullView = false; return true; } bool UnorderedAccessView::Init(Device* dev, Buffer* buf) { return Init(dev, buf, 0, 0xFFFFFFFF); } #endif /*************************************************************** * Abstraction for constant buffer view ***************************************************************/ #if defined(GRAPHICS_API_D3D12) bool ConstantBufferView::Init(Buffer* buf, uint64_t offsetInBytes, uint32_t sizeInBytes) { D3D12_CONSTANT_BUFFER_VIEW_DESC desc = {}; desc.BufferLocation = buf->m_apiData.m_resource->GetGPUVirtualAddress(); if (ALIGN((uint64_t)D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT, offsetInBytes) != offsetInBytes || ALIGN((uint32_t)D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT, sizeInBytes) != sizeInBytes) { Log::Fatal(L"Faild to init CBV. Alignment violation detected."); return false; } if (offsetInBytes + (uint64_t)sizeInBytes > buf->m_sizeInBytes) { Log::Fatal(L"Faild to init CBV. CBV range exceeded the buffer range."); return false; } desc.BufferLocation += offsetInBytes; desc.SizeInBytes = sizeInBytes; m_apiData.m_desc = desc; m_apiData.m_resource = buf->m_apiData.m_resource; return true; } bool ConstantBufferView::Init(Buffer* buf) { return Init(buf, 0, (uint32_t)buf->m_sizeInBytes); } #elif defined(GRAPHICS_API_VK) bool ConstantBufferView::Init(Buffer* buf, uint64_t offsetInBytes, uint32_t sizeInBytes) { if (Resource::ConstantBufferPlacementAlignment(offsetInBytes) != offsetInBytes || Resource::ConstantBufferPlacementAlignment(sizeInBytes) != sizeInBytes) { Log::Fatal(L"Faild to init CBV. Alignment violation detected."); return false; } if (offsetInBytes + (uint64_t)sizeInBytes > buf->m_sizeInBytes) { Log::Fatal(L"Faild to init CBV. CBV range exceeded the buffer range."); return false; } m_apiData.m_buffer = buf->m_apiData.m_buffer; m_apiData.m_offsetInBytes = offsetInBytes; m_apiData.m_sizeInBytes = sizeInBytes; return true; } bool ConstantBufferView::Init(Buffer* buf) { return Init(buf, 0, (uint32_t)buf->m_sizeInBytes); } #endif /*************************************************************** * CommandList in D3D12 * CommandBuffer in VK ***************************************************************/ #if defined(GRAPHICS_API_D3D12) CommandList::~CommandList() { m_apiData = {}; } void CommandList::SetName(const std::wstring& str) { SetNameInternal(m_apiData.m_commandList, str.c_str()); } void CommandList::ClearState() { m_apiData.m_commandList->ClearState(nullptr); } bool CommandList::InitFromAPIData(ID3D12GraphicsCommandList4* cmdList, ID3D12DebugCommandList1* dbgCmdList) { if (cmdList == nullptr) return false; m_apiData.m_commandList = cmdList; m_apiData.m_debugCommandList = dbgCmdList; return true; } bool CommandList::SetDescriptorHeap(DescriptorHeap* heap) { std::vector<ID3D12DescriptorHeap*> descs; for (auto& h : heap->m_apiData.m_heaps) { if (h.m_descHeap != nullptr) { descs.push_back(h.m_descHeap); } } m_apiData.m_commandList->SetDescriptorHeaps((uint32_t)descs.size(), descs.data()); return true; } bool CommandList::HasDebugCommandList() const { return m_apiData.m_debugCommandList != nullptr; } bool CommandList::AssertResourceStates(Resource** resArr, SubresourceRange* subresourceArr, size_t numRes, ResourceState::State* statesToAssert) { if (m_apiData.m_debugCommandList) { for (size_t i = 0; i < numRes; ++i) { Resource* r = resArr[i]; if (subresourceArr || r->m_globalState.IsTrackingPerSubresource()) { assert(Resource::IsTexture(r->m_type)); Texture* t = (Texture*)r; const SubresourceRange& range = subresourceArr ? subresourceArr[i] : SubresourceRange(0, (uint8_t)t->m_arraySize, 0, (uint8_t)t->m_mipLevels); for (uint8_t arraySlice = range.baseArrayLayer; arraySlice < range.baseArrayLayer + range.arrayLayerCount; ++arraySlice) { for (uint8_t mipLevel = range.baseMipLevel; mipLevel < range.baseMipLevel + range.mipLevelCount; ++mipLevel) { uint32_t subresurceIdx = SubresourceRange::CalcSubresource(mipLevel, arraySlice, t->m_mipLevels); m_apiData.m_debugCommandList->AssertResourceState(r->m_apiData.m_resource, subresurceIdx, ResourceState::GetD3D12ResourceState(statesToAssert[i])); } } } } } return true; } #if defined(GRAPHICS_API_D3D12) // Handy shortcut for D3D12 buffers bool CommandList::AssertResourceStates(ID3D12Resource** resArr, size_t numRes, const D3D12_RESOURCE_STATES* statesToAssert) { if (m_apiData.m_debugCommandList) { for (size_t i = 0; i < numRes; ++i) { m_apiData.m_debugCommandList->AssertResourceState(resArr[i], D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, statesToAssert[i]); } } return true; } #endif bool CommandList::ResourceTransitionBarrier(Resource** resArr, SubresourceRange* subresourceArr, size_t numRes, ResourceState::State* desiredStates) { std::vector<D3D12_RESOURCE_BARRIER> bArr; D3D12_RESOURCE_BARRIER bWrk = { D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, D3D12_RESOURCE_BARRIER_FLAG_NONE, }; for (size_t i = 0; i < numRes; ++i) { Resource* r = resArr[i]; if (subresourceArr || r->m_globalState.IsTrackingPerSubresource()) { assert(Resource::IsTexture(r->m_type)); Texture* t = (Texture*)r; const SubresourceRange& range = subresourceArr ? subresourceArr[i] : SubresourceRange(0, (uint8_t)t->m_arraySize, 0, (uint8_t)t->m_mipLevels); for (uint8_t arraySlice = range.baseArrayLayer; arraySlice < range.baseArrayLayer + range.arrayLayerCount; ++arraySlice) { for (uint8_t mipLevel = range.baseMipLevel; mipLevel < range.baseMipLevel + range.mipLevelCount; ++mipLevel) { uint32_t subresurceIdx = SubresourceRange::CalcSubresource(mipLevel, arraySlice, t->m_mipLevels); if (r->GetGlobalState(subresurceIdx) != desiredStates[i]) { bWrk.Transition.pResource = r->m_apiData.m_resource; bWrk.Transition.Subresource = subresurceIdx; bWrk.Transition.StateBefore = ResourceState::GetD3D12ResourceState(r->GetGlobalState(subresurceIdx)); bWrk.Transition.StateAfter = ResourceState::GetD3D12ResourceState(desiredStates[i]); // This happens when transitioning between ShaderResource and NonPixelShader if (bWrk.Transition.StateBefore != bWrk.Transition.StateAfter) bArr.push_back(bWrk); r->SetGlobalState(desiredStates[i], subresurceIdx); } } } } else { if (r->GetGlobalState() != desiredStates[i]) { bWrk.Transition.pResource = r->m_apiData.m_resource; bWrk.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; bWrk.Transition.StateBefore = ResourceState::GetD3D12ResourceState(r->GetGlobalState()); bWrk.Transition.StateAfter = ResourceState::GetD3D12ResourceState(desiredStates[i]); // This happens when transitioning between ShaderResource and NonPixelShader if (bWrk.Transition.StateBefore != bWrk.Transition.StateAfter) bArr.push_back(bWrk); r->SetGlobalState(desiredStates[i]); } } } if (bArr.size() > 0) { D3D12_RESOURCE_BARRIER* data = bArr.data(); uint32_t size = (uint32_t)bArr.size(); m_apiData.m_commandList->ResourceBarrier(size, data); } return true; } bool CommandList::ResourceTransitionBarrier(Resource** resArr, size_t numRes, ResourceState::State* desiredStates) { return ResourceTransitionBarrier(resArr, nullptr, numRes, desiredStates); } bool CommandList::ResourceUAVBarrier(Resource** resArr, size_t numRes) { std::vector<D3D12_RESOURCE_BARRIER> bArr; D3D12_RESOURCE_BARRIER bWrk = { D3D12_RESOURCE_BARRIER_TYPE_UAV, D3D12_RESOURCE_BARRIER_FLAG_NONE, }; for (size_t i = 0; i < numRes; ++i) { Resource* r = resArr[i]; bWrk.UAV.pResource = r->m_apiData.m_resource; bArr.push_back(bWrk); } if (bArr.size() > 0) { m_apiData.m_commandList->ResourceBarrier((uint32_t)bArr.size(), &bArr[0]); } return true; } bool CommandList::CopyTextureSingleMip(Device* dev, uint32_t mipIndex, Texture* dstTex, Buffer* srcUpBuf) { D3D12_RESOURCE_DESC desc = {}; desc.MipLevels = (UINT16)dstTex->m_mipLevels; desc.Format = Resource::GetDxgiFormat(dstTex->m_format); desc.Width = dstTex->m_width; desc.Height = dstTex->m_height; desc.Flags = Resource::GetD3D12ResourceFlags(dstTex->m_bindFlags); desc.SampleDesc.Count = dstTex->m_sampleCount; desc.SampleDesc.Quality = 0; desc.Dimension = Resource::GetResourceDimension(dstTex->m_type); desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; desc.Alignment = 0; if (dstTex->m_type == Resource::Type::TextureCube) { desc.DepthOrArraySize = (UINT16)(dstTex->m_arraySize * 6); } else if (dstTex->m_type == Resource::Type::Texture3D) { desc.DepthOrArraySize = (UINT16)dstTex->m_depth; } else { desc.DepthOrArraySize = (UINT16)dstTex->m_arraySize; } assert(desc.Width > 0 && desc.Height > 0); assert(desc.MipLevels > 0 && desc.DepthOrArraySize > 0 && desc.SampleDesc.Count > 0); D3D12_PLACED_SUBRESOURCE_FOOTPRINT uploadBufferFootprint; UINT numRows; UINT64 rowSizeInBytes, totalBytes; dev->m_apiData.m_device->GetCopyableFootprints(&desc, mipIndex, 1, 0, &uploadBufferFootprint, &numRows, &rowSizeInBytes, &totalBytes); if (totalBytes != srcUpBuf->m_sizeInBytes) { Log::Fatal(L"Upload staging buffer didn't fit to the destination texture."); return false; } // upload buffer is always generic read state. Resource* resArr[1] = { dstTex }; ResourceState::State desiredStatesBefore[1] = { ResourceState::State::CopyDest }; ResourceState::State desiredStatesAfter[1] = { ResourceState::State::ShaderResource }; ResourceTransitionBarrier(resArr, 1, desiredStatesBefore); D3D12_TEXTURE_COPY_LOCATION uploadBufLocation = { srcUpBuf->m_apiData.m_resource, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, uploadBufferFootprint }; D3D12_TEXTURE_COPY_LOCATION defaultBufLocation = { dstTex->m_apiData.m_resource, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, 0 }; m_apiData.m_commandList->CopyTextureRegion(&defaultBufLocation, 0, 0, 0, &uploadBufLocation, nullptr); ResourceTransitionBarrier(resArr, 1, desiredStatesAfter); return true; } void CommandList::CopyBufferRegion(Buffer* dst, uint64_t dstOffset, Buffer* src, uint64_t srcOffset, uint64_t copySizeInBytes) { m_apiData.m_commandList->CopyBufferRegion(dst->m_apiData.m_resource, dstOffset, src->m_apiData.m_resource, srcOffset, copySizeInBytes); } void CommandList::CopyTextureRegion(Texture* dst, Texture* src) { constexpr uint32_t kNumBuf = 2; GraphicsAPI::Resource* dstBufArr[kNumBuf] = { dst, src }; GraphicsAPI::ResourceState::State desiredStateArr[kNumBuf] = { GraphicsAPI::ResourceState::State::CopyDest, GraphicsAPI::ResourceState::State::CopySource }; ResourceTransitionBarrier(dstBufArr, kNumBuf, desiredStateArr); D3D12_TEXTURE_COPY_LOCATION dstLoc = {}; dstLoc.pResource = dst->m_apiData.m_resource; dstLoc.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; dstLoc.SubresourceIndex = 0; D3D12_TEXTURE_COPY_LOCATION srcLoc = {}; srcLoc.pResource = src->m_apiData.m_resource; srcLoc.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; srcLoc.SubresourceIndex = 0; constexpr UINT DstX = 0; constexpr UINT DstY = 0; constexpr UINT DstZ = 0; const D3D12_BOX* pSrcBox = nullptr; m_apiData.m_commandList->CopyTextureRegion(&dstLoc, DstX, DstY, DstZ, &srcLoc, pSrcBox); } void CommandList::CopyResource(Texture* dst, Texture* src) { constexpr uint32_t kNumBuf = 2; GraphicsAPI::Resource* dstBufArr[kNumBuf] = { dst, src }; GraphicsAPI::ResourceState::State desiredStateArr[kNumBuf] = { GraphicsAPI::ResourceState::State::CopyDest, GraphicsAPI::ResourceState::State::CopySource }; ResourceTransitionBarrier(dstBufArr, kNumBuf, desiredStateArr); m_apiData.m_commandList->CopyResource(dst->m_apiData.m_resource, src->m_apiData.m_resource); } void CommandList::SetComputeRootDescriptorTable(RootSignature* /*rootSig*/, uint32_t baseSlotIndex, DescriptorTable** tables, size_t numTables) { for (size_t i = 0; i < numTables; ++i) { m_apiData.m_commandList->SetComputeRootDescriptorTable(baseSlotIndex + (uint32_t)i, tables[i]->m_apiData.m_heapAllocationInfo.m_hGPU); } } void CommandList::SetRayTracingRootDescriptorTable(RootSignature* rootSig, uint32_t baseSlotIndex, DescriptorTable** tables, size_t numTables) { // D3D12 uses the same binding point for RT. return SetComputeRootDescriptorTable(rootSig, baseSlotIndex, tables, numTables); } void CommandList::SetComputeRootSignature(RootSignature* rootSig) { m_apiData.m_commandList->SetComputeRootSignature(rootSig->m_apiData.m_rootSignature); } void CommandList::SetComputePipelineState(ComputePipelineState* pso) { m_apiData.m_commandList->SetPipelineState(pso->m_apiData.m_pipelineState); } void CommandList::SetRayTracingPipelineState(RaytracingPipelineState* rtPSO) { m_apiData.m_commandList->SetPipelineState1(rtPSO->m_apiData.m_rtPSO); } void CommandList::Dispatch(uint32_t x, uint32_t y, uint32_t z) { m_apiData.m_commandList->Dispatch(x, y, z); } void CommandList::BeginEvent(const std::array<uint32_t, 3>& color, const std::string& str) { #if defined(USE_PIX) PIXBeginEvent(m_apiData.m_commandList, PIX_COLOR((BYTE)color[0], (BYTE)color[1], (BYTE)color[2]), "%s", str.c_str()); #endif } void CommandList::EndEvent() { #if defined(USE_PIX) PIXEndEvent(m_apiData.m_commandList); #endif } #elif defined(GRAPHICS_API_VK) CommandList::~CommandList() { m_apiData = {}; } void CommandList::SetName(const std::wstring& str) { SetNameInternal(m_apiData.m_device, VkObjectType::VK_OBJECT_TYPE_COMMAND_BUFFER, (uint64_t)m_apiData.m_commandBuffer, str.c_str()); } bool CommandList::InitFromAPIData(VkDevice device, VkCommandBuffer cmdBuf) { m_apiData.m_device = device; m_apiData.m_commandBuffer = cmdBuf; return true; } void CommandList::ClearState() { // There is no VK clear state. assert(false); } bool CommandList::SetDescriptorHeap(DescriptorHeap* /*heap*/) { // nothing to do. return true; } bool CommandList::HasDebugCommandList() const { return false; } bool CommandList::AssertResourceStates(Resource** , SubresourceRange* , size_t , ResourceState::State* ) { return true; } bool CommandList::ResourceTransitionBarrier(Resource** resArr, SubresourceRange* subresourceRanges, size_t numRes, ResourceState::State* desiredStates) { { std::vector<VkBufferMemoryBarrier> bufSHADER2SHADERBarrier; std::vector<VkBufferMemoryBarrier> bufSHADER2CPYBarrier; std::vector<VkBufferMemoryBarrier> bufTop2CPYBarrier; std::vector<VkBufferMemoryBarrier> bufCPY2SHADERBarrier; std::vector<VkBufferMemoryBarrier> bufCPY2CPYBarrier; std::vector<VkBufferMemoryBarrier> bufCPY2HOSTBarrier; std::vector<VkImageMemoryBarrier> imgSHADER2SHADERBBarrier; std::vector<VkImageMemoryBarrier> imgSHADER2CPYBarrier; std::vector<VkImageMemoryBarrier> imgCPY2SHADERBarrier; for (size_t i = 0; i < numRes; i++) { auto res = resArr[i]; auto newState = desiredStates[i]; if (res->m_type == Resource::Type::Buffer) { assert(subresourceRanges == nullptr && "Expecting no subresource ranges for buffers"); Buffer* buf = (Buffer*)res; VkBufferMemoryBarrier barrier = {}; barrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER; barrier.srcAccessMask = Resource::GetVkAccessMask(buf->GetGlobalState()); barrier.dstAccessMask = Resource::GetVkAccessMask(newState); barrier.buffer = buf->m_apiData.m_buffer; barrier.offset = 0; barrier.size = buf->m_sizeInBytes; if (buf->GetGlobalState() == newState) { continue; } else if (buf->GetGlobalState() == ResourceState::State::UnorderedAccess && newState == ResourceState::State::ShaderResource) { bufSHADER2SHADERBarrier.push_back(barrier); } else if (buf->GetGlobalState() == ResourceState::State::ShaderResource && newState == ResourceState::State::UnorderedAccess) { bufSHADER2SHADERBarrier.push_back(barrier); } else if (buf->GetGlobalState() == ResourceState::State::UnorderedAccess && newState == ResourceState::State::CopySource) { bufSHADER2CPYBarrier.push_back(barrier); } else if (buf->GetGlobalState() == ResourceState::State::UnorderedAccess && newState == ResourceState::State::CopyDest) { bufSHADER2CPYBarrier.push_back(barrier); } else if (buf->GetGlobalState() == ResourceState::State::GenericRead && newState == ResourceState::State::CopySource) { bufTop2CPYBarrier.push_back(barrier); } else if (buf->GetGlobalState() == ResourceState::State::CopyDest && newState == ResourceState::State::UnorderedAccess) { bufCPY2SHADERBarrier.push_back(barrier); } else if (buf->GetGlobalState() == ResourceState::State::CopyDest && newState == ResourceState::State::NonPixelShader) { bufCPY2SHADERBarrier.push_back(barrier); } else if (buf->GetGlobalState() == ResourceState::State::CopyDest && newState == ResourceState::State::CopySource) { bufCPY2CPYBarrier.push_back(barrier); } else if (buf->GetGlobalState() == ResourceState::State::CopyDest && newState == ResourceState::State::CopyDest) { // this is a hacky case that D3D12 doesn't need barrier copy after host read, but VK need a barrier. barrier.dstAccessMask = VK_ACCESS_HOST_READ_BIT; bufCPY2HOSTBarrier.push_back(barrier); } else if (buf->GetGlobalState() == ResourceState::State::CopySource && newState == ResourceState::State::UnorderedAccess) { bufCPY2SHADERBarrier.push_back(barrier); } else { Log::Fatal(L"Unsupported resource transition type in VK detected."); return false; } buf->SetGlobalState(newState); } else { auto QueueVkBarrier = [&imgSHADER2SHADERBBarrier,&imgSHADER2CPYBarrier,&imgCPY2SHADERBarrier] (const VkImageMemoryBarrier& barrier, ResourceState::State from, ResourceState::State to){ if (from == ResourceState::State::UnorderedAccess && to == ResourceState::State::ShaderResource) { imgSHADER2SHADERBBarrier.push_back(barrier); } else if (from == ResourceState::State::UnorderedAccess && to == ResourceState::State::NonPixelShader) { imgSHADER2SHADERBBarrier.push_back(barrier); } else if (from == ResourceState::State::UnorderedAccess && to == ResourceState::State::CopySource) { imgSHADER2CPYBarrier.push_back(barrier); } else if (from == ResourceState::State::UnorderedAccess && to == ResourceState::State::CopyDest) { imgSHADER2CPYBarrier.push_back(barrier); } else if (from == ResourceState::State::ShaderResource && to == ResourceState::State::UnorderedAccess) { imgSHADER2SHADERBBarrier.push_back(barrier); } else if (from == ResourceState::State::ShaderResource && to == ResourceState::State::CopyDest) { imgSHADER2CPYBarrier.push_back(barrier); } else if (from == ResourceState::State::ShaderResource && to == ResourceState::State::Common) { imgSHADER2SHADERBBarrier.push_back(barrier); } else if (from == ResourceState::State::NonPixelShader && to == ResourceState::State::UnorderedAccess) { imgSHADER2SHADERBBarrier.push_back(barrier); } else if (from == ResourceState::State::NonPixelShader && to == ResourceState::State::Common) { imgSHADER2SHADERBBarrier.push_back(barrier); } else if (from == ResourceState::State::NonPixelShader && to == ResourceState::State::CopyDest) { imgSHADER2CPYBarrier.push_back(barrier); } else if (from == ResourceState::State::CopyDest && to == ResourceState::State::NonPixelShader) { imgCPY2SHADERBarrier.push_back(barrier); } else if (from == ResourceState::State::CopyDest && to == ResourceState::State::Common) { imgCPY2SHADERBarrier.push_back(barrier); } else if (from == ResourceState::State::CopyDest && to == ResourceState::State::UnorderedAccess) { imgCPY2SHADERBarrier.push_back(barrier); } else if (from == ResourceState::State::CopySource && to == ResourceState::State::Common) { imgCPY2SHADERBarrier.push_back(barrier); } else if (from == ResourceState::State::Undefined && to == ResourceState::State::UnorderedAccess) { imgSHADER2SHADERBBarrier.push_back(barrier); } else if (from == ResourceState::State::Undefined && to == ResourceState::State::NonPixelShader) { imgSHADER2SHADERBBarrier.push_back(barrier); } else if (from == ResourceState::State::Undefined && to == ResourceState::State::Common) { imgSHADER2SHADERBBarrier.push_back(barrier); } else if (from == ResourceState::State::Common && to == ResourceState::State::NonPixelShader) { imgSHADER2SHADERBBarrier.push_back(barrier); } else if (from == ResourceState::State::Common && to == ResourceState::State::UnorderedAccess) { imgSHADER2SHADERBBarrier.push_back(barrier); } else if (from == ResourceState::State::Common && to == ResourceState::State::CopyDest) { imgSHADER2CPYBarrier.push_back(barrier); } else if (from == ResourceState::State::Common && to == ResourceState::State::ShaderResource) { imgSHADER2SHADERBBarrier.push_back(barrier); } else { Log::Fatal(L"Unsupported resource transition type in VK detected."); } }; // texture (image) Texture* tex = (Texture*)res; if (subresourceRanges || tex->m_globalState.IsTrackingPerSubresource()) { const SubresourceRange& range = subresourceRanges ? subresourceRanges[i] : SubresourceRange(0, (uint8_t)tex->m_arraySize, 0, (uint8_t)tex->m_mipLevels); for (uint8_t arrayIdx = range.baseArrayLayer; arrayIdx < range.baseArrayLayer + range.arrayLayerCount; ++arrayIdx) { for (uint8_t mipIdx = range.baseMipLevel; mipIdx < range.baseMipLevel + range.mipLevelCount; ++mipIdx) { uint32_t subresource = SubresourceRange::CalcSubresource(mipIdx, arrayIdx, tex->m_mipLevels); ResourceState::State oldState = tex->GetGlobalState(subresource); VkImageLayout srcLayout = Resource::GetVkImageLayout(oldState); VkImageLayout dstLayout = Resource::GetVkImageLayout(newState); if (srcLayout != dstLayout) { VkImageMemoryBarrier barrier = {}; barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; barrier.oldLayout = srcLayout; barrier.newLayout = dstLayout; barrier.image = tex->m_apiData.m_image; barrier.subresourceRange.aspectMask = Resource::GetVkImageAspectFlags(tex->m_format); barrier.subresourceRange.baseArrayLayer = arrayIdx; barrier.subresourceRange.baseMipLevel = mipIdx; barrier.subresourceRange.layerCount = 1; barrier.subresourceRange.levelCount = 1; barrier.srcAccessMask = Resource::GetVkAccessMask(oldState); barrier.dstAccessMask = Resource::GetVkAccessMask(newState); QueueVkBarrier(barrier, oldState, newState); } tex->SetGlobalState(newState, subresource); } } } else { ResourceState::State oldState = tex->GetGlobalState(); VkImageLayout srcLayout = Resource::GetVkImageLayout(oldState); VkImageLayout dstLayout = Resource::GetVkImageLayout(newState); if (srcLayout != dstLayout) { VkImageMemoryBarrier barrier = {}; barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; barrier.oldLayout = srcLayout; barrier.newLayout = dstLayout; barrier.image = tex->m_apiData.m_image; barrier.subresourceRange.aspectMask = Resource::GetVkImageAspectFlags(tex->m_format); barrier.subresourceRange.baseArrayLayer = 0; barrier.subresourceRange.baseMipLevel = 0; barrier.subresourceRange.layerCount = tex->m_arraySize; barrier.subresourceRange.levelCount = tex->m_mipLevels;; barrier.srcAccessMask = Resource::GetVkAccessMask(oldState); barrier.dstAccessMask = Resource::GetVkAccessMask(newState); QueueVkBarrier(barrier, oldState, newState); } tex->SetGlobalState(newState); } } } if (bufSHADER2SHADERBarrier.size() > 0) { vkCmdPipelineBarrier(m_apiData.m_commandBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, (uint32_t)bufSHADER2SHADERBarrier.size(), bufSHADER2SHADERBarrier.data(), 0, nullptr); } if (bufSHADER2CPYBarrier.size() > 0) { vkCmdPipelineBarrier(m_apiData.m_commandBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, (uint32_t)bufSHADER2CPYBarrier.size(), bufSHADER2CPYBarrier.data(), 0, nullptr); } if (bufTop2CPYBarrier.size() > 0) { vkCmdPipelineBarrier(m_apiData.m_commandBuffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, (uint32_t)bufTop2CPYBarrier.size(), bufTop2CPYBarrier.data(), 0, nullptr); } if (bufCPY2SHADERBarrier.size() > 0) { vkCmdPipelineBarrier(m_apiData.m_commandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, (uint32_t)bufCPY2SHADERBarrier.size(), bufCPY2SHADERBarrier.data(), 0, nullptr); } if (bufCPY2CPYBarrier.size() > 0) { vkCmdPipelineBarrier(m_apiData.m_commandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, (uint32_t)bufCPY2CPYBarrier.size(), bufCPY2CPYBarrier.data(), 0, nullptr); } if (bufCPY2HOSTBarrier.size() > 0) { vkCmdPipelineBarrier(m_apiData.m_commandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, 0, nullptr, (uint32_t)bufCPY2HOSTBarrier.size(), bufCPY2HOSTBarrier.data(), 0, nullptr); } if (imgSHADER2SHADERBBarrier.size() > 0) { vkCmdPipelineBarrier(m_apiData.m_commandBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, (uint32_t)imgSHADER2SHADERBBarrier.size(), imgSHADER2SHADERBBarrier.data()); } if (imgSHADER2CPYBarrier.size() > 0) { vkCmdPipelineBarrier(m_apiData.m_commandBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, (uint32_t)imgSHADER2CPYBarrier.size(), imgSHADER2CPYBarrier.data()); } if (imgCPY2SHADERBarrier.size() > 0) { vkCmdPipelineBarrier(m_apiData.m_commandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, (uint32_t)imgCPY2SHADERBarrier.size(), imgCPY2SHADERBarrier.data()); } } return true; } bool CommandList::ResourceTransitionBarrier(Resource** resArr, size_t numRes, ResourceState::State* desiredStates) { return ResourceTransitionBarrier(resArr, nullptr, numRes, desiredStates); } bool CommandList::ResourceUAVBarrier(Resource** resArr, size_t numRes) { // There is no layout change in UAV barrier. std::vector<VkBufferMemoryBarrier> bufSHADER2SHADERBarrier; std::vector<VkBufferMemoryBarrier> bufAS2ASBarrier; std::vector<VkImageMemoryBarrier> imgBarrier; for (size_t i = 0; i < numRes; i++) { auto res = resArr[i]; if (res->m_type == Resource::Type::Buffer) { Buffer* buf = (Buffer*)res; VkBufferMemoryBarrier barrier = {}; barrier.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER; barrier.buffer = buf->m_apiData.m_buffer; barrier.offset = 0; barrier.size = buf->m_sizeInBytes; if (buf->GetGlobalState() == ResourceState::State::UnorderedAccess) { barrier.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT; barrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; bufSHADER2SHADERBarrier.push_back(barrier); } else if (buf->GetGlobalState() == ResourceState::State::ShaderResource) { barrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT; barrier.dstAccessMask = VK_ACCESS_SHADER_WRITE_BIT; bufSHADER2SHADERBarrier.push_back(barrier); } else if (buf->GetGlobalState() == ResourceState::State::AccelerationStructure) { barrier.srcAccessMask = VK_ACCESS_ACCELERATION_STRUCTURE_WRITE_BIT_KHR; barrier.dstAccessMask = VK_ACCESS_ACCELERATION_STRUCTURE_READ_BIT_KHR; bufAS2ASBarrier.push_back(barrier); } else { Log::Fatal(L"Unsupported resource transition type in VK detected."); return false; } } else { // texture (image) Texture* tex = (Texture*)res; VkImageLayout srcLayout = Resource::GetVkImageLayout(tex->GetGlobalState()); VkImageLayout dstLayout = Resource::GetVkImageLayout(tex->GetGlobalState()); if (srcLayout != dstLayout) { VkImageMemoryBarrier barrier = {}; barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; barrier.oldLayout = srcLayout; barrier.newLayout = dstLayout; barrier.image = tex->m_apiData.m_image; barrier.subresourceRange.aspectMask = Resource::GetVkImageAspectFlags(tex->m_format); barrier.subresourceRange.baseArrayLayer = 0; barrier.subresourceRange.baseMipLevel = 0; barrier.subresourceRange.layerCount = tex->m_arraySize; barrier.subresourceRange.levelCount = tex->m_mipLevels;; barrier.srcAccessMask = Resource::GetVkAccessMask(tex->GetGlobalState()); barrier.dstAccessMask = Resource::GetVkAccessMask(tex->GetGlobalState()); imgBarrier.push_back(barrier); } } } if (bufSHADER2SHADERBarrier.size() > 0) { vkCmdPipelineBarrier(m_apiData.m_commandBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, (uint32_t)bufSHADER2SHADERBarrier.size(), bufSHADER2SHADERBarrier.data(), 0, nullptr); } if (bufAS2ASBarrier.size() > 0) { vkCmdPipelineBarrier(m_apiData.m_commandBuffer, VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, (uint32_t)bufAS2ASBarrier.size(), bufAS2ASBarrier.data(), 0, nullptr); } if (imgBarrier.size() > 0) { vkCmdPipelineBarrier(m_apiData.m_commandBuffer, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, (uint32_t)imgBarrier.size(), imgBarrier.data()); } return true; } bool CommandList::CopyTextureSingleMip(Device* dev, uint32_t mipIndex, Texture* dstTex, Buffer* srcUpBuf) { uint32_t rowPitch, totalSize; if (mipIndex > 0) { Log::Fatal(L"Copy texture only support the first mip."); return false; } if (!dstTex->GetUploadBufferFootplint(dev, mipIndex, &rowPitch, &totalSize)) { Log::Fatal(L"Faild to get upload size of a texture."); return false; } if (totalSize > srcUpBuf->m_sizeInBytes) { Log::Fatal(L"Src buffer size is too small to copy to a texture slice."); return false; } // to TRANSFER_DST_OPTIMAL { VkImageLayout srcLayout = Resource::GetVkImageLayout(dstTex->GetGlobalState()); VkImageLayout dstLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; VkImageMemoryBarrier barrier = {}; barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; barrier.oldLayout = srcLayout; barrier.newLayout = dstLayout; barrier.image = dstTex->m_apiData.m_image; barrier.subresourceRange.aspectMask = Resource::GetVkImageAspectFlags(dstTex->m_format); barrier.subresourceRange.baseArrayLayer = 0; barrier.subresourceRange.baseMipLevel = 0; barrier.subresourceRange.layerCount = dstTex->m_arraySize; barrier.subresourceRange.levelCount = dstTex->m_mipLevels;; barrier.srcAccessMask = Resource::GetVkAccessMask(dstTex->GetGlobalState()); barrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; vkCmdPipelineBarrier( m_apiData.m_commandBuffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier ); } VkBufferImageCopy region{}; region.bufferOffset = 0; region.bufferRowLength = 0; region.bufferImageHeight = 0; region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; region.imageSubresource.mipLevel = mipIndex; region.imageSubresource.baseArrayLayer = 0; region.imageSubresource.layerCount = 1; region.imageOffset = { 0, 0, 0 }; region.imageExtent = { dstTex->m_width, dstTex->m_height, dstTex->m_depth }; vkCmdCopyBufferToImage( m_apiData.m_commandBuffer, srcUpBuf->m_apiData.m_buffer, dstTex->m_apiData.m_image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &region ); // to shader resource for compute shader stage. { dstTex->SetGlobalState(ResourceState::State::ShaderResource); VkImageLayout srcLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; VkImageLayout dstLayout = Resource::GetVkImageLayout(dstTex->GetGlobalState()); VkImageMemoryBarrier barrier = {}; barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; barrier.oldLayout = srcLayout; barrier.newLayout = dstLayout; barrier.image = dstTex->m_apiData.m_image; barrier.subresourceRange.aspectMask = Resource::GetVkImageAspectFlags(dstTex->m_format); barrier.subresourceRange.baseArrayLayer = 0; barrier.subresourceRange.baseMipLevel = 0; barrier.subresourceRange.layerCount = dstTex->m_arraySize; barrier.subresourceRange.levelCount = dstTex->m_mipLevels;; barrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; barrier.dstAccessMask = Resource::GetVkAccessMask(dstTex->GetGlobalState()); vkCmdPipelineBarrier( m_apiData.m_commandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier ); } return true; } void CommandList::CopyBufferRegion(Buffer* dst, uint64_t dstOffset, Buffer* src, uint64_t srcOffset, uint64_t copySizeInBytes) { #if 0 { std::vector<VkBufferMemoryBarrier> bufBarrier; VkBufferMemoryBarrier b = {}; b.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER; b.srcAccessMask = 0; b.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; b.buffer = dst->m_apiData.m_buffer; b.size = dst->m_sizeInBytes; bufBarrier.push_back(b); b.srcAccessMask = 0; b.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; b.buffer = src->m_apiData.m_buffer; b.size = src->m_sizeInBytes; bufBarrier.push_back(b); vkCmdPipelineBarrier(m_apiData.m_commandBuffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, (uint32_t)bufBarrier.size(), bufBarrier.data(), 0, nullptr); } #endif { VkBufferCopy copyRegion{}; copyRegion.srcOffset = srcOffset; copyRegion.dstOffset = dstOffset; copyRegion.size = copySizeInBytes; vkCmdCopyBuffer(m_apiData.m_commandBuffer, src->m_apiData.m_buffer, dst->m_apiData.m_buffer, 1, &copyRegion); } #if 0 { VkPipelineStageFlagBits dstStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; VkBufferMemoryBarrier b = {}; b.sType = VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER; b.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; b.buffer = dst->m_apiData.m_buffer; b.size = dst->m_sizeInBytes; if (dst->GetGlobalState() == Buffer::State::ShaderResource) { b.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; dstStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; } else if (dst->GetGlobalState() == Buffer::State::UnorderedAccess) { b.dstAccessMask = VK_ACCESS_SHADER_WRITE_BIT; dstStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; } else if (dst->GetGlobalState() == Buffer::State::CopyDest && dst->m_cpuAccess == Buffer::CpuAccess::Read) { b.dstAccessMask = VK_ACCESS_HOST_READ_BIT; dstStage = VK_PIPELINE_STAGE_HOST_BIT; } vkCmdPipelineBarrier(m_apiData.m_commandBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, dstStage, 0, 0, nullptr, (uint32_t)1, &b, 0, nullptr); } #endif return; } void CommandList::CopyTextureRegion(Texture* dst, Texture* src) { constexpr uint32_t kNumBuf = 2; GraphicsAPI::Resource* dstBufArr[kNumBuf] = { dst, src }; GraphicsAPI::ResourceState::State desiredStateArr[kNumBuf] = { GraphicsAPI::ResourceState::State::CopyDest, GraphicsAPI::ResourceState::State::CopySource }; ResourceTransitionBarrier(dstBufArr, kNumBuf, desiredStateArr); VkImageLayout srcLayout = Resource::GetVkImageLayout(src->GetGlobalState()); VkImageLayout dstLayout = Resource::GetVkImageLayout(dst->GetGlobalState()); VkImageCopy region = {}; region.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; region.srcSubresource.mipLevel = 0; region.srcSubresource.baseArrayLayer = 0; region.srcSubresource.layerCount = 1; region.srcOffset.x = 0; region.srcOffset.y = 0; region.srcOffset.z = 0; region.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; region.dstSubresource.mipLevel = 0; region.dstSubresource.baseArrayLayer = 0; region.dstSubresource.layerCount = 1; region.dstOffset.x = 0; region.dstOffset.y = 0; region.dstOffset.z = 0; region.extent.width = src->m_width; region.extent.height = src->m_height; region.extent.depth = src->m_depth; vkCmdCopyImage( m_apiData.m_commandBuffer, src->m_apiData.m_image, srcLayout, dst->m_apiData.m_image, dstLayout, 1, &region); } void CommandList::CopyResource(Texture* , Texture* ) { assert(false); } void CommandList::SetComputeRootDescriptorTable(RootSignature* rootSig, uint32_t baseSlotIndex, DescriptorTable** tables, size_t numTables) { std::vector<VkDescriptorSet> sets; for (size_t i = 0; i < numTables; ++i) { sets.push_back(tables[i]->m_apiData.m_heapAllocationInfo.m_descSet); } vkCmdBindDescriptorSets( m_apiData.m_commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, rootSig->m_apiData.m_pipelineLayout, baseSlotIndex, (uint32_t)numTables, sets.data(), 0, nullptr); }; void CommandList::SetRayTracingRootDescriptorTable(RootSignature* rootSig, uint32_t baseSlotIndex, DescriptorTable** tables, size_t numTables) { std::vector<VkDescriptorSet> sets; for (size_t i = 0; i < numTables; ++i) { sets.push_back(tables[i]->m_apiData.m_heapAllocationInfo.m_descSet); } vkCmdBindDescriptorSets( m_apiData.m_commandBuffer, VK_PIPELINE_BIND_POINT_RAY_TRACING_KHR, rootSig->m_apiData.m_pipelineLayout, baseSlotIndex, (uint32_t)numTables, sets.data(), 0, nullptr); }; void CommandList::SetComputeRootSignature(RootSignature* /*rootSig*/) { // nothing to do in vk?? } void CommandList::SetComputePipelineState(ComputePipelineState* pso) { vkCmdBindPipeline(m_apiData.m_commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, pso->m_apiData.m_pipeline); } void CommandList::SetRayTracingPipelineState(RaytracingPipelineState* rtPSO) { vkCmdBindPipeline(m_apiData.m_commandBuffer, VK_PIPELINE_BIND_POINT_RAY_TRACING_KHR, rtPSO->m_apiData.m_pipeline); } void CommandList::Dispatch(uint32_t x, uint32_t y, uint32_t z) { vkCmdDispatch(m_apiData.m_commandBuffer, x, y, z); } void CommandList::BeginEvent(const std::array<uint32_t, 3>& color, const std::string& str) { (void)color; VkDebugUtilsLabelEXT s{ VK_STRUCTURE_TYPE_DEBUG_UTILS_LABEL_EXT, nullptr, str.c_str(), {1.0f, 1.0f, 1.0f, 1.0f} }; VK::vkCmdBeginDebugUtilsLabelEXT(m_apiData.m_commandBuffer, &s); } void CommandList::EndEvent() { VK::vkCmdEndDebugUtilsLabelEXT(m_apiData.m_commandBuffer); } #endif namespace Utils { ScopedEventObject::ScopedEventObject(CommandList* cmdList, const std::array<uint32_t, 3>& color, const std::string &str) { m_cmdList = cmdList; m_cmdList->BeginEvent(color, str); }; ScopedEventObject::~ScopedEventObject() { m_cmdList->EndEvent(); }; #if defined(GRAPHICS_API_D3D12) D3D12_SHADER_RESOURCE_VIEW_DESC BufferResourceViewDesc_R32F(UINT64 firstElm, UINT numElm) { D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {}; srvDesc.Format = DXGI_FORMAT_R32_FLOAT; srvDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; srvDesc.Buffer.FirstElement = firstElm; srvDesc.Buffer.NumElements = numElm; srvDesc.Buffer.StructureByteStride = 0; srvDesc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_NONE; return srvDesc; } D3D12_SHADER_RESOURCE_VIEW_DESC BufferResourceViewDesc_R32U(UINT64 firstElm, UINT numElm) { D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {}; srvDesc.Format = DXGI_FORMAT_R32_UINT; srvDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; srvDesc.Buffer.FirstElement = firstElm; srvDesc.Buffer.NumElements = numElm; srvDesc.Buffer.StructureByteStride = 0; srvDesc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_NONE; return srvDesc; } D3D12_SHADER_RESOURCE_VIEW_DESC BufferResourceViewDesc_R16U(UINT64 firstElm, UINT numElm) { D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {}; srvDesc.Format = DXGI_FORMAT_R16_UINT; srvDesc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; srvDesc.Buffer.FirstElement = firstElm; srvDesc.Buffer.NumElements = numElm; srvDesc.Buffer.StructureByteStride = 0; srvDesc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_NONE; return srvDesc; } D3D12_SHADER_RESOURCE_VIEW_DESC BufferResourceViewDesc_Tex2DFloat_SingleSlice(ID3D12Resource* res) { D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {}; auto desc = res->GetDesc(); switch (desc.Format) { case DXGI_FORMAT_R32G32B32A32_TYPELESS: srvDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; break; case DXGI_FORMAT_R32G32B32_TYPELESS: srvDesc.Format = DXGI_FORMAT_R32G32B32_FLOAT; break; case DXGI_FORMAT_R32G32_TYPELESS: srvDesc.Format = DXGI_FORMAT_R32G32_FLOAT; break; case DXGI_FORMAT_R32_TYPELESS: srvDesc.Format = DXGI_FORMAT_R32_FLOAT; break; default: srvDesc.Format = desc.Format; break; } srvDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; srvDesc.Texture2D.MipLevels = 1; srvDesc.Texture2D.MostDetailedMip = 0; srvDesc.Texture2D.PlaneSlice = 0; srvDesc.Texture2D.ResourceMinLODClamp = 0; return srvDesc; } D3D12_UNORDERED_ACCESS_VIEW_DESC BufferAccessViewDesc_R32F(UINT64 firstElm, UINT numElm) { D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {}; uavDesc.Format = DXGI_FORMAT_R32_FLOAT; uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; uavDesc.Buffer.FirstElement = firstElm; uavDesc.Buffer.NumElements = numElm; uavDesc.Buffer.StructureByteStride = 0; uavDesc.Buffer.CounterOffsetInBytes = 0; uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_NONE; return uavDesc; } D3D12_UNORDERED_ACCESS_VIEW_DESC BufferAccessViewDesc_R32U(UINT64 firstElm, UINT numElm) { D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {}; uavDesc.Format = DXGI_FORMAT_R32_UINT; uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER; uavDesc.Buffer.FirstElement = firstElm; uavDesc.Buffer.NumElements = numElm; uavDesc.Buffer.StructureByteStride = 0; uavDesc.Buffer.CounterOffsetInBytes = 0; uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_NONE; return uavDesc; } #endif }; /*************************************************************** * Utils ***************************************************************/ namespace Utils { #if defined(GRAPHICS_API_D3D12) std::wstring GetName(ID3D12Object* obj) { static const wchar_t* nullstr = L"NULL_D3DObject"; static const wchar_t* emptystr = L"EMPTY_NAME"; if (obj == nullptr) return nullstr; wchar_t wBuf[1024]; UINT siz = sizeof(wBuf) - 2; memset(wBuf, 0, sizeof(wBuf)); HRESULT hr = obj->GetPrivateData(WKPDID_D3DDebugObjectNameW, &siz, wBuf); wBuf[1023] = L'\0'; if (SUCCEEDED(hr) && siz > 0) return std::wstring(wBuf); return std::wstring(); }; #endif }; /*************************************************************** * QueryPool in VK * Not abstracted at all. Just for resource destruction. ***************************************************************/ #if defined(GRAPHICS_API_VK) QueryPool_VK::~QueryPool_VK() { if (m_apiData.m_device && m_apiData.m_queryPool) { vkDestroyQueryPool(m_apiData.m_device, m_apiData.m_queryPool, nullptr); } } bool QueryPool_VK::Create(Device* dev, const QueryPool_VK::InitInfo& initInfo) { VkQueryPoolCreateInfo info = {}; info.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO; info.flags = initInfo.m_createFlags; info.queryType = initInfo.m_queryType; info.queryCount = initInfo.m_poolSize; if (vkCreateQueryPool(dev->m_apiData.m_device, &info, nullptr, &m_apiData.m_queryPool) != VK_SUCCESS) { Log::Fatal(L"Failed to allocate queryPool."); return false; } m_apiData.m_device = dev->m_apiData.m_device; return true; } #endif };
NVIDIAGameWorks/KickstartRT
<|start_filename|>LoadPEGo/ImportTable.h<|end_filename|> #pragma once #include "PEFile.h" class CImportTable : public CPEFile { public: CImportTable(); virtual ~CImportTable(); PIMAGE_IMPORT_BY_NAME GetFuncByName(DWORD ThunkRva); PIMAGE_IMPORT_DESCRIPTOR GetImportDes(int nIndex,int num); int GetImportDesCount(); PIMAGE_IMPORT_DESCRIPTOR GetFirstImportDes(); void operator=(CPEFile& pefile); PIMAGE_THUNK_DATA GetFirstThunkData(DWORD ThunkDataRva); PIMAGE_THUNK_DATA GetThunkData(int nIndex, DWORD ThunkDataRva,int num); int GetThunkDataCount(DWORD ThunkDataRva); }; <|start_filename|>Ygdy8Crawl/mongostart.bat<|end_filename|> start mongod --dbpath D:\mongodb\data
qiyeboy/LuLunZi
<|start_filename|>assets/styles.css<|end_filename|> .no-deferjs .has-fallback { display: none !important; } picture, video, audio, source, img, iframe, frame, embed { min-width: 1px; min-height: 1px; visibility: visible; } .defer-loaded { background-color: initial!important; } .defer-faded .defer-loading { opacity: 0.5!important; } .defer-faded .defer-loaded { transition: opacity 0.2s; } <|start_filename|>.docker/Dockerfile<|end_filename|> # Dockerfile FROM php:7-zts # Install Composer, NPM RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer \ ;apt update -y \ ;apt install -y nodejs npm git zip unzip \ ;npm i -g npm CMD ["/usr/local/bin/composer", "docker"] <|start_filename|>package.json<|end_filename|> { "homepage": "https://github.com/shinsenter/defer.php#readme", "author": "<NAME> <<EMAIL>>", "license": "MIT", "dependencies": { "@shinsenter/defer.js": "^2.5.0" }, "scripts": { "cleanup": "rm -rf ./node_modules package-lock.json", "tools": "npm -g i eslint js-beautify uglify-js clean-css-cli", "pull": "npm run cleanup && npm run tools && npm i --prod && npm audit fix", "copy": "cp -p ./node_modules/@shinsenter/defer.js/dist/*.js ./public/lib/", "lint": "eslint --config assets/.eslintrc --ext .js assets --fix", "js": "uglifyjs --config-file assets/.uglifyjs -o public/helpers.min.js assets/helpers.js", "css": "cleancss -o public/styles.min.css assets/styles.css" } } <|start_filename|>assets/helpers.js<|end_filename|> /** * Package shinsenter/defer.php * https://github.com/shinsenter/defer.php * * Released under the MIT license * https://raw.githubusercontent.com/shinsenter/defer.php/master/LICENSE * * MIT License * * Copyright (c) 2019 <NAME> <<EMAIL>> * * 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. * */ (function (window, document, console) { /* |-------------------------------------------------------------------------- | Define variables and constants |-------------------------------------------------------------------------- */ // Common texts var _dataLayer = 'dataLayer'; // Common CSS selectors var _queryTarget = '.defer-loading:not([data-ignore])'; /* |-------------------------------------------------------------------------- | Check for defer.js |-------------------------------------------------------------------------- */ var defer = window.Defer; var _delay = window.DEFERJS_DELAY || 8; var _options = window.DEFERJS_OPTIONS || {'rootMargin': '150%'}; /* |-------------------------------------------------------------------------- | Internal functions |-------------------------------------------------------------------------- */ function _replaceClass(node, find, replace) { node.className = ((' ' + node.className + ' '). replace(' ' + find + ' ', ' ') + replace).trim(); } /* |-------------------------------------------------------------------------- | Fallback for external libraries |-------------------------------------------------------------------------- */ // Fix missing dataLayer (for Google Analytics) // See: https://developers.google.com/analytics/devguides/collection/analyticsjs window.ga = window.ga || function () {(window.ga.q = window.ga.q || []).push(arguments)}; window.ga.l = Number(Date()); window[_dataLayer] = window[_dataLayer] || []; /* |-------------------------------------------------------------------------- | Define helper object |-------------------------------------------------------------------------- */ _replaceClass( document.documentElement, 'no-deferjs', defer ? 'deferjs' : '' ); // Check if missing defer feature if (!defer) { return; } /* |-------------------------------------------------------------------------- | Main |-------------------------------------------------------------------------- */ // Lazyload all style tags defer(function() { [].slice.call(document.querySelectorAll('style[defer]')). forEach(defer.reveal); }, _delay); // Lazyload all media defer.dom(_queryTarget, _delay, 0, function (node) { _replaceClass(node, 'defer-loading', 'defer-loaded'); }, _options); // Copyright if (console.log) { console.log([ 'Optimized by defer.php', '(c) 2021 AppSeeds', 'Github: https://code.shin.company/defer.php' ].join('\n')); } })(this, document, console); <|start_filename|>package-lock.json<|end_filename|> { "name": "defer.php", "lockfileVersion": 2, "requires": true, "packages": { "": { "license": "MIT", "dependencies": { "@shinsenter/defer.js": "^2.5.0" } }, "node_modules/@shinsenter/defer.js": { "version": "2.5.0", "resolved": "https://registry.npmjs.org/@shinsenter/defer.js/-/defer.js-2.5.0.tgz", "integrity": "<KEY> "funding": [ { "type": "github", "url": "https://github.com/shinsenter/defer.js/stargazers" }, { "type": "paypal", "url": "https://www.patreon.com/appseeds" }, { "type": "patreon", "url": "https://www.patreon.com/shinsenter" } ] } }, "dependencies": { "@shinsenter/defer.js": { "version": "2.5.0", "resolved": "https://registry.npmjs.org/@shinsenter/defer.js/-/defer.js-2.5.0.tgz", "integrity": "<KEY> } } }
shinsenter/defer.php
<|start_filename|>node_modules/nodemailer-mailgun-transport/src/mailgun-transport.js<|end_filename|> 'use strict'; var Mailgun = require('mailgun-js'); var cons = require('consolidate'); var packageData = require('../package.json'); var series = require('async-series'); var pickBy = require('lodash.pickby'); var some = require('lodash.some'); var startsWith = require('lodash.startswith'); var whitelistExact = [ 'from', 'to', 'cc', 'bcc', 'subject', 'text', 'html', 'attachment', 'inline', 'recipient-variables', 'o:tag', 'o:campaign', 'o:dkim', 'o:deliverytime', 'o:testmode', 'o:tracking', 'o:tracking-clicks', 'o:tracking-opens', 'o:require-tls', 'o:skip-verification' ]; var whitelistPrefix = [ 'h:', 'v:' ]; module.exports = function (options) { return new MailgunTransport(options); }; function MailgunTransport(options) { this.options = options || {}; this.name = 'Mailgun'; this.version = packageData.version; this.mailgun = Mailgun({ apiKey: this.options.auth.api_key, domain: this.options.auth.domain || '' }); this.messages = this.mailgun.messages(); } MailgunTransport.prototype.send = function send(mail, callback) { var self = this; var mailData = mail.data; series([ function (done) { if (mailData.template && mailData.template.name && mailData.template.engine) { mailData.template.context = mailData.template.context || {}; cons[mailData.template.engine](mailData.template.name, mailData.template.context, function (err, html) { if (err) throw err; mailData.html = html; done(); }); } else { done(); } }, function (done) { // convert nodemailer attachments to mailgun-js attachements if (mailData.attachments) { var attachment, mailgunAttachment, data, attachmentList = [], inlineList = []; for (var i in mailData.attachments) { attachment = mailData.attachments[i]; // mailgunjs does not encode content string to a buffer if (typeof attachment.content === 'string') { data = new Buffer(attachment.content, attachment.encoding); } else { data = attachment.content || attachment.path || undefined; } //console.log(data); mailgunAttachment = new self.mailgun.Attachment({ data: data, filename: attachment.cid || attachment.filename || undefined, contentType: attachment.contentType || undefined, knownLength: attachment.knownLength || undefined }); if (attachment.cid) { inlineList.push(mailgunAttachment); } else { attachmentList.push(mailgunAttachment); } //console.log(b); } mailData.attachment = attachmentList; mailData.inline = inlineList; delete mailData.attachments; } delete mail.data.headers; var options = pickBy(mailData, function (value, key) { if (whitelistExact.indexOf(key) !== -1) { return true; } return some(whitelistPrefix, function (prefix) { return startsWith(key, prefix); }); }); self.messages.send(options, function (err, data) { callback(err || null, data); }); } ], function (err) { if (err) throw err; }); };
nonsenseMB/newsscraler
<|start_filename|>module/options/js/options-custom.js<|end_filename|> /** * Custom scripts needed for the colorpicker, image button selectors, * and navigation tabs. */ jQuery(document).ready(function($) { $('#versionss').click(function(){ $("#versionss").val("检测版本中..."); $.ajax({ type: "GET", url: "https://www.boxmoe.com/api/boxmoe-dove.txt", data: {}, dataType: "json", success: function(result){ var dataObj = result, con = ""; $.each(dataObj, function(index, item){ con += "<span class=\"boxmoe-button\">主题名:"+item.name+" | "; con += "最新版本号:"+item.version+" | "; con += "更新日期:"+item.update+" | "; con += "更新链接:<a href='"+item.updateto+"' target='_blank'>点击访问</a></span>"; }); console.log(con); $("#showing").html(con); $('#versionss').remove(); } }); }); // Loads the color pickers $('.of-color').wpColorPicker(); // Image Options $('.of-radio-img-img').click(function(){ $(this).parent().parent().find('.of-radio-img-img').removeClass('of-radio-img-selected'); $(this).addClass('of-radio-img-selected'); }); $('.of-radio-img-label').hide(); $('.of-radio-img-img').show(); $('.of-radio-img-radio').hide(); // Loads tabbed sections if they exist if ( $('.nav-tab-wrapper').length > 0 ) { options_framework_tabs(); } function options_framework_tabs() { var $group = $('.group'), $navtabs = $('.nav-tab-wrapper a'), active_tab = ''; // Hides all the .group sections to start $group.hide(); // Find if a selected tab is saved in localStorage if ( typeof(localStorage) != 'undefined' ) { active_tab = localStorage.getItem('active_tab'); } // If active tab is saved and exists, load it's .group if ( active_tab != '' && $(active_tab).length ) { $(active_tab).fadeIn(); $(active_tab + '-tab').addClass('nav-tab-active'); } else { $('.group:first').fadeIn(); $('.nav-tab-wrapper a:first').addClass('nav-tab-active'); } // Bind tabs clicks $navtabs.click(function(e) { e.preventDefault(); // Remove active class from all tabs $navtabs.removeClass('nav-tab-active'); $(this).addClass('nav-tab-active').blur(); if (typeof(localStorage) != 'undefined' ) { localStorage.setItem('active_tab', $(this).attr('href') ); } var selected = $(this).attr('href'); $group.hide(); $(selected).fadeIn(); }); } }); <|start_filename|>style.css<|end_filename|> /* Theme Name: Boxmoe(鸽子版) Theme URI: https://www.boxmoe.com Description: boxmoe. Author: 爆米花 Author URI: https://www.boxmoe.com Version: dove2.0 */ <|start_filename|>assets/js/comments.js<|end_filename|> $(document).ready(function() { ajaxComt(); }); function ajaxComt(){ var i = 0, got = -1, len = document.getElementsByTagName('script').length; while ( i <= len && got == -1){ var js_url = document.getElementsByTagName('script')[i].src, got = js_url.indexOf('comments.js'); i++ ; } var edit_mode = '1', // 再编辑模式( '1'=打开; '0'=关闭 ) ajax_php_url = js_url.replace('comments.js','../../module/fun-ajax-comments.php').replace(/^https?:\/\/.+\/wp-content/, location.origin+"/wp-content"), wp_url = js_url.substr(0, js_url.indexOf('wp-content')), wp_url = js_url.substr(0, js_url.indexOf('wp-content')), pic_sb = wp_url + 'wp-admin/images/wpspin_dark.gif', // 提交 icon pic_no = wp_url + 'wp-admin/images/no.png', // 错误 icon pic_ys = wp_url + 'wp-admin/images/yes.png', // 成功 icon txt1 = '<div id="commentsloading"><i class="fa fa-spinner fa-spin"></i> 正在提交, 请稍候...</div>', txt2 = '<div id="error">#</div>', txt3 = '"> <div id="edita" class="badge badge-success mb20 mt10">提交成功!', edt1 = '刷新页面之前您可以<a rel="nofollow" class="comment-reply-link_a" href="#edit" onclick=\'return addComment.moveForm("', edt2 = ')\'>&nbsp;&nbsp;重新编辑</a></div> ', cancel_edit = '取消编辑', edit, num = 1, comm_array=[]; comm_array.push(''); jQuery(document).ready(function($) { $comments = $('#comments-title'); // 评论数据的 ID $cancel = $('#cancel-comment-reply-link'); cancel_text = $cancel.text(); $submit = $('#commentform #submit'); $submit.attr('disabled', false); $('#comment').after( txt1 + txt2 ); $('#commentsloading').hide(); $('#error').hide(); $body = (window.opera) ? (document.compatMode == "CSS1Compat" ? $('html') : $('body')) : $('html,body'); /** submit */ $('#commentform').submit(function() { $('#commentsloading').slideDown(); $submit.attr('disabled', true).fadeTo('slow', 0.5); if ( edit ) $('#comment').after('<input type="text" name="edit_id" id="edit_id" value="' + edit + '" style="display:none;" />'); /** Ajax */ $.ajax( { url: ajax_php_url, data: $(this).serialize(), type: $(this).attr('method'), error: function(request) { $('#commentsloading').slideUp(); $('#error').slideDown().html('<img src="' + pic_no + '" style="vertical-align:middle;" alt="img"/> ' + request.responseText); setTimeout(function() {$submit.attr('disabled', false).fadeTo('slow', 1); $('#error').slideUp();}, 3000); }, success: function(data) { $('#commentsloading').hide(); comm_array.push($('#comment').val()); $('textarea').each(function() {this.value = ''}); var t = addComment, cancel = t.I('cancel-comment-reply-link'), temp = t.I('wp-temp-form-div'), respond = t.I(t.respondId), post = t.I('comment_post_ID').value, parent = t.I('comment_parent').value; // comments if ( ! edit && $comments.length ) { n = parseInt($comments.text().match(/\d+/)); $comments.text($comments.text().replace( n, n + 1 )); } // show comment new_htm = '" id="new_comm_' + num + '"></'; new_htm = ( parent == '0' ) ? ('\n<div class="comments-list commenting' + new_htm + 'div>') : ('\n<div class="comments-list commenting' + new_htm + 'div>'); ok_htm = '\n<span id="success_' + num + txt3; if ( edit_mode == '1' ) { div_ = (document.body.innerHTML.indexOf('div-comment-') == -1) ? '' : ((document.body.innerHTML.indexOf('li-comment-') == -1) ? 'div-' : ''); ok_htm = ok_htm.concat(edt1, div_, 'comment-', parent, '", "', parent, '", "respond", "', post, '", ', num, edt2); } ok_htm += '</span>\n'; $('#respond_com').before(new_htm); $('#new_comm_' + num).hide().append(data); $('#new_comm_' + num).append(ok_htm); $('#new_comm_' + num).fadeIn(4000); $body.animate( { scrollTop: $('#new_comm_' + num).offset().top - 200}, 900); countdown(); num++ ; edit = ''; $('*').remove('#edit_id'); cancel.style.display = 'none'; cancel.onclick = null; t.I('comment_parent').value = '0'; if ( temp && respond ) { temp.parentNode.insertBefore(respond, temp); temp.parentNode.removeChild(temp) } } }); // end Ajax return false; }); // end submit /** comment-reply.dev.js */ addComment = { moveForm : function(commId, parentId, respondId, postId, num) { var t = this, div, comm = t.I(commId), respond = t.I(respondId), cancel = t.I('cancel-comment-reply-link'), parent = t.I('comment_parent'), post = t.I('comment_post_ID'); if ( edit ) exit_prev_edit(); num ? ( t.I('comment').value = comm_array[num], edit = t.I('new_comm_' + num).innerHTML.match(/(comment-)(\d+)/)[2], $new_sucs = $('#success_' + num ), $new_sucs.hide(), $new_comm = $('#new_comm_' + num ), $new_comm.hide(), $cancel.text(cancel_edit) ) : $cancel.text(cancel_text); t.respondId = respondId; postId = postId || false; if ( !t.I('wp-temp-form-div') ) { div = document.createElement('div'); div.id = 'wp-temp-form-div'; div.style.display = 'none'; respond.parentNode.insertBefore(div, respond) } !comm ? ( temp = t.I('wp-temp-form-div'), t.I('comment_parent').value = '0', temp.parentNode.insertBefore(respond, temp), temp.parentNode.removeChild(temp) ) : comm.parentNode.insertBefore(respond, comm.nextSibling); $body.animate( { scrollTop: $('#respond').offset().top - 180 }, 400); if ( post && postId ) post.value = postId; parent.value = parentId; cancel.style.display = ''; cancel.onclick = function() { if ( edit ) exit_prev_edit(); var t = addComment, temp = t.I('wp-temp-form-div'), respond = t.I(t.respondId); t.I('comment_parent').value = '0'; if ( temp && respond ) { temp.parentNode.insertBefore(respond, temp); temp.parentNode.removeChild(temp); } this.style.display = 'none'; this.onclick = null; return false; }; try { t.I('comment').focus(); } catch(e) {} return false; }, I : function(e) { return document.getElementById(e); } }; // end addComment function exit_prev_edit() { $new_comm.show(); $new_sucs.show(); $('textarea').each(function() {this.value = ''}); edit = ''; } var wait = 8, submit_val = $submit.val(); function countdown() { if ( wait > 0 ) { $submit.val(wait); wait--; setTimeout(countdown, 1000); } else { $submit.val(submit_val).attr('disabled', false).fadeTo('slow', 1); wait = 8; } } }); }
czahoi/boxmoe-dove-
<|start_filename|>public/bower_components/angular-simple-logger/dist/index.js<|end_filename|> /** * angular-simple-logger * * @version: 0.0.4 * @author: <NAME> * @date: Tue Sep 22 2015 17:09:12 GMT-0400 (EDT) * @license: MIT */var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; angular.module('nemLogging', []).provider('nemSimpleLogger', function() { var LEVELS, Logger, _fns, maybeExecLevel; _fns = ['log', 'info', 'debug', 'warn', 'error']; LEVELS = { log: 1, info: 2, debug: 3, warn: 4, error: 5 }; maybeExecLevel = function(level, current, fn) { if (level >= current) { return fn(); } }; Logger = (function() { function Logger($log1) { var logFns; this.$log = $log1; this.spawn = bind(this.spawn, this); if (!this.$log) { throw 'internalLogger undefined'; } this.doLog = true; logFns = {}; _fns.forEach((function(_this) { return function(level) { return logFns[level] = function(msg) { if (_this.doLog) { return maybeExecLevel(LEVELS[level], _this.currentLevel, function() { return _this.$log[level](msg); }); } }; }; })(this)); this.LEVELS = LEVELS; this.currentLevel = LEVELS.error; _fns.forEach((function(_this) { return function(fnName) { return _this[fnName] = logFns[fnName]; }; })(this)); } Logger.prototype.spawn = function(newInternalLogger) { return new Logger(newInternalLogger || this.$log); }; return Logger; })(); this.decorator = [ '$log', function($delegate) { var log; log = new Logger($delegate); log.currentLevel = LEVELS.log; return log; } ]; this.$get = [ '$log', function($log) { return new Logger($log); } ]; return this; }); <|start_filename|>public/bower_components/angular-simple-logger/src/logger.coffee<|end_filename|> angular.module('nemLogging',[]) .provider 'nemSimpleLogger', -> _fns = ['log', 'info', 'debug', 'warn', 'error'] LEVELS = log: 1 info: 2 debug: 3 warn: 4 error: 5 maybeExecLevel = (level, current, fn) -> fn() if level >= current class Logger constructor: (@$log) -> throw 'internalLogger undefined' unless @$log @doLog = true logFns = {} _fns.forEach (level) => logFns[level] = (msg) => if @doLog maybeExecLevel LEVELS[level], @currentLevel, => @$log[level](msg) @LEVELS = LEVELS @currentLevel = LEVELS.error _fns.forEach (fnName) => @[fnName] = logFns[fnName] spawn: (newInternalLogger) => new Logger(newInternalLogger or @$log) @decorator = ['$log', ($delegate) -> #app domain logger enables all logging by default log = new Logger($delegate) log.currentLevel = LEVELS.log log ] @$get = [ '$log', ($log) -> # console.log $log #default logging is error for specific domain new Logger($log) ] @ <|start_filename|>public/bower_components/angular-simple-logger/gulp/index.coffee<|end_filename|> require './tasks/' gulp = require 'gulp' gulp.task 'default', gulp.series 'clean', 'build', 'spec' #, 'watch' <|start_filename|>public/bower_components/angular-simple-logger/gulpfile.coffee<|end_filename|> ### gulpfile.js =========== Rather than manage one giant configuration file responsible for creating multiple tasks, each task has been broken out into its own file in gulp/tasks. Any file in that folder gets automatically required by the loop in ./gulp/index.js (required below). To add a new task, simply add a new task file to gulp/tasks. ### require('./gulp') <|start_filename|>public/bower_components/angular-simple-logger/gulp/tasks/build.coffee<|end_filename|> gulp = require 'gulp' gulpif = require 'gulp-if' insert = require 'gulp-insert' ourPackage = require '../../package.json' coffeelint = require 'gulp-coffeelint' coffee = require 'gulp-coffee' concat = require 'gulp-concat' {log} = require 'gulp-util' uglify = require 'gulp-uglify' coffeeOptions = bare: true date = new Date() header = """ /** * #{ourPackage.name} * * @version: #{ourPackage.version} * @author: #{ourPackage.author} * @date: #{date.toString()} * @license: #{ourPackage.license} */ """ gulp.task 'build', -> gulp.src('src/*.coffee') .pipe gulpif(/[.]coffee$/,coffeelint()) .pipe gulpif(/[.]coffee$/,coffeelint.reporter()) .pipe gulpif(/[.]coffee$/,coffee(coffeeOptions).on('error', log)) .pipe(insert.prepend(header)) .pipe concat 'index.js' .pipe(gulp.dest 'dist' ) .pipe concat 'angular-simple-logger.js' .pipe(gulp.dest 'dist' ) .pipe uglify() .pipe concat 'angular-simple-logger.min.js' .pipe(gulp.dest 'dist' ) <|start_filename|>public/bower_components/angular-simple-logger/coffeelint.json<|end_filename|> { "camel_case_classes": { "level": "error" }, "max_line_length": { "value": 125, "level": "ignore", "limitComments": false }, "no_backticks": { "level": "ignore" }, "no_debugger": { "level": "warn" }, "no_plusplus": { "level": "error" }, "no_stand_alone_at": { "level": "ignore" }, "no_tabs": { "level": "error" }, "no_throwing_strings": { "level": "ignore" }, "no_trailing_semicolons": { "level": "error" }, "no_trailing_whitespace": { "level": "error", "allowed_in_comments": true, "allowed_in_empty_lines": true }, "no_unnecessary_double_quotes": { "level": "error" }, "no_unnecessary_fat_arrows": { "level": "error" }, "non_empty_constructor_needs_parens": { "level": "ignore" }, "no_interpolation_in_single_quotes":{ "level": "error" } } <|start_filename|>public/bower_components/angular-simple-logger/gulp/tasks/index.coffee<|end_filename|> requireDirectory = require 'require-directory' module.exports = requireDirectory(module)
shabeermothi/datart
<|start_filename|>lib/ui/home.dart<|end_filename|> import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:snaphunt/routes.dart'; import 'package:snaphunt/services/auth.dart'; import 'package:snaphunt/services/connectivity.dart'; import 'package:snaphunt/utils/utils.dart'; import 'package:snaphunt/widgets/common/fancy_button.dart'; import 'package:snaphunt/widgets/common/wave.dart'; class Home extends StatefulWidget { static Route<dynamic> route() { return MaterialPageRoute( builder: (BuildContext context) => const Home(), ); } const Home({ Key key, }) : super(key: key); @override _HomeState createState() => _HomeState(); } class HomeFancyButton extends StatelessWidget { final String text; final Color color; final Function onPressed; final Widget child; final double width; const HomeFancyButton( {Key key, this.text, this.color, this.onPressed, this.child, this.width = 220}) : super(key: key); @override Widget build(BuildContext context) { return FancyButton( child: SizedBox( width: width, child: child, ), size: 70, color: color, onPressed: onPressed, ); } } class _HomeState extends State<Home> { @override Widget build(BuildContext context) { var connectionStatus = Provider.of<ConnectivityStatus>(context); return Scaffold( backgroundColor: Colors.white, body: SafeArea( child: SizedBox.expand( child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.center, mainAxisSize: MainAxisSize.max, children: <Widget>[ Container( padding: EdgeInsets.only(left: 30, right: 30, top: 50), color: Colors.white, child: Image.asset('assets/main.png', height: 185), ), Column( mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[ const UserInfo(), const SizedBox(height: 32.0), HomeFancyButton( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( "Singleplayer", style: TextStyle(color: Colors.white, fontSize: 18), ), ]), color: Colors.orange, onPressed: () { Navigator.of(context) .pushNamed(Router.singlePlayerSettings); }, ), const SizedBox(height: 18.0), HomeFancyButton( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( "Multiplayer", style: TextStyle(color: Colors.white, fontSize: 18), ), ]), color: connectionStatus == ConnectivityStatus.Offline ? Colors.grey : Colors.blue, onPressed: connectionStatus == ConnectivityStatus.Offline ? () { showAlertDialog( context: context, title: 'You are offline!', body: 'Internet connection is needed to play online', ); } : () { Navigator.of(context).pushNamed(Router.lobby); }, ), const SizedBox(height: 18.0), Container( child: HomeFancyButton( width: 125, child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Padding( padding: const EdgeInsets.all(0), child: Icon( Icons.power_settings_new, color: Colors.white, size: 18, ), ), Container( margin: EdgeInsets.only(left: 2), child: Text( "Logout", style: TextStyle( color: Colors.white, fontSize: 18), )) ], ), onPressed: () { Auth.of(context).logout(); }, color: Colors.red, ), ), ], ), CustomWaveWidget() ], ), ), ), ); } } class UserInfo extends StatelessWidget { const UserInfo({ Key key, }) : super(key: key); @override Widget build(BuildContext context) { final user = Provider.of<FirebaseUser>(context, listen: false); return Container( child: Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, mainAxisSize: MainAxisSize.max, children: <Widget>[ UserAvatar( photoUrl: user.photoUrl, ), SizedBox(width: 15), Text( user.displayName, style: TextStyle( fontSize: 28, fontWeight: FontWeight.w400, ), maxLines: 2, ) ], ), ); } } /// Displays the user's image class UserAvatar extends StatelessWidget { final String photoUrl; final double height; final Color borderColor; const UserAvatar({ Key key, this.photoUrl, this.height = 70.0, this.borderColor = Colors.orange, }) : super(key: key); @override Widget build(BuildContext context) { return Column( children: <Widget>[ Material( elevation: 2.0, shape: CircleBorder( side: BorderSide(color: borderColor, width: 3.0), ), color: Colors.black, clipBehavior: Clip.antiAlias, child: SizedBox( width: height, height: height, child: photoUrl != null ? Image.network(photoUrl) : Icon( Icons.person, color: Colors.white, size: 72.0, ), ), ), ], ); } } <|start_filename|>lib/widgets/multiplayer/create_buttons.dart<|end_filename|> import 'package:flutter/material.dart'; import 'package:snaphunt/constants/app_theme.dart'; import 'package:snaphunt/widgets/common/fancy_button.dart'; class CreateButtons extends StatelessWidget { final Function onCreate; final String cancelLabel; final String createLabel; const CreateButtons({ Key key, this.onCreate, this.cancelLabel = 'Cancel', this.createLabel = 'Create Room', }) : super(key: key); @override Widget build(BuildContext context) { return Container( margin: const EdgeInsets.symmetric(horizontal: 16.0), child: Row( mainAxisSize: MainAxisSize.max, crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Expanded( child: FancyButton( child: Center( child: Text( cancelLabel, style: fancy_button_style, ), ), color: Colors.blueGrey, size: 60, onPressed: () { Navigator.of(context).pop(); }, ), ), SizedBox(width: 15), Expanded( child: FancyButton( child: Center( child: Text( createLabel, style: fancy_button_style, ), ), color: Colors.deepOrangeAccent, size: 60, onPressed: onCreate, ), ), ], ), ); } } <|start_filename|>lib/main.dart<|end_filename|> import 'package:camera/camera.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:provider/provider.dart'; import 'package:snaphunt/data/repository.dart'; import 'package:snaphunt/routes.dart'; import 'package:snaphunt/services/auth.dart'; import 'package:snaphunt/services/connectivity.dart'; import 'package:snaphunt/ui/home.dart'; import 'package:snaphunt/ui/login.dart'; import 'package:snaphunt/utils/utils.dart'; import 'package:snaphunt/widgets/common/custom_scroll.dart'; List<CameraDescription> cameras; Future<void> main() async { WidgetsFlutterBinding.ensureInitialized(); SystemChrome.setPreferredOrientations([ DeviceOrientation.portraitUp, DeviceOrientation.portraitDown, ]); cameras = await availableCameras(); openDB().then((_) async { initDB(); runApp(App(auth: await Auth.create())); }); } class App extends StatefulWidget { const App({ Key key, @required this.auth, }) : super(key: key); final Auth auth; @override _AppState createState() => _AppState(); } class _AppState extends State<App> { final _navigatorKey = GlobalKey<NavigatorState>(); FirebaseUser currentUser; @override void initState() { super.initState(); Repository.instance.updateLocalWords(); currentUser = widget.auth.init(_onUserChanged); } void _onUserChanged() { final user = widget.auth.currentUser.value; if (currentUser == null && user != null) { Repository.instance.updateUserData(user); _navigatorKey.currentState .pushAndRemoveUntil(Home.route(), (route) => false); } else if (currentUser != null && user == null) { _navigatorKey.currentState .pushAndRemoveUntil(Login.route(), (route) => false); } currentUser = user; } @override void dispose() { widget.auth.dispose(_onUserChanged); super.dispose(); } @override Widget build(BuildContext context) { return MultiProvider( providers: <SingleChildCloneableWidget>[ Provider<Auth>.value(value: widget.auth), ValueListenableProvider<FirebaseUser>.value( value: widget.auth.currentUser), StreamProvider<ConnectivityStatus>.controller( builder: (context) => ConnectivityService().connectionStatusController, ) ], child: MaterialApp( title: 'SnapHunt', theme: ThemeData( primaryColor: Colors.orange, textTheme: TextTheme(), fontFamily: 'SF_Atarian_System', ), navigatorKey: _navigatorKey, onGenerateRoute: Router.generateRoute, builder: (context, child) { return ScrollConfiguration( behavior: NoOverFlowScrollBehavior(), child: child, ); }, home: currentUser == null ? const Login() : const Home(), ), ); } } <|start_filename|>lib/ui/login.dart<|end_filename|> import 'package:flutter/material.dart'; import 'package:snaphunt/routes.dart'; import 'package:snaphunt/services/auth.dart'; import 'package:snaphunt/widgets/common/fancy_button.dart'; import '../widgets/common/wave.dart'; class Login extends StatefulWidget { static Route<dynamic> route() { return MaterialPageRoute( builder: (BuildContext context) => const Login(), ); } const Login({ Key key, }) : super(key: key); @override _LoginState createState() => _LoginState(); } class LoginFancyButton extends StatelessWidget { final String text; final Color color; final Function onPressed; const LoginFancyButton({ Key key, this.text, this.color, this.onPressed, }) : super(key: key); @override Widget build(BuildContext context) { return FancyButton( child: SizedBox( width: 200, child: Center( child: Text( text, style: TextStyle(color: Colors.white, fontSize: 18), ), ), ), size: 70, color: color, onPressed: onPressed, ); } } class _LoginState extends State<Login> { Future _loginFuture; void _onLoginWithGooglePressed() { setState(() { _loginFuture = Auth.of(context).loginWithGoogle(); }); } void _onHowToPlay() { Navigator.of(context).pushNamed(Router.howToPlay); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, body: SafeArea( child: SizedBox.expand( child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Image.asset('assets/top.png', scale: 1), Image.asset('assets/main.png', height: 185), FutureBuilder( future: _loginFuture, builder: (BuildContext context, AsyncSnapshot snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return const Center( child: CircularProgressIndicator(), ); } return Padding( padding: const EdgeInsets.symmetric(horizontal: 0.0), child: Column( children: <Widget>[ Container( child: LoginFancyButton( text: 'Login with Google', color: Color(0xffFF951A), onPressed: _onLoginWithGooglePressed, ), ), Container( margin: const EdgeInsets.only(top: 18.0), child: LoginFancyButton( text: 'How to Play', color: Colors.grey, onPressed: _onHowToPlay, ), ), if (snapshot.hasError) Container( width: double.infinity, margin: const EdgeInsets.symmetric(vertical: 16.0), padding: const EdgeInsets.all(12.0), decoration: BoxDecoration( border: Border.all(color: Theme.of(context).errorColor), borderRadius: const BorderRadius.all(Radius.circular(2.0)), color: Theme.of(context).errorColor.withOpacity(0.6), ), child: Text( snapshot.error.toString(), style: TextStyle( color: Colors.white, ), textAlign: TextAlign.center, ), ), ], ), ); }, ), Container( alignment: Alignment.bottomCenter, child: Column(children: <Widget>[ Container( margin: EdgeInsets.only(bottom: 12), child: Text("Flutter PH Hackathon Entry", style: TextStyle( color: Colors.grey, fontSize: 16, fontWeight: FontWeight.bold)), ), CustomWaveWidget(), ])), ], )), ), ); } } <|start_filename|>lib/widgets/multiplayer/join_room_dialog.dart<|end_filename|> import 'package:flutter/material.dart'; import 'package:flutter_barcode_scanner/flutter_barcode_scanner.dart'; import 'package:snaphunt/constants/app_theme.dart'; import 'package:snaphunt/widgets/common/fancy_button.dart'; import 'package:flutter/services.dart'; class JoinRoom extends StatelessWidget { Future<String> scanQR() async { String barcodeScanRes; try { barcodeScanRes = await FlutterBarcodeScanner.scanBarcode( "#ff6666", "Cancel", true, ScanMode.QR); } on PlatformException { barcodeScanRes = null; } catch (ex) { barcodeScanRes = null; } return barcodeScanRes; } @override Widget build(BuildContext context) { final controller = TextEditingController(); return AlertDialog( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(18.0), ), elevation: 5, title: Center( child: Text( 'Enter Room Code', style: TextStyle( fontSize: 28, fontWeight: FontWeight.bold, ), ), ), content: SingleChildScrollView( scrollDirection: Axis.vertical, child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ DialogCardTextField(controller: controller), const SizedBox(height: 15), DialogFancyButton( text: 'Join Room', color: Colors.deepOrangeAccent, onPressed: () { final code = controller.text; if (code != null && code.isNotEmpty) { Navigator.of(context).pop(code); } }, ), const SizedBox(height: 10), const DividerDialog(), const SizedBox(height: 20), DialogFancyButton( text: 'Scan QR Code', color: Colors.orange, onPressed: () async { final code = await scanQR(); if (code != null && code != '-1') { Navigator.of(context).pop(code); } }, ), SizedBox(height: 15), DialogFancyButton( text: 'Close', color: Colors.blueGrey, onPressed: () { Navigator.of(context).pop(); }, ), ], ), ), ); } } class DialogFancyButton extends StatelessWidget { final String text; final Color color; final Function onPressed; const DialogFancyButton({ Key key, this.text, this.color, this.onPressed, }) : super(key: key); @override Widget build(BuildContext context) { return FancyButton( child: SizedBox( width: 150, child: Center( child: Text( text, style: fancy_button_style, ), ), ), size: 60, color: color, onPressed: onPressed, ); } } class DialogCardTextField extends StatelessWidget { final TextEditingController controller; const DialogCardTextField({Key key, this.controller}) : super(key: key); @override Widget build(BuildContext context) { return Container( margin: const EdgeInsets.symmetric( horizontal: 8.0, vertical: 2.0, ), height: 65, child: Card( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(8.0), ), elevation: 3, child: Container( width: 300, margin: EdgeInsets.all(8.0), child: Row( mainAxisSize: MainAxisSize.max, crossAxisAlignment: CrossAxisAlignment.baseline, textBaseline: TextBaseline.alphabetic, children: <Widget>[ Expanded( child: Container( child: TextField( textAlign: TextAlign.center, controller: controller, keyboardType: TextInputType.text, maxLines: 1, decoration: InputDecoration( border: InputBorder.none, ), ), padding: const EdgeInsets.symmetric(horizontal: 8.0), ), ) ], ), ), ), ); } } class DividerDialog extends StatelessWidget { const DividerDialog({Key key}) : super(key: key); @override Widget build(BuildContext context) { return Row( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Expanded( child: Container( height: 1, color: Colors.blueGrey, ), ), SizedBox( width: 60, child: Center( child: Text( 'or', style: TextStyle(fontSize: 18), ), ), ), Expanded( child: Container( height: 1, color: Colors.blueGrey, ), ), ], ); } } <|start_filename|>lib/services/auth.dart<|end_filename|> import 'dart:async'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:google_sign_in/google_sign_in.dart'; import 'package:provider/provider.dart'; // src: https://gist.github.com/slightfoot/6f97d6c1ec4eb52ce880c6394adb1386 class Auth { static Future<Auth> create() async { final currentUser = await FirebaseAuth.instance.currentUser(); return Auth._(currentUser); } static Auth of(BuildContext context) { return Provider.of<Auth>(context, listen: false); } Auth._( FirebaseUser currentUser, ) : this.currentUser = ValueNotifier<FirebaseUser>(currentUser); final ValueNotifier<FirebaseUser> currentUser; final _googleSignIn = GoogleSignIn(); final _firebaseAuth = FirebaseAuth.instance; StreamSubscription<FirebaseUser> _authSub; FirebaseUser init(VoidCallback onUserChanged) { currentUser.addListener(onUserChanged); _authSub = _firebaseAuth.onAuthStateChanged.listen((FirebaseUser user) { currentUser.value = user; }); return currentUser.value; } void dispose(VoidCallback onUserChanged) { currentUser.removeListener(onUserChanged); _authSub.cancel(); } Future<void> loginWithEmailAndPassword(String email, String password) async { try { await _firebaseAuth.signInWithEmailAndPassword(email: email, password: password); } catch (e, st) { throw _getAuthException(e, st); } } Future<void> loginWithGoogle() async { try { final account = await _googleSignIn.signIn(); if (account == null) { throw AuthException.cancelled; } final auth = await account.authentication; await _firebaseAuth.signInWithCredential( GoogleAuthProvider.getCredential(idToken: auth.idToken, accessToken: auth.accessToken), ); } catch (e, st) { throw _getAuthException(e, st); } } Future<void> logout() async { try { await _firebaseAuth.signOut(); await _googleSignIn.signOut(); } catch (e, st) { FlutterError.reportError(FlutterErrorDetails(exception: e, stack: st)); } } AuthException _getAuthException(dynamic e, StackTrace st) { if (e is AuthException) { return e; } FlutterError.reportError(FlutterErrorDetails(exception: e, stack: st)); if (e is PlatformException) { switch (e.code) { case 'ERROR_INVALID_EMAIL': throw const AuthException('Please check your email address.'); case 'ERROR_WRONG_PASSWORD': throw const AuthException('Please check your password.'); case 'ERROR_USER_NOT_FOUND': throw const AuthException('User not found. Is that the correct email address?'); case 'ERROR_USER_DISABLED': throw const AuthException('Your account has been disabled. Please contact support'); case 'ERROR_TOO_MANY_REQUESTS': throw const AuthException('You have tried to login too many times. Please try again later.'); } } throw const AuthException('Sorry, an error occurred. Please try again.'); } } class AuthException implements Exception { static const cancelled = AuthException('cancelled'); const AuthException(this.message); final String message; @override String toString() => message; } <|start_filename|>lib/ui/singleplayer/single_result.dart<|end_filename|> import 'package:flutter/material.dart'; import 'package:snaphunt/model/hunt.dart'; import 'package:snaphunt/ui/home.dart'; import 'package:snaphunt/widgets/common/fancy_button.dart'; import 'package:snaphunt/widgets/common/wave.dart'; class ResultScreenSinglePlayer extends StatelessWidget { final bool isHuntFinished; final List<Hunt> objects; final Duration duration; const ResultScreenSinglePlayer( {Key key, this.isHuntFinished, this.objects, this.duration}) : super(key: key); String formatHHMMSS(int seconds) { int hours = (seconds / 3600).truncate(); seconds = (seconds % 3600).truncate(); int minutes = (seconds / 60).truncate(); String hoursStr = (hours).toString().padLeft(2, '0'); String minutesStr = (minutes).toString().padLeft(2, '0'); String secondsStr = (seconds % 60).toString().padLeft(2, '0'); if (hours == 0) { return "$minutesStr:$secondsStr"; } return "$hoursStr:$minutesStr:$secondsStr"; } @override Widget build(BuildContext context) { final found = objects.where((hunt) => hunt.isFound).length; return Scaffold( body: Container( color: Colors.white, height: double.infinity, child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Image.asset('assets/top.png', scale: 1), // Image.asset('assets/main.png', height: 185), const SizedBox(height: 15), const UserInfo(), const SizedBox(height: 20), Text( isHuntFinished ? 'Congrats! You found all items' : 'Better luck next time!', maxLines: 2, style: TextStyle( fontSize: 32, fontWeight: FontWeight.w300, ), ), const SizedBox(height: 25), Text( '$found/${objects.length} found', style: TextStyle( fontSize: 24, fontWeight: FontWeight.w300, ), ), Text( 'in ${formatHHMMSS(duration.inSeconds)}!', style: TextStyle( fontSize: 24, fontWeight: FontWeight.w300, ), ), const SizedBox(height: 20), FancyButton( child: Text( "Back", style: TextStyle( color: Colors.white, fontSize: 18, ), ), size: 70, color: Colors.blue, onPressed: () { Navigator.of(context).pop(); }, ), CustomWaveWidget() ], )), ); } } <|start_filename|>lib/widgets/multiplayer/host_start_button.dart<|end_filename|> import 'package:flutter/material.dart'; import 'package:snaphunt/constants/app_theme.dart'; import 'package:snaphunt/widgets/common/fancy_button.dart'; class HostStartButton extends StatelessWidget { final bool canStartGame; final Function onGameStart; const HostStartButton({ Key key, this.canStartGame, this.onGameStart, }) : super(key: key); @override Widget build(BuildContext context) { return Container( child: Column( mainAxisSize: MainAxisSize.max, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ FancyButton( child: Text( 'BEGIN HUNT', style: fancy_button_style, ), color: canStartGame ? Colors.deepOrangeAccent : Colors.grey, size: 70, onPressed: canStartGame ? onGameStart : null, ), SizedBox(height: 10), ], ), ); } } <|start_filename|>lib/routes.dart<|end_filename|> import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:snaphunt/stores/game_model.dart'; import 'package:snaphunt/ui/home.dart'; import 'package:snaphunt/ui/login.dart'; import 'package:snaphunt/ui/how_to_play.dart'; import 'package:snaphunt/ui/multiplayer/create_room.dart'; import 'package:snaphunt/ui/multiplayer/lobby.dart'; import 'package:snaphunt/ui/multiplayer/multiplayer.dart'; import 'package:snaphunt/ui/multiplayer/multiplayer_result.dart'; import 'package:snaphunt/ui/multiplayer/room.dart'; import 'package:snaphunt/ui/singleplayer/single_result.dart'; import 'package:snaphunt/ui/singleplayer/single_settings.dart'; import 'package:snaphunt/ui/singleplayer/singleplayer.dart'; class Router { static const String home = '/'; static const String login = '/login'; static const String howToPlay = '/howToPlay'; static const String lobby = '/multiplayer'; static const String create = '/createRoom'; static const String room = '/room'; static const String game = '/game'; static const String resultMulti = '/multiplayerResult'; static const String singlePlayerSettings = '/singleplayerSettings'; static const String singlePlayer = '/singleplayer'; static const String resultSingle = '/singleplayerResult'; static Route<dynamic> generateRoute(RouteSettings settings) { switch (settings.name) { case home: return MaterialPageRoute(builder: (_) => Home()); case lobby: return MaterialPageRoute(builder: (_) => Lobby()); case create: return MaterialPageRoute(builder: (_) => CreateRoom()); case game: final args = settings.arguments as List; return MaterialPageRoute( builder: (_) => MultiPlayer( game: args[0], userId: args[1], players: args[2], ), ); case room: final args = settings.arguments as List; return MaterialPageRoute( builder: (_) => ChangeNotifierProvider( builder: (_) => GameModel( args[0], args[1], args[2], ), child: Room(), ), ); case resultMulti: final args = settings.arguments as List; return MaterialPageRoute( builder: (_) => ResultMultiPlayer( gameId: args[0], title: args[1], duration: args[2], ), ); case singlePlayerSettings: return MaterialPageRoute(builder: (_) => SinglePlayerSettings()); case singlePlayer: final args = settings.arguments as List; return MaterialPageRoute( builder: (_) => SinglePlayer( numOfObjects: args[0], duration: args[1], ), ); case resultSingle: final args = settings.arguments as List; return MaterialPageRoute( builder: (_) => ResultScreenSinglePlayer( isHuntFinished: args[0], objects: args[1], duration: args[2], ), ); case howToPlay: return MaterialPageRoute(builder: (_) => HowToPlay()); case login: default: return MaterialPageRoute(builder: (_) => Login()); } } } <|start_filename|>lib/stores/hunt_model.dart<|end_filename|> import 'dart:async'; import 'dart:io'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_ml_vision/firebase_ml_vision.dart'; import 'package:flutter/material.dart'; import 'package:snaphunt/data/repository.dart'; import 'package:snaphunt/model/hunt.dart'; import 'package:vibration/vibration.dart'; class HuntModel with ChangeNotifier { HuntModel({ this.objects, this.timeLimit, this.isMultiplayer = false, this.gameId, this.userId, this.timeDuration, }); final List<Hunt> objects; int get objectsFound => objects.where((hunt) => hunt.isFound).length; Hunt get nextNotFound { Hunt hunt; try { hunt = objects.where((hunt) => !hunt.isFound).first; } catch (e) { hunt = null; } return hunt; } final DateTime timeLimit; // multi final bool isMultiplayer; final String gameId; final String userId; final int timeDuration; bool isGameEnd = false; StreamSubscription<DocumentSnapshot> gameStream; final ImageLabeler _imageLabeler = FirebaseVision.instance.imageLabeler( ImageLabelerOptions( confidenceThreshold: 0.65, ), ); bool isTimeUp = false; bool isHuntComplete = false; final Stopwatch duration = Stopwatch(); final repository = Repository.instance; Timer timer; @override void addListener(listener) { super.addListener(listener); init(); if (isMultiplayer) { initMultiplayer(); } } @override void dispose() { super.dispose(); timer?.cancel(); if (isMultiplayer) { disposeMultiplayer(); } } void init() { final limit = Duration(seconds: timeLimit.difference(DateTime.now()).inSeconds); duration.start(); timer = Timer(limit, () { isTimeUp = true; if (isMultiplayer) { repository.endGame(gameId); } notifyListeners(); duration.stop(); }); } void initMultiplayer() { gameStream = repository.gameSnapshot(gameId).listen(gameStatusListener); } void disposeMultiplayer() { gameStream.cancel(); } void gameStatusListener(DocumentSnapshot snapshot) async { final status = snapshot.data['status']; if (status == 'end') { isGameEnd = true; notifyListeners(); } } void _scanImage(File image) async { final FirebaseVisionImage visionImage = FirebaseVisionImage.fromFile(image); final results = await _imageLabeler.processImage(visionImage); checkWords(results); } void checkWords(List<ImageLabel> scanResults) { hasMatch(scanResults).then((result) { if (result != 0) { successVibrate(); incrementScore(result); checkComplete().then((complete) { if (complete) { isHuntComplete = true; if (isMultiplayer) { repository.endGame(gameId); } } }); } else { failVibrate(); } }); notifyListeners(); } Future<int> hasMatch(List<ImageLabel> scanResults) async { int count = 0; scanResults.forEach((results) { objects.where((hunt) => !hunt.isFound).forEach((words) { if (results.text.toLowerCase() == words.word.toLowerCase()) { count++; words.isFound = true; } }); }); return count; } void incrementScore(int increment) { if (isMultiplayer && increment != 0) { repository.updateUserScore(gameId, userId, increment); } } Future<bool> checkComplete() async { bool isComplete = false; if (objects.where((hunt) => !hunt.isFound).isEmpty) { isComplete = true; } return isComplete; } void onCameraPressed(String path) { _scanImage(File(path)); } void successVibrate() { Vibration.vibrate(pattern: [0, 250, 250, 250]); } void failVibrate() { Vibration.vibrate(pattern: [0, 250]); } } <|start_filename|>lib/widgets/multiplayer/player_await_button.dart<|end_filename|> import 'package:flutter/material.dart'; class PlayerAwaitButton extends StatelessWidget { final bool canStartGame; const PlayerAwaitButton({ Key key, this.canStartGame, }) : super(key: key); @override Widget build(BuildContext context) { return Container( child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ CircularProgressIndicator(), const SizedBox(height: 14), Text(canStartGame ? 'Waiting for host' : 'Waiting for player') ], ), ); } } <|start_filename|>lib/widgets/multiplayer/room_loading.dart<|end_filename|> import 'package:flutter/material.dart'; class RoomLoading extends StatelessWidget { @override Widget build(BuildContext context) { return Center( child: Column( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ CircularProgressIndicator(), SizedBox(height: 10), Text('Retrieving game') ], ), ); } } <|start_filename|>lib/widgets/common/wave.dart<|end_filename|> import 'package:flutter/material.dart'; import 'package:wave/config.dart'; import 'package:wave/wave.dart'; class CustomWaveWidget extends StatelessWidget { @override Widget build(BuildContext context) { return WaveWidget( duration: 1, config: CustomConfig( gradients: [ [Colors.orange, Color(0xEEF44336)], [Colors.red[200], Color(0x77E57373)], [Colors.orange, Color(0x66FF9800)], [Colors.yellow[800], Color(0x55FFEB3B)] ], durations: [35000, 19440, 10800, 6000], heightPercentages: [0.20, 0.23, 0.25, 0.30], blur: MaskFilter.blur(BlurStyle.solid, 2), gradientBegin: Alignment.bottomLeft, gradientEnd: Alignment.topRight, ), waveAmplitude: 1.0, backgroundColor: Colors.white, size: Size(double.maxFinite, 50.0)); } } <|start_filename|>lib/stores/player_hunt_model.dart<|end_filename|> import 'dart:async'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:snaphunt/data/repository.dart'; import 'package:snaphunt/model/player.dart'; class PlayHuntModel with ChangeNotifier { final String gameId; final List<Player> players; PlayHuntModel({this.players, this.gameId}); StreamSubscription<QuerySnapshot> playerStream; final repository = Repository.instance; @override void addListener(listener) { super.addListener(listener); initStreams(); } @override void dispose() { playerStream.cancel(); super.dispose(); } void initStreams() { playerStream = repository.playersSnapshot(gameId).listen(playerListener); } void playerListener(QuerySnapshot snapshot) { snapshot.documentChanges.forEach((DocumentChange change) async { if (DocumentChangeType.modified == change.type) { int index = players.indexWhere( (player) => player.user.uid == change.document.documentID); if (index != -1) { players[index].score = change.document.data['score']; sort(); notifyListeners(); } } }); } void sort() { players.sort((a, b) => b.score.compareTo(a.score)); } } <|start_filename|>lib/stores/game_model.dart<|end_filename|> import 'dart:async'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:snaphunt/constants/game_status_enum.dart'; import 'package:snaphunt/data/repository.dart'; import 'package:snaphunt/model/game.dart'; import 'package:snaphunt/model/player.dart'; class GameModel with ChangeNotifier { Game _game; Game get game => _game; bool _isHost; bool get isHost => _isHost; String _userId; String get userId => _userId; bool _isLoading = false; bool get isLoading => _isLoading; GameStatus _status = GameStatus.waiting; GameStatus get status => _status; bool _isGameStart = false; bool get isGameStart => _isGameStart; bool _canStartGame = false; bool get canStartGame => _canStartGame; StreamSubscription<DocumentSnapshot> gameStream; StreamSubscription<QuerySnapshot> playerStream; List<Player> _players = []; List<Player> get players => _players; final repository = Repository.instance; GameModel(this._game, this._isHost, this._userId); @override void addListener(listener) { initRoom(); super.addListener(listener); } void initRoom() async { _isLoading = true; notifyListeners(); if (_isHost) { String id = await repository.createRoom(_game); _game.id = id; } await joinRoom(); _isLoading = false; notifyListeners(); initStreams(); } @override void dispose() { onDispose(); super.dispose(); } void initStreams() { gameStream = repository.gameSnapshot(_game.id).listen(gameStatusListener); playerStream = repository.playersSnapshot(_game.id).listen(playerListener); } void gameStatusListener(DocumentSnapshot snapshot) async { final status = snapshot.data['status']; if (status == 'cancelled') { _status = GameStatus.cancelled; notifyListeners(); } else if (status == 'in_game') { _status = GameStatus.game; _game = Game.fromJson(snapshot.data); _game.id = snapshot.documentID; notifyListeners(); } } void playerListener(QuerySnapshot snapshot) { snapshot.documentChanges.forEach((DocumentChange change) async { print(change.type); print(change.document.documentID); if (DocumentChangeType.added == change.type) { players.add( Player(user: await repository.getUser(change.document.documentID))); } else if (DocumentChangeType.removed == change.type) { if (change.document.documentID == _userId) { _status = GameStatus.kicked; notifyListeners(); return; } players.removeWhere( (player) => player.user.uid == change.document.documentID); } checkCanStartGame(); notifyListeners(); }); } void checkCanStartGame() { if (players.length >= 2) { _canStartGame = true; } else { _canStartGame = false; } } void onKickPlayer(String userId) { repository.kickPlayer(_game.id, userId); } void onDispose() { if (GameStatus.game != _status) { if (_isHost) { repository.cancelRoom(_game.id); } else { repository.leaveRoom(_game.id, _userId); } } gameStream.cancel(); playerStream.cancel(); } void onGameStart() { if (_canStartGame) { _isGameStart = true; repository.startGame(_game.id, numOfItems: _game.noOfItems); } } Future joinRoom() async { final playerCount = await repository.getGamePlayerCount(_game.id); if (playerCount >= _game.maxPlayers) { _status = GameStatus.full; return Future.value(null); } return repository.joinRoom(_game.id, _userId); } } <|start_filename|>lib/ui/multiplayer/multiplayer.dart<|end_filename|> import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:snaphunt/model/game.dart'; import 'package:snaphunt/model/player.dart'; import 'package:snaphunt/stores/hunt_model.dart'; import 'package:snaphunt/widgets/common/hunt_game.dart'; import 'package:snaphunt/utils/utils.dart'; class MultiPlayer extends StatelessWidget { final Game game; final String userId; final List<Player> players; const MultiPlayer({ Key key, this.userId, this.players, this.game, }) : super(key: key); @override Widget build(BuildContext context) { return ChangeNotifierProvider( builder: (_) => HuntModel( objects: generateHuntObjectsFromList(game.words), timeLimit: game.gameStartTime.add(Duration(minutes: game.timeLimit)), isMultiplayer: true, gameId: game.id, userId: userId, timeDuration: game.timeLimit, ), child: HuntGame( title: game.name, players: players, ), ); } } <|start_filename|>lib/widgets/common/fancy_alert_dialog.dart<|end_filename|> import 'package:flutter/material.dart'; import 'package:snaphunt/constants/app_theme.dart'; import 'package:snaphunt/widgets/common/fancy_button.dart'; class FancyAlertDialog extends StatelessWidget { final String title; final String body; const FancyAlertDialog({Key key, this.title, this.body}) : super(key: key); @override Widget build(BuildContext context) { return AlertDialog( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(18.0), ), elevation: 5, title: Center( child: Text( title, style: TextStyle( fontSize: 32, fontWeight: FontWeight.bold, ), ), ), contentPadding: const EdgeInsets.fromLTRB(24, 32, 24, 18), content: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Text( body, textAlign: TextAlign.center, style: TextStyle(fontSize: 20), ), const SizedBox(height: 30), DialogFancyButtonExit( text: 'OKAY', color: Colors.orange, onPressed: () { Navigator.of(context).pop(); }, ) ], ), ); } } class DialogFancyButtonExit extends StatelessWidget { final String text; final Color color; final Function onPressed; const DialogFancyButtonExit({ Key key, this.text, this.color, this.onPressed, }) : super(key: key); @override Widget build(BuildContext context) { return FancyButton( child: Center( child: Text( text, style: fancy_button_style, ), ), size: 60, color: color, onPressed: onPressed, ); } } <|start_filename|>lib/widgets/multiplayer/room_exit_dialog.dart<|end_filename|> import 'package:flutter/material.dart'; import 'package:snaphunt/constants/app_theme.dart'; import 'package:snaphunt/widgets/common/fancy_button.dart'; class RoomExitDialog extends StatelessWidget { final String title; final String body; const RoomExitDialog({Key key, this.title, this.body}) : super(key: key); @override Widget build(BuildContext context) { return AlertDialog( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(18.0), ), elevation: 5, title: Center( child: Text( title, style: TextStyle( fontSize: 32, fontWeight: FontWeight.bold, ), ), ), contentPadding: const EdgeInsets.fromLTRB(24, 32, 24, 18), content: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ const SizedBox(height: 20), Text( body, textAlign: TextAlign.center, style: TextStyle(fontSize: 24, height: 0.9), ), const SizedBox(height: 40), Row( mainAxisSize: MainAxisSize.max, children: <Widget>[ Expanded( child: DialogFancyButtonExit( text: 'OKAY', color: Colors.orange, onPressed: () { Navigator.of(context).pop(true); }, ), ), SizedBox(width: 10), Expanded( child: DialogFancyButtonExit( text: 'CANCEL', color: Colors.blueGrey, onPressed: () { Navigator.of(context).pop(false); }, ), ) ], ), ], ), ); } } class DialogFancyButtonExit extends StatelessWidget { final String text; final Color color; final Function onPressed; const DialogFancyButtonExit({ Key key, this.text, this.color, this.onPressed, }) : super(key: key); @override Widget build(BuildContext context) { return FancyButton( child: Center( child: Text( text, style: fancy_button_style, ), ), size: 60, color: color, onPressed: onPressed, ); } } <|start_filename|>lib/utils/utils.dart<|end_filename|> import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:hive/hive.dart'; import 'package:path_provider/path_provider.dart'; import 'package:snaphunt/model/hunt.dart'; import 'package:snaphunt/widgets/common/fancy_alert_dialog.dart'; import 'package:flutter/services.dart' show rootBundle; void showAlertDialog({BuildContext context, String title, String body}) { showDialog( context: context, barrierDismissible: false, builder: (BuildContext context) => FancyAlertDialog( title: title, body: body, ), ); } Future<String> loadAsset() async { return await rootBundle.loadString('assets/default.json'); } Future openDB() async { final dir = await getApplicationDocumentsDirectory(); Hive.init(dir.path); return Future.wait([ Hive.openBox('words'), ]); } void initDB() async { final box = Hive.box('words'); if (box.isEmpty) { Map<String, dynamic> data = json.decode(await loadAsset()); box.put('version', data['version']); box.put('words', data['words']); } } List<String> generateWords([int numOfWords = 8]) { final box = Hive.box('words'); final List words = box.get('words'); words.shuffle(); return List<String>.generate(numOfWords, (index) => words[index]); } List<Hunt> generateHuntObjects([int numOfWords = 8]) { final List words = generateWords(numOfWords); return new List<Hunt>.generate(numOfWords, (index) { return Hunt(word: words[index]); }); } List<Hunt> generateHuntObjectsFromList(List<String> words) { return new List<Hunt>.generate(words.length, (index) { return Hunt(word: words[index]); }); } <|start_filename|>lib/widgets/common/countdown.dart<|end_filename|> import 'package:flutter/material.dart'; class CountDownTimer extends StatefulWidget { final DateTime timeLimit; const CountDownTimer({Key key, this.timeLimit}) : super(key: key); State createState() => new _CountDownTimerState(); } class _CountDownTimerState extends State<CountDownTimer> with TickerProviderStateMixin { int secondsRemaining; AnimationController _controller; Duration duration; String get timerDisplayString { Duration duration = _controller.duration * _controller.value; return formatHHMMSS(duration.inSeconds); } String formatHHMMSS(int seconds) { int hours = (seconds / 3600).truncate(); seconds = (seconds % 3600).truncate(); int minutes = (seconds / 60).truncate(); String hoursStr = (hours).toString().padLeft(2, '0'); String minutesStr = (minutes).toString().padLeft(2, '0'); String secondsStr = (seconds % 60).toString().padLeft(2, '0'); if (hours == 0) { return "$minutesStr:$secondsStr"; } return "$hoursStr:$minutesStr:$secondsStr"; } @override void initState() { super.initState(); final now = DateTime.now(); secondsRemaining = widget.timeLimit.difference(now).inSeconds; duration = new Duration(seconds: secondsRemaining); _controller = new AnimationController( vsync: this, duration: duration, ); _controller.reverse(from: secondsRemaining.toDouble()); } @override void didUpdateWidget(CountDownTimer oldWidget) { super.didUpdateWidget(oldWidget); if (secondsRemaining != secondsRemaining) { setState(() { duration = new Duration(seconds: secondsRemaining); _controller.dispose(); _controller = new AnimationController( vsync: this, duration: duration, ); _controller.reverse(from: secondsRemaining.toDouble()); }); } } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Center( child: AnimatedBuilder( animation: _controller, builder: (_, Widget child) { return Text( timerDisplayString, style: TextStyle( fontSize: 24, fontWeight: FontWeight.w600, color: Colors.white, ), ); }), ); } } <|start_filename|>lib/constants/game_status_enum.dart<|end_filename|> enum GameStatus { waiting, game, cancelled, kicked, full, } <|start_filename|>lib/model/user.dart<|end_filename|> class User { String uid; String email; String photoUrl; String displayName; User({ this.uid, this.email, this.photoUrl, this.displayName, }); User.fromJson(Map<String, dynamic> json) { uid = json['uid']; email = json['email']; photoUrl = json['photoURL']; displayName = json['displayName']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['uid'] = this.uid; data['email'] = this.email; data['photoURL'] = this.photoUrl; data['displayName'] = this.displayName; return data; } } <|start_filename|>lib/model/hunt.dart<|end_filename|> class Hunt { String word; bool isFound; Hunt({ this.word, this.isFound = false, }); Hunt.fromJson(Map<String, dynamic> json) { word = json['word']; isFound = json['isFound']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['word'] = this.word; data['isFound'] = this.isFound; return data; } } <|start_filename|>lib/constants/app_theme.dart<|end_filename|> import 'package:flutter/material.dart'; const fancy_button_style = TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.bold); final List<Color> user_colors = [ Colors.orange, Colors.purple, Colors.yellow, Colors.red, Colors.green, ]; <|start_filename|>lib/data/repository.dart<|end_filename|> import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:hive/hive.dart'; import 'package:snaphunt/model/game.dart'; import 'package:snaphunt/model/player.dart'; import 'package:snaphunt/model/user.dart'; import 'package:snaphunt/utils/utils.dart'; class Repository { static final Repository _singleton = Repository._(); Repository._(); factory Repository() => _singleton; static Repository get instance => _singleton; final Firestore _db = Firestore.instance; void updateUserData(FirebaseUser user) async { final DocumentReference ref = _db.collection('users').document(user.uid); return ref.setData({ 'uid': user.uid, 'email': user.email, 'photoURL': user.photoUrl, 'displayName': user.displayName, }, merge: true); } Future<String> createRoom(Game game) async { final DocumentReference ref = await _db.collection('games').add(game.toJson()); return ref.documentID; } Future<Game> retrieveGame(String roomId) async { Game game; try { final DocumentSnapshot ref = await _db.document('games/$roomId').get(); if (ref.data != null) { game = Game.fromJson(ref.data)..id = ref.documentID; } } catch (e) { print(e); } return game; } Future joinRoom(String roomId, String userId) async { return _db .document('games/$roomId') .collection('players') .document(userId) .setData({'status': 'active', 'score': 0}); } void cancelRoom(String roomId) async { await _db.document('games/$roomId').updateData({'status': 'cancelled'}); } void leaveRoom(String roomId, String userId) async { await _db .document('games/$roomId') .collection('players') .document(userId) .delete(); } void endGame(String roomId) async { await _db.document('games/$roomId').updateData({'status': 'end'}); } void startGame(String roomId, {int numOfItems = 8}) async { await _db.document('games/$roomId').updateData({ 'status': 'in_game', 'gameStartTime': Timestamp.now(), 'words': generateWords(numOfItems) }); } Future<String> getUserName(String uuid) async { final DocumentSnapshot ref = await _db.collection('users').document(uuid).get(); return ref['displayName']; } Future<User> getUser(String uuid) async { final DocumentSnapshot ref = await _db.collection('users').document(uuid).get(); return User.fromJson(ref.data); } Stream<DocumentSnapshot> gameSnapshot(String roomId) { return _db.collection('games').document(roomId).snapshots(); } Stream<QuerySnapshot> playersSnapshot(String gameId) { return _db .collection('games') .document(gameId) .collection('players') .snapshots(); } void kickPlayer(String gameId, String userId) async { await _db .collection('games') .document(gameId) .collection('players') .document(userId) .delete(); } Future<int> getGamePlayerCount(String gameId) async { final players = await _db .collection('games') .document(gameId) .collection('players') .getDocuments(); return players.documents.length; } void updateLocalWords() async { final box = Hive.box('words'); final DocumentSnapshot doc = await _db.document('words/words').get(); final localVersion = box.get('version'); final onlineVersion = doc.data['version']; if (localVersion != onlineVersion) { box.put('words', doc.data['words']); box.put('version', doc.data['version']); } } Future updateUserScore(String gameId, String userId, int increment) async { final DocumentReference ref = _db.document('games/$gameId/players/$userId'); return ref.setData({ 'score': FieldValue.increment(increment), }, merge: true); } Future<List<Player>> getPlayers(String gameId) async { List<Player> players = []; final QuerySnapshot ref = await _db .collection('games') .document(gameId) .collection('players') .getDocuments(); for (var document in ref.documents) { final DocumentSnapshot userRef = await _db.collection('users').document(document.documentID).get(); players.add(Player.fromJson(document.data, userRef.data)); } return players; } } <|start_filename|>lib/widgets/common/camera.dart<|end_filename|> import 'package:camera/camera.dart'; import 'package:flutter/material.dart'; import 'package:path/path.dart'; import 'package:path_provider/path_provider.dart'; import 'package:provider/provider.dart'; import 'package:snaphunt/main.dart'; import 'package:snaphunt/stores/hunt_model.dart'; class CameraScreen extends StatefulWidget { const CameraScreen({Key key}) : super(key: key); @override _CameraScreenState createState() => _CameraScreenState(); } class _CameraScreenState extends State<CameraScreen> with WidgetsBindingObserver { CameraController controller; String imagePath; int selectedCameraIdx = 0; @override void initState() { super.initState(); onNewCameraSelected(cameras[selectedCameraIdx]); WidgetsBinding.instance.addObserver(this); } @override void dispose() { WidgetsBinding.instance.removeObserver(this); super.dispose(); } @override void didChangeAppLifecycleState(AppLifecycleState state) { if (controller == null || !controller.value.isInitialized) { return; } if (state == AppLifecycleState.inactive) { controller?.dispose(); } else if (state == AppLifecycleState.resumed) { if (controller != null) { onNewCameraSelected(cameras[selectedCameraIdx]); } } } @override Widget build(BuildContext context) { return Scaffold( body: Stack( children: <Widget>[ Container( color: Colors.black, width: double.infinity, height: double.infinity, child: controller != null && controller.value.isInitialized ? AspectRatio( aspectRatio: controller.value.aspectRatio, child: CameraPreview(controller), ) : Center(child: CircularProgressIndicator()), ), Align( alignment: Alignment.bottomCenter, child: CameraRow( controller: controller, onCameraSwitch: _onSwitchCamera, ), ), ], ), ); } void _onSwitchCamera() { selectedCameraIdx = selectedCameraIdx < cameras.length - 1 ? selectedCameraIdx + 1 : 0; onNewCameraSelected(cameras[selectedCameraIdx]); } void onNewCameraSelected(CameraDescription cameraDescription) async { if (controller != null) { await controller.dispose(); } controller = CameraController( cameraDescription, ResolutionPreset.high, ); controller.addListener(() { if (mounted) setState(() {}); }); try { await controller.initialize(); } on CameraException catch (e) { print(e.description); } if (mounted) { setState(() {}); } } } class CameraRow extends StatelessWidget { final CameraController controller; final Function onCameraSwitch; const CameraRow({ Key key, this.controller, this.onCameraSwitch, }) : super(key: key); @override Widget build(BuildContext context) { return Container( color: Colors.black.withOpacity(0.4), height: 100, child: Stack( children: <Widget>[ Align( alignment: Alignment.center, child: CameraButton(controller: controller), ), Positioned( child: CameraSwapButton( onPressed: onCameraSwitch, ), height: 100, left: MediaQuery.of(context).size.width * 0.75, ) ], ), ); } } class CameraSwapButton extends StatelessWidget { final Function onPressed; const CameraSwapButton({Key key, this.onPressed}) : super(key: key); @override Widget build(BuildContext context) { return Container( decoration: BoxDecoration( shape: BoxShape.circle, border: Border.all( width: 1, color: Colors.white, ), ), child: IconButton( icon: Icon( Icons.switch_camera, color: Colors.white, ), onPressed: onPressed, ), ); } } class CameraButton extends StatelessWidget { final CameraController controller; const CameraButton({ Key key, this.controller, }) : super(key: key); Future<String> onCapturePressed() async { String _path; try { final path = join( (await getTemporaryDirectory()).path, '${DateTime.now()}.png', ); await controller.takePicture(path); _path = path; } catch (e) { print(e); } return _path; } @override Widget build(BuildContext context) { final model = Provider.of<HuntModel>(context, listen: false); return InkWell( onTap: () async { model.onCameraPressed(await onCapturePressed()); }, child: Container( padding: const EdgeInsets.all(6), height: 70, width: 70, decoration: BoxDecoration( shape: BoxShape.circle, color: Colors.deepOrange, ), child: Container( decoration: BoxDecoration( shape: BoxShape.circle, color: Colors.white, ), ), ), ); } } <|start_filename|>lib/ui/singleplayer/singleplayer.dart<|end_filename|> import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:snaphunt/stores/hunt_model.dart'; import 'package:snaphunt/utils/utils.dart'; import 'package:snaphunt/widgets/common/hunt_game.dart'; class SinglePlayer extends StatelessWidget { final int numOfObjects; final int duration; const SinglePlayer({Key key, this.numOfObjects, this.duration}) : super(key: key); @override Widget build(BuildContext context) { return ChangeNotifierProvider( builder: (_) => new HuntModel( objects: generateHuntObjects(numOfObjects), timeLimit: DateTime.now().add(Duration(minutes: duration)), ), child: HuntGame( title: 'SinglePlayer!', ), ); } } <|start_filename|>lib/widgets/multiplayer/lobby_buttons.dart<|end_filename|> import 'package:flutter/material.dart'; import 'package:snaphunt/constants/app_theme.dart'; import 'package:snaphunt/widgets/common/fancy_button.dart'; class LobbyButtons extends StatelessWidget { final Function onJoinRoom; final Function onCreateRoom; const LobbyButtons({Key key, this.onJoinRoom, this.onCreateRoom}) : super(key: key); @override Widget build(BuildContext context) { return Container( margin: const EdgeInsets.fromLTRB(4, 12, 4, 2), child: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ Expanded( child: Center( child: Text( 'Snap Rooms', maxLines: 2, style: TextStyle(fontSize: 28), ), ), ), Expanded( child: FancyButton( child: Center( child: Text( 'Join Room', style: fancy_button_style, ), ), color: Colors.orange, size: 60, onPressed: onJoinRoom, ), ), const SizedBox(width: 10), Expanded( child: FancyButton( child: Center( child: Text( 'Create Room', style: fancy_button_style, ), ), color: Colors.red, size: 60, onPressed: onCreateRoom, ), ), ], ), ); } } <|start_filename|>lib/widgets/common/loading.dart<|end_filename|> import 'package:flutter/material.dart'; class LoadingTextField extends StatefulWidget { @override _LoadingTextFieldState createState() => _LoadingTextFieldState(); } class _LoadingTextFieldState extends State<LoadingTextField> with SingleTickerProviderStateMixin { AnimationController _controller; Animation<double> animation; @override void initState() { super.initState(); _controller = AnimationController( vsync: this, duration: Duration(seconds: 1), ); animation = Tween<double>(begin: -1.0, end: 2.0).animate( CurvedAnimation(curve: Curves.easeInOutSine, parent: _controller)); animation.addStatusListener((status) { if (status == AnimationStatus.completed || status == AnimationStatus.dismissed) { _controller.repeat(); } else if (status == AnimationStatus.dismissed) { _controller.forward(); } }); _controller.forward(); } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { var brightness = Theme.of(context).brightness; return AnimatedBuilder( animation: animation, builder: (context, child) { return Padding( padding: const EdgeInsets.all(1.0), child: Container( width: 75, height: 8.0, decoration: myBoxDec(animation, brightness: brightness), ), ); }, ); } } Decoration myBoxDec(animation, {isCircle = false, brightness}) { final dark = [ Colors.grey[700], Colors.grey[600], Colors.grey[700], ]; final light = [ Color(0xfff6f7f9), Color(0xffe9ebee), Color(0xfff6f7f9), ]; return BoxDecoration( shape: isCircle ? BoxShape.circle : BoxShape.rectangle, gradient: LinearGradient( begin: Alignment.centerLeft, end: Alignment.centerRight, colors: brightness == Brightness.light ? light : dark, stops: [ // animation.value * 0.1, animation.value - 1, animation.value, animation.value + 1, // animation.value + 5, // 1.0, ], ), ); } <|start_filename|>lib/ui/multiplayer/room.dart<|end_filename|> import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:qr_flutter/qr_flutter.dart'; import 'package:snaphunt/constants/app_theme.dart'; import 'package:snaphunt/constants/game_status_enum.dart'; import 'package:snaphunt/routes.dart'; import 'package:snaphunt/stores/game_model.dart'; import 'package:snaphunt/ui/home.dart'; import 'package:snaphunt/utils/utils.dart'; import 'package:snaphunt/widgets/common/fancy_button.dart'; import 'package:snaphunt/widgets/multiplayer/host_start_button.dart'; import 'package:snaphunt/widgets/multiplayer/player_await_button.dart'; import 'package:snaphunt/widgets/multiplayer/room_exit_dialog.dart'; import 'package:snaphunt/widgets/multiplayer/room_loading.dart'; class Room extends StatelessWidget { void gameStatusListener(GameModel model, BuildContext context) { if (GameStatus.full == model.status) { Navigator.of(context).pop(); showAlertDialog( context: context, title: 'Room Full', body: 'Room already reached max players', ); } if (GameStatus.game == model.status) { Navigator.of(context).pushReplacementNamed( Router.game, arguments: [ model.game, model.userId, model.players, ], ); } if (GameStatus.cancelled == model.status) { Navigator.of(context).pop(); showAlertDialog( context: context, title: 'Game Cancelled', body: 'Game was cancelled by host!', ); } if (GameStatus.kicked == model.status) { Navigator.of(context).pop(); showAlertDialog( context: context, title: 'Kicked', body: 'You were kicked by the host!', ); } } @override Widget build(BuildContext context) { bool _isHost = false; return WillPopScope( onWillPop: () async { final roomCode = await showDialog<bool>( context: context, barrierDismissible: false, builder: (BuildContext context) { return RoomExitDialog( title: _isHost ? 'Delete room' : 'Leave room', body: _isHost ? 'Leaving the room will cancel the game' : 'Are you sure you want to leave from the room?', ); }, ); return roomCode; }, child: Scaffold( appBar: AppBar( iconTheme: IconThemeData( color: Colors.white, ), title: Text( 'Room', style: TextStyle(color: Colors.white), ), centerTitle: true, elevation: 0, ), body: Container( child: Consumer<GameModel>( builder: (context, model, child) { _isHost = model.isHost; if (model.isLoading) { return RoomLoading(); } WidgetsBinding.instance.addPostFrameCallback( (_) => gameStatusListener(model, context), ); return child; }, child: Column( children: <Widget>[ RoomDetails(), PlayerRow(), Expanded(child: PlayerList()), ], ), ), ), ), ); } } class RoomDetails extends StatelessWidget { const RoomDetails({Key key}) : super(key: key); @override Widget build(BuildContext context) { return Consumer<GameModel>(builder: (context, model, child) { return Container( height: MediaQuery.of(context).size.height * 0.35, width: double.infinity, // padding: const EdgeInsets.fromLTRB(16.0, 32.0, 16.0, 32.0), child: Column( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Row( children: <Widget>[ Container( color: Color(0xFEEBEBEB), width: MediaQuery.of(context).size.width / 2.75, height: 255, child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ const SizedBox(height: 20), QrImage( data: model.game.id, version: QrVersions.auto, size: 120.0, padding: EdgeInsets.all(10), backgroundColor: Colors.white, ), const SizedBox(height: 32), Text( '${model.game.timeLimit} min', style: TextStyle( fontSize: 32, color: Colors.red, fontWeight: FontWeight.bold), ), const SizedBox(height: 10), Text( 'Hunt time', style: TextStyle( fontWeight: FontWeight.bold, fontSize: 24, ), ), ], )), Container( color: Colors.white, width: MediaQuery.of(context).size.width / 1.575, padding: EdgeInsets.fromLTRB(15, 25, 15, 5), height: 255, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( model.game.name, overflow: TextOverflow.ellipsis, maxLines: 2, textAlign: TextAlign.center, style: TextStyle( fontSize: 38, height: 0.8, fontWeight: FontWeight.bold, ), ), const SizedBox(height: 25), Text('Code:', style: TextStyle(fontSize: 24, color: Colors.grey),), const SizedBox(height: 10), Text( model.game.id, style: TextStyle( fontWeight: FontWeight.bold, fontSize: 20, ), ), const SizedBox(height: 40), RoomBody(), ], )), ], ) ], ), ); }); } } class RoomBody extends StatelessWidget { const RoomBody({Key key}) : super(key: key); @override Widget build(BuildContext context) { return Consumer<GameModel>( builder: (context, model, child) { if (!model.isHost) { return PlayerAwaitButton( canStartGame: model.canStartGame, ); } return HostStartButton( canStartGame: model.canStartGame, onGameStart: model.onGameStart, ); }, ); } } class PlayerRow extends StatelessWidget { const PlayerRow({Key key}) : super(key: key); @override Widget build(BuildContext context) { return Consumer<GameModel>( builder: (context, model, child) { return Container( color: Colors.grey[600], height: 45, padding: const EdgeInsets.symmetric(vertical: 4.0, horizontal: 24.0), child: Row( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Text( 'PLAYERS', style: TextStyle( color: Colors.white, fontWeight: FontWeight.bold, fontSize: 20, ), ), Text( '${model.players.length}/${model.game.maxPlayers}', style: TextStyle( color: Colors.white, fontWeight: FontWeight.bold, fontSize: 20, ), ), ], ), ); }, ); } } class PlayerList extends StatelessWidget { const PlayerList({Key key}) : super(key: key); @override Widget build(BuildContext context) { return Consumer<GameModel>( builder: (context, model, child) { return Container( child: ListView.builder( itemCount: model.players.length, itemBuilder: (context, index) { final player = model.players[index]; final isMe = player.user.uid == model.userId; return Container( padding: EdgeInsets.symmetric(vertical: 8, horizontal: 4), child: ListTile( title: Text( player.user.displayName, style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, ), ), leading: UserAvatar( photoUrl: player.user.photoUrl, height: 45, borderColor: user_colors[index % 4], ), trailing: model.isHost ? !isMe ? FancyButton( child: Text( 'REMOVE', style: fancy_button_style, ), color: Colors.red, size: 40, onPressed: () => model.onKickPlayer(player.user.uid), ) : Container( height: 0, width: 0, ) : Container( height: 0, width: 0, ), ), ); }, ), ); }, ); } } <|start_filename|>lib/ui/how_to_play.dart<|end_filename|> import 'package:flutter/material.dart'; import 'package:intro_views_flutter/Models/page_view_model.dart'; import 'package:intro_views_flutter/intro_views_flutter.dart'; class HowToPlay extends StatelessWidget { final pages = [ PageViewModel( pageColor: Colors.amber, body: Text('Modes:\nSINGLEPLAYER or MULTIPLAYER', style: TextStyle(fontSize: 24, height: 1)), title: Text( 'Select Game Mode', style: TextStyle( fontWeight: FontWeight.bold, ), ), textStyle: TextStyle(color: Colors.white), mainImage: Image.asset( 'assets/intro_one.png', height: 400, width: 400, alignment: Alignment.center, ), ), PageViewModel( pageColor: Colors.lightBlue, body: Text('Set TIME LIMIT and NO. OF ITEMS\n\nMultiplayer:\n(ROOM NAME and MAX PLAYERS)', style: TextStyle(fontSize: 24, height: 1)), title: Text( 'Set Game Settings', style: TextStyle( fontWeight: FontWeight.bold, ), ), textStyle: TextStyle(color: Colors.white), mainImage: Image.asset( 'assets/intro_two.png', height: 350, width: 350, alignment: Alignment.center, ), ), PageViewModel( pageColor: Colors.deepPurple, body: Text('Start the game and look for the items displayed on the screen.', style: TextStyle(fontSize: 24, height: 1)), title: Text( 'Begin Hunt', style: TextStyle( fontWeight: FontWeight.bold, ), ), textStyle: TextStyle(color: Colors.white), mainImage: Image.asset( 'assets/intro_three.png', height: 400, width: 400, alignment: Alignment.center, ), ), PageViewModel( pageColor: Colors.green, body: Text('Take a snap of the object to be verified.\nEvery point is gained once item is valid.', style: TextStyle(fontSize: 26, height: 1)), title: Text( 'Take a Snap', style: TextStyle( fontWeight: FontWeight.bold, ), ), textStyle: TextStyle(color: Colors.white), mainImage: Image.asset( 'assets/intro_four.png', height: 400, width: 400, alignment: Alignment.center, ), ), PageViewModel( pageColor: Colors.blueAccent, body: Text('First one to snap all items or with the highest score before the time limit ends wins the game.', style: TextStyle(fontSize: 26, height: 1)), title: Text( 'Be The Champion', style: TextStyle( fontWeight: FontWeight.bold, ), ), textStyle: TextStyle(color: Colors.white), mainImage: Image.asset( 'assets/intro_five.png', height: 400, width: 400, alignment: Alignment.center, ), ), PageViewModel( pageColor: Colors.red, body: Text('You are now ready to begin your Scavenger Game Hunt!', style: TextStyle(fontSize: 26, height: 1)), title: Text( 'Let the Hunt Begin', style: TextStyle( fontWeight: FontWeight.bold, ), ), textStyle: TextStyle(color: Colors.white), mainImage: Image.asset( 'assets/intro_six.png', height: 320, width: 320, alignment: Alignment.center, ), ) ]; @override Widget build(BuildContext context) { return WillPopScope( onWillPop: () async => false, child: IntroViewsFlutter( pages, onTapDoneButton: () { Navigator.pop(context); }, columnMainAxisAlignment: MainAxisAlignment.center, fullTransition: 175, showSkipButton: false, showNextButton: false, pageButtonTextStyles: TextStyle( color: Colors.white, fontSize: 16.0, ), ), ); } } <|start_filename|>lib/model/player.dart<|end_filename|> import 'package:snaphunt/model/user.dart'; class Player { User user; int score; String status; Player({this.user, this.score = 0, this.status = 'active'}); Player.fromJson(Map<String, dynamic> json, Map<String, dynamic> userJson) { user = User.fromJson(userJson); score = json['score']; status = json['status']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['user'] = this.user.toJson(); data['score'] = this.score; data['status'] = this.status; return data; } } <|start_filename|>lib/widgets/common/hunt_game.dart<|end_filename|> import 'package:auto_size_text/auto_size_text.dart'; import 'package:expandable/expandable.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:snaphunt/constants/app_theme.dart'; import 'package:snaphunt/model/hunt.dart'; import 'package:snaphunt/model/player.dart'; import 'package:snaphunt/routes.dart'; import 'package:snaphunt/stores/hunt_model.dart'; import 'package:snaphunt/stores/player_hunt_model.dart'; import 'package:snaphunt/ui/home.dart'; import 'package:snaphunt/utils/utils.dart'; import 'package:snaphunt/widgets/common/camera.dart'; import 'package:snaphunt/widgets/common/countdown.dart'; import 'package:snaphunt/widgets/multiplayer/room_exit_dialog.dart'; class HuntGame extends StatelessWidget { final String title; final List<Player> players; const HuntGame({Key key, this.title, this.players}) : super(key: key); void statusListener(HuntModel model, BuildContext context) { if (model.isMultiplayer) { if (model.isTimeUp) { pushMultiPlayerResult( model, context, title: 'Times up!', body: 'Times up! Hunting stops now!', gameTitle: title, duration: model.timeDuration, ); } else if (model.isGameEnd && model.isHuntComplete) { pushMultiPlayerResult( model, context, title: 'Congrats!', body: 'All items found! You are a champion!', gameTitle: title, duration: model.timeDuration, ); } else if (model.isGameEnd && !model.isHuntComplete) { pushMultiPlayerResult( model, context, title: 'Hunt Ended!', body: 'Someone completed the hunt!', gameTitle: title, duration: model.timeDuration, ); } } else { if (model.isTimeUp) { pushSinglePlayerResult( model, context, title: 'Times up!', body: 'Times up! Hunting stops now!', ); } else if (model.isHuntComplete) { pushSinglePlayerResult( model, context, title: 'Congrats!', body: 'All items found! You are a champion!', ); } } } void pushSinglePlayerResult( HuntModel model, BuildContext context, { String title, String body, }) { Navigator.of(context).pushReplacementNamed( Router.resultSingle, arguments: [ model.isHuntComplete, model.objects, model.duration.elapsed, ], ); showAlertDialog( context: context, title: title, body: body, ); } void pushMultiPlayerResult( HuntModel model, BuildContext context, { String title, String body, String gameTitle, int duration, }) { Navigator.of(context).pushReplacementNamed( Router.resultMulti, arguments: [model.gameId, gameTitle, duration], ); showAlertDialog( context: context, title: title, body: body, ); } @override Widget build(BuildContext context) { return WillPopScope( onWillPop: () async { final roomCode = await showDialog<bool>( context: context, barrierDismissible: false, builder: (BuildContext context) { return RoomExitDialog( title: 'Leave game?', body: 'Are you sure you want to leave the game? Your progress will be lost', ); }, ); return roomCode; }, child: Scaffold( body: Consumer<HuntModel>( builder: (context, model, child) { WidgetsBinding.instance.addPostFrameCallback( (_) => statusListener(model, context), ); return Stack( children: <Widget>[ child, HeaderRow( title: title, timeLimit: model.timeLimit, ), Container( margin: const EdgeInsets.only(top: 90), child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ if (model.isMultiplayer) PlayerUpdate( gameId: model.gameId, players: players, ), ExpandedWordList( objectsFound: model.objectsFound, totalObjects: model.objects.length, hunt: model.nextNotFound, ), ], ), ), ], ); }, child: CameraScreen(), ), ), ); } } class HeaderRow extends StatelessWidget { final String title; final DateTime timeLimit; const HeaderRow({Key key, this.title, this.timeLimit}) : super(key: key); @override Widget build(BuildContext context) { return Container( height: 75, padding: EdgeInsets.only( top: MediaQuery.of(context).padding.top + 8.0, left: 24.0, right: 24.0, ), child: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Text( title, style: TextStyle( color: Colors.white, fontSize: 24, ), ), CountDownTimer(timeLimit: timeLimit) ], ), ); } } class ExpandedWordList extends StatelessWidget { final int objectsFound; final int totalObjects; final Hunt hunt; const ExpandedWordList({ Key key, this.objectsFound, this.totalObjects, this.hunt, }) : super(key: key); @override Widget build(BuildContext context) { return Container( child: ExpandablePanel( collapsed: Container( padding: const EdgeInsets.symmetric(horizontal: 16.0), child: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Text( 'Items ($objectsFound/$totalObjects)', style: TextStyle( fontSize: 20, color: Colors.white, ), ), if (hunt != null) WordTile(word: hunt) ], ), ), expanded: WordList(), headerAlignment: ExpandablePanelHeaderAlignment.center, tapBodyToCollapse: true, tapHeaderToExpand: true, hasIcon: true, iconColor: Colors.white, ), ); } } class WordList extends StatelessWidget { @override Widget build(BuildContext context) { final size = MediaQuery.of(context).size; return Consumer<HuntModel>( builder: (context, model, child) { return Container( width: double.infinity, color: Colors.transparent, constraints: BoxConstraints(maxHeight: size.height * 0.4), padding: const EdgeInsets.only(left: 16.0), child: ListView( shrinkWrap: true, children: [ Wrap( alignment: WrapAlignment.center, spacing: 24, runSpacing: 14, direction: Axis.horizontal, children: <Widget>[ for (Hunt word in model.objects) WordTile( word: word, ), ], ) ], ), ); }, ); } } class WordTile extends StatelessWidget { final Hunt word; const WordTile({Key key, this.word}) : super(key: key); @override Widget build(BuildContext context) { return Container( child: Row( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Icon( word.isFound ? Icons.check : Icons.fiber_manual_record, color: word.isFound ? Colors.green : Colors.red, ), SizedBox(width: 10), AutoSizeText( word.word, maxLines: 1, minFontSize: 10, style: TextStyle( fontSize: 20, color: Colors.white, decoration: word.isFound ? TextDecoration.lineThrough : null, ), ), ], ), ); } } class PlayerUpdate extends StatelessWidget { final String gameId; final List<Player> players; const PlayerUpdate({Key key, this.gameId, this.players}) : super(key: key); @override Widget build(BuildContext context) { return ChangeNotifierProvider( builder: (_) => PlayHuntModel( gameId: gameId, players: players, ), child: Consumer<PlayHuntModel>( builder: (context, model, child) { return Container( margin: const EdgeInsets.all(8), height: 60, child: ListView.builder( scrollDirection: Axis.horizontal, itemCount: model.players.length, itemBuilder: (context, index) { final player = model.players[index]; return ScoreAvatar( photoUrl: player.user.photoUrl, score: player.score, userBorderColor: user_colors[index % 4], ); }, ), ); }, ), ); } } class ScoreAvatar extends StatelessWidget { final String photoUrl; final int score; final Color userBorderColor; const ScoreAvatar({Key key, this.photoUrl, this.score, this.userBorderColor}) : super(key: key); @override Widget build(BuildContext context) { return Container( margin: const EdgeInsets.symmetric(horizontal: 8.0), child: Row( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ UserAvatar( borderColor: userBorderColor, photoUrl: photoUrl, height: 50, ), SizedBox(width: 10), Text( '$score', style: TextStyle( color: Colors.white, fontSize: 24, fontWeight: FontWeight.bold, ), ), ], ), ); } } class AvatarScore extends StatelessWidget { final int score; const AvatarScore({Key key, this.score}) : super(key: key); @override Widget build(BuildContext context) { return Container( height: 20, width: 20, decoration: BoxDecoration( color: Colors.white, shape: BoxShape.circle, ), alignment: Alignment.center, padding: const EdgeInsets.all(2), child: Text('$score'), ); } } <|start_filename|>lib/ui/singleplayer/single_settings.dart<|end_filename|> import 'package:flutter/material.dart'; import 'package:hive/hive.dart'; import 'package:snaphunt/routes.dart'; import 'package:snaphunt/widgets/common/card_textfield.dart'; import 'package:snaphunt/widgets/multiplayer/create_buttons.dart'; class SinglePlayerSettings extends StatefulWidget { @override _SinglePlayerSettingsState createState() => _SinglePlayerSettingsState(); } class _SinglePlayerSettingsState extends State<SinglePlayerSettings> { final itemsController = TextEditingController(); int dropdownValue = 3; @override void initState() { itemsController.text = '8'; super.initState(); } @override void dispose() { itemsController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { final objectCount = Hive.box('words').get('words').length; return Scaffold( resizeToAvoidBottomPadding: false, appBar: AppBar( title: Text( 'Single player', style: TextStyle(color: Colors.white), ), leading: Container(), centerTitle: true, elevation: 0, ), body: ListView( physics: NeverScrollableScrollPhysics(), children: <Widget>[ const SizedBox(height: 10), CardTextField( label: 'Time Limit', widget: DropdownButton<int>( isExpanded: true, value: dropdownValue, iconSize: 24, elevation: 16, underline: Container(), onChanged: (newVal) { setState(() { dropdownValue = newVal; }); }, items: <int>[3, 5, 8, 12, 15] .map<DropdownMenuItem<int>>((int value) { return DropdownMenuItem<int>( value: value, child: Text( '$value mins', style: TextStyle( fontSize: 16, ), ), ); }).toList(), ), ), CardTextField( label: 'No. of Items', widget: TextField( controller: itemsController, keyboardType: TextInputType.number, maxLines: 1, decoration: InputDecoration( border: InputBorder.none, ), ), ), const SizedBox(height: 20), CreateButtons( createLabel: 'Play!', onCreate: () { int numObjects = int.parse(itemsController.text); if (numObjects == 0) { numObjects = 1; } else if (numObjects > objectCount) { numObjects = objectCount; } Navigator.of(context).pushReplacementNamed( Router.singlePlayer, arguments: [ numObjects, dropdownValue, ], ); }, ) ], ), ); } } <|start_filename|>lib/ui/multiplayer/multiplayer_result.dart<|end_filename|> import 'dart:io'; import 'package:esys_flutter_share/esys_flutter_share.dart'; import 'package:flutter/material.dart'; import 'package:screenshot/screenshot.dart'; import 'package:snaphunt/constants/app_theme.dart'; import 'package:snaphunt/data/repository.dart'; import 'package:snaphunt/model/player.dart'; import 'package:snaphunt/ui/home.dart'; import 'package:snaphunt/widgets/common/fancy_button.dart'; import 'package:snaphunt/widgets/multiplayer/room_loading.dart'; class ResultMultiPlayer extends StatefulWidget { final String gameId; final String title; final int duration; const ResultMultiPlayer({ Key key, this.gameId, this.title, this.duration, }) : super(key: key); @override _ResultMultiPlayerState createState() => _ResultMultiPlayerState(); } class _ResultMultiPlayerState extends State<ResultMultiPlayer> { List<Player> _players; ScreenshotController screenshotController = ScreenshotController(); @override void initState() { super.initState(); initPlayers(); } void initPlayers() async { final players = await Repository.instance.getPlayers(widget.gameId); players.sort((a, b) => b.score.compareTo(a.score)); setState(() { _players = players; }); } @override Widget build(BuildContext context) { return Scaffold( body: Container( color: Colors.white, child: Container( child: _players == null ? RoomLoading() : Column( children: <Widget>[ Screenshot( controller: screenshotController, child: Container( color: Colors.white, width: double.infinity, child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.center, mainAxisSize: MainAxisSize.max, children: <Widget>[ ResultHeader( title: widget.title, duration: widget.duration, ), ResultWinner(winner: _players.first), Divider( color: Colors.grey, thickness: 2, indent: 0, endIndent: 0, ), ResultPlayers( players: _players.sublist(1, _players.length), ), ], ), ), ), const SizedBox(height: 40), FancyButton( color: Colors.orange, size: 50, child: Container( width: 150, child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Padding( padding: const EdgeInsets.all(0), child: Icon(Icons.share, color: Colors.white), ), Text( 'Share', style: fancy_button_style, ) ], ), ), onPressed: () async { screenshotController.capture().then((File image) async { await Share.file( 'SnapHunt', 'snaphunt.png', image.readAsBytesSync().buffer.asUint8List(), 'image/png'); }).catchError((onError) { print(onError); }); }, ), const SizedBox(height: 20), FancyButton( color: Colors.deepOrange, size: 50, child: Container( width: 150, child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Padding( padding: const EdgeInsets.all(0), child: Icon(Icons.arrow_back, color: Colors.white), ), Text( 'Return to Lobby', style: fancy_button_style, ) ], ), ), onPressed: () { Navigator.of(context).pop(); }, ), ], ), ), ), ); } } class ResultHeader extends StatelessWidget { final String title; final int duration; const ResultHeader({Key key, this.title, this.duration}) : super(key: key); @override Widget build(BuildContext context) { return Container( padding: EdgeInsets.fromLTRB( 16.0, MediaQuery.of(context).padding.top + 8, 16.0, 16.0), height: MediaQuery.of(context).size.height * 0.23, color: Colors.orange, child: Row( children: <Widget>[ Expanded( child: ResultHeaderLogo(), ), Expanded( flex: 2, child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.end, children: <Widget>[ Text( title, style: TextStyle( color: Colors.white, fontSize: 32, fontWeight: FontWeight.bold, ), ), const SizedBox(height: 20), Text( '$duration min', style: TextStyle( color: Colors.red, fontSize: 18, fontWeight: FontWeight.w700, ), ), const SizedBox(height: 4), Text( 'Hunt Time', style: TextStyle( color: Colors.white, fontSize: 16, fontWeight: FontWeight.w500, ), ) ], ), ) ], ), ); } } class ResultHeaderLogo extends StatelessWidget { @override Widget build(BuildContext context) { return Material( elevation: 4.0, shape: const CircleBorder( side: BorderSide(color: Colors.transparent), ), child: Container( decoration: BoxDecoration( shape: BoxShape.circle, color: Colors.deepPurple[300], ), height: 120, width: 120, alignment: Alignment.center, child: Image.asset( 'assets/trophy.png', height: 80, ), ), ); } } class ResultWinner extends StatelessWidget { final Player winner; const ResultWinner({Key key, this.winner}) : super(key: key); @override Widget build(BuildContext context) { return Container( height: MediaQuery.of(context).size.height * 0.2, child: Row( mainAxisSize: MainAxisSize.min, children: <Widget>[ Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ UserAvatar( photoUrl: winner.user.photoUrl, height: 100, ), ], ), SizedBox(width: 20), Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text( 'WINNER', style: TextStyle( color: Colors.red, fontSize: 32, fontWeight: FontWeight.bold, ), ), SizedBox(height: 20), Text( '${winner.user.displayName}', style: TextStyle( fontSize: 24, fontWeight: FontWeight.w500, ), ), const SizedBox(height: 10.0), Text( '${winner.score} points', style: TextStyle( color: Colors.orange, fontSize: 18, fontWeight: FontWeight.w300, ), ) ], ) ], ), ); } } class ResultPlayers extends StatelessWidget { final List<Player> players; const ResultPlayers({Key key, this.players}) : super(key: key); @override Widget build(BuildContext context) { return Container( padding: const EdgeInsets.symmetric(horizontal: 8.0), height: MediaQuery.of(context).size.height * 0.25, child: ListView.builder( itemCount: players.length, itemBuilder: (context, index) { final player = players[index]; return ListTile( leading: UserAvatar( borderColor: user_colors[(index + 1) % 4], photoUrl: player.user.photoUrl, height: 50, ), title: Text( player.user.displayName, style: TextStyle( color: Colors.black, fontSize: 18, fontWeight: FontWeight.w400, ), ), trailing: Text( '${player.score} points', style: TextStyle( color: Colors.orange, fontSize: 16, fontWeight: FontWeight.w300, ), ), ); }, ), ); } } <|start_filename|>lib/model/game.dart<|end_filename|> import 'package:cloud_firestore/cloud_firestore.dart'; class Game { String id; String name; String createdBy; int maxPlayers; int timeLimit; int noOfItems; String status; DateTime timeCreated; DateTime gameStartTime; List<String> words; Game( {this.id, this.name, this.createdBy, this.maxPlayers, this.timeLimit, this.noOfItems, this.status, this.timeCreated, this.gameStartTime, this.words}); Game.fromJson(Map<String, dynamic> json) { id = json['id']; name = json['name']; createdBy = json['createdBy']; maxPlayers = json['maxPlayers']; timeLimit = json['timeLimit']; noOfItems = json['noOfItems']; status = json['status']; timeCreated = DateTime.fromMillisecondsSinceEpoch( (json['timeCreated'] as Timestamp).millisecondsSinceEpoch); gameStartTime = json['gameStartTime'] != null ? DateTime.fromMillisecondsSinceEpoch( (json['gameStartTime'] as Timestamp).millisecondsSinceEpoch) : null; words = json['words']?.cast<String>(); } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['id'] = this.id; data['name'] = this.name; data['createdBy'] = this.createdBy; data['maxPlayers'] = this.maxPlayers; data['timeLimit'] = this.timeLimit; data['noOfItems'] = this.noOfItems; data['status'] = this.status; data['timeCreated'] = this.timeCreated; data['gameStartTime'] = this.gameStartTime; data['words'] = this.words; return data; } } <|start_filename|>lib/widgets/common/card_textfield.dart<|end_filename|> import 'package:flutter/material.dart'; class CardTextField extends StatelessWidget { final String label; final Widget widget; const CardTextField({ Key key, this.label, this.widget, }) : super(key: key); @override Widget build(BuildContext context) { return Container( margin: const EdgeInsets.symmetric( horizontal: 8.0, vertical: 2.0, ), height: 60, child: Card( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(8.0), ), elevation: 3, child: Container( margin: EdgeInsets.all(8.0), child: Row( mainAxisSize: MainAxisSize.max, crossAxisAlignment: CrossAxisAlignment.baseline, textBaseline: TextBaseline.alphabetic, children: <Widget>[ Expanded( flex: 2, child: Center( child: Text( label, style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold ), ), ), ), const VerticalDivider( width: 10, thickness: 1, ), Expanded( flex: 5, child: Container( child: widget, padding: const EdgeInsets.symmetric(horizontal: 8.0), ), ) ], ), ), ), ); } } <|start_filename|>lib/ui/multiplayer/lobby.dart<|end_filename|> import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:flutter_staggered_animations/flutter_staggered_animations.dart'; import 'package:provider/provider.dart'; import 'package:snaphunt/data/repository.dart'; import 'package:snaphunt/model/game.dart'; import 'package:snaphunt/routes.dart'; import 'package:snaphunt/utils/utils.dart'; import 'package:snaphunt/widgets/multiplayer/join_room_dialog.dart'; import 'package:snaphunt/widgets/multiplayer/lobby_buttons.dart'; class Lobby extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text( 'SNAPHUNT LOBBY', style: TextStyle(color: Colors.white), ), automaticallyImplyLeading: false, centerTitle: true, elevation: 0, ), body: SafeArea( child: Container( padding: const EdgeInsets.symmetric(vertical: 8.0), child: Column( children: <Widget>[ Expanded( child: LobbyList(), ), Divider( thickness: 1.5, ), LobbyButtons( onCreateRoom: () { Navigator.of(context).pushNamed(Router.create); }, onJoinRoom: () async { String roomCode = await showDialog<String>( context: context, barrierDismissible: false, builder: (BuildContext context) => JoinRoom(), ); if (roomCode != null && roomCode.isNotEmpty) { final game = await Repository.instance.retrieveGame(roomCode); if (game == null) { showAlertDialog( context: context, title: 'Invalid Code', body: 'Invalid code. Game does not exist!', ); } else { if (game.status != 'waiting') { showAlertDialog( context: context, title: 'Game not available!', body: 'Game has already started or ended!', ); } else { final user = Provider.of<FirebaseUser>(context, listen: false); Navigator.of(context).pushNamed(Router.room, arguments: [game, false, user.uid]); } } } }, ), ], ), ), ), ); } } class LobbyList extends StatelessWidget { @override Widget build(BuildContext context) { return Container( child: StreamBuilder<QuerySnapshot>( stream: Firestore.instance .collection('games') .where('status', isEqualTo: 'waiting') .snapshots(), builder: (context, snapshot) { if (!snapshot.hasData) return Center( child: CircularProgressIndicator(), ); if (snapshot.data.documents.isEmpty) { return Container( child: Center( child: Text( 'No rooms available', style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, color: Colors.grey, ), ), ), ); } return AnimationLimiter( child: ListView.builder( itemCount: snapshot.data.documents.length, itemBuilder: (context, index) { final game = Game.fromJson(snapshot.data.documents[index].data); game.id = snapshot.data.documents[index].documentID; return AnimationConfiguration.staggeredList( position: index, duration: const Duration(milliseconds: 650), child: SlideAnimation( verticalOffset: 50.0, child: FadeInAnimation( child: LobbyListTile( game: game, onRoomClick: () async { final user = Provider.of<FirebaseUser>(context, listen: false); Navigator.of(context).pushNamed(Router.room, arguments: [game, false, user.uid]); }, ), ), ), ); }, ), ); }, ), ); } } class LobbyListTile extends StatefulWidget { final Game game; final Function onRoomClick; const LobbyListTile({ Key key, this.onRoomClick, this.game, }) : super(key: key); @override _LobbyListTileState createState() => _LobbyListTileState(); } class _LobbyListTileState extends State<LobbyListTile> { String _createdBy = ''; bool _isRoomFull = false; @override void initState() { getName(); super.initState(); } void getName() async { final name = await Repository.instance.getUserName(widget.game.createdBy); if (mounted) { setState(() { _createdBy = name; }); } } @override Widget build(BuildContext context) { return Container( margin: const EdgeInsets.symmetric(horizontal: 8, vertical: 2), child: Card( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(8.0), ), elevation: 4, child: Container( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2), child: ListTile( title: Text( widget.game.name, style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold, ), ), subtitle: Text(_createdBy), trailing: Column( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('${widget.game.timeLimit} mins'), const SizedBox(height: 8.0), StreamBuilder<QuerySnapshot>( stream: Firestore.instance .collection('games') .document(widget.game.id) .collection('players') .snapshots(), builder: (context, snapshot) { if (snapshot.data == null) { return Text('0/${widget.game.maxPlayers}'); } final players = snapshot.data.documents.length; final isRoomFull = players == widget.game.maxPlayers; return Text( '$players/${widget.game.maxPlayers}', style: TextStyle(color: isRoomFull ? Colors.red : null), ); }, ), ], ), onTap: _isRoomFull ? null : widget.onRoomClick, ), ), ), ); } }
snap-hunt/snaphunt
<|start_filename|>test/templates/errors.json<|end_filename|> { "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#", "contentVersion": "1.0.0.0", "parameters": { "domainNamePrefix": { "type": "string", "metadata": { "description": "The public DNS name label for the service. The pattern will follow: <domainNamePrefix>.<region>.cloudapp.azure.com" } }, "vmssName": { "type": "string", "metadata": { "description": "String used as a base for naming resources (9 characters or less). A hash is prepended to this string for some resources, and resource-specific information is appended." }, "maxLength": 9 }, "automationAccountName": { "type": "string", "defaultValue": "myAutomationAccount", "metadata": { "description": "The name of the Automation account to use. Check the SKU and tags to make sure they match the existing account." } }, "automationRegionId": { "type": "string", "defaultValue": "East US 2", "allowedValues": [ "Japan East", "East US 2", "West Europe", "Southeast Asia", "South Central US", "Central India" ], "metadata": { "description": "The region the Automation account is located in." } }, "configurationName": { "type": "string", "defaultValue": "MyService", "metadata": { "description": "The name of the DSC Configuration. The name must match the name in the URI." } }, "jobid": { "type": "string", "metadata": { "description": "The job id to compile the configuration" } } }, "variables": { "saCount": 5, "namingInfix": "[toLower(parameters('vmssName'))]", "newStorageAccountSuffix": "[concat(variables('namingInfix'), 'sa')]", "uniqueStringArray": [ "[concat(uniqueString(concat(resourceGroup().id, deployment().name, variables('newStorageAccountSuffix'), '0')))]", "[concat(uniqueString(concat(resourceGroup().id, deployment().name, variables('newStorageAccountSuffix'), '1')))]", "[concat(uniqueString(concat(resourceGroup().id, deployment().name, variables('newStorageAccountSuffix'), '2')))]", "[concat(uniqueString(concat(resourceGroup().id, deployment().name, variables('newStorageAccountSuffix'), '3')))]", "[concat(uniqueString(concat(resourceGroup().id, deployment().name, variables('newStorageAccountSuffix'), '4')))]" ], "publicIPAddressName": "[concat(variables('namingInfix'), 'pip')]", "publicIPAddressID": "[resourceId('Microsoft.Network/publicIPAddresses/',variables('publicIPAddressName'))]", "osType": { "publisher": "MicrosoftWindowsServer", "offer": "WindowsServer", "sku": "[parameters('windowsOSVersion')]", "version": "latest" }, "automationPricingTier": "Free" }, "resources": [ { "type": "Microsoft.Automation/automationAccounts", "name": "[parameters('automationAccountName')]", "apiVersion": "2015-10-31", "location": "[parameters('automationRegionId')]", "dependsOn": [], "tags": {}, "properties": { "sku": { "name": "[variables('automationPricingTier')]" } }, "resources": [ { "name": "[parameters('jobid')]", "type": "compilationjobs", "apiVersion": "2015-10-31", "location": "parameters('automationRegionId')]", "tags": {}, "dependsOn": [ "[concat('Microsoft.Automation/automationAccounts/', parameters('automationAccountName'))]", "[concat('Microsoft.Automation/automationAccounts/', parameters('automationAccountName'),'/Configurations/', parameters('configurationName'))]" ], "properties": { "configuration": { "name": "[parameters('configurationName')]" } } } ] }, { "type": "Microsoft.Storage/storageAccounts", "name": "[concat(variables('uniqueStringArray')[copyindex(1,2)], variables('newStorageAccountSuffix'))]", "location": "[resourceGroup().location]", "apiVersion": "2015-06-15", "copy": { "name": "storageLoop", "count": "[variables('sacount')]" }, "properties": { "accountType": "[variables('storageAccountType')]" } } ], "outputs": { "fqdn": { "value": "[reference(variables('publicIPAddressID'),'2017-04-01', 'Full').dnsSettings.fqdn]", "type": "string" }, "ipaddress": { "value": "[reference(variables('publicIPAddressID'),'2017-04-01').ipAddress]", "type": "string" } } } <|start_filename|>clean.cmd<|end_filename|> rmdir /S /Q out <|start_filename|>test/colorization/real-examples/examples1.json<|end_filename|> { "$schema": "https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#", "variables": { "exmaple1": "[concat('sudo sh config-bootstrap-node.sh ',parameters('AdminUser'),' ''',parameters('AdminPassword'),''' anyauth 5 10 public ',parameters('LicenseKey'),' ',parameters('Licensee'))]", "example2": "[concat('sudo sh config-additional-node.sh ',parameters('AdminUser'),' ''',parameters('AdminPassword'),''' anyauth 5 10 ',string(variables('enableHA')),' ',parameters('LicenseKey'),' ',parameters('Licensee'))]", "example3": "[concat('cd /hub*/docker-compose; sudo docker-compose down -t 60; sudo -s source /set_hub_url.sh ', reference(parameters('publicIpName')).dnsSettings.fqdn, '; sudo docker volume rm ''dockercompose_cert-volume''; sudo docker-compose up')]" } } <|start_filename|>test/colorization/inputs/simple-template-subscription-deployment.json<|end_filename|> { "$schema": "https://schema.management.azure.com/schemas/2015-01-01/subscriptionDeploymentTemplate.json#", "parameters": { "guid": { "type": "string", "defaultValue": "[subscription()]" } } } <|start_filename|>test/templates/arm-template-language-samples/any-property-at-any-level-can-be-an-expression.json<|end_filename|> { "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#", "contentVersion": "1.0.0.0", "parameters": { "budgetName": { "type": "string", "metadata": { "description": "Budget name" } }, "amount": { "type": "string", "metadata": { "description": "The total amount of cost or usage to track with the budget" } }, "budgetCategory": { "type": "string", "defaultValue": "Cost", "allowedValues": [ "Cost", "Usage" ], "metadata": { "description": "The category of the budget, whether the budget tracks cost or usage." } }, "timeGrain": { "type": "string", "defaultValue": "Monthly", "allowedValues": [ "Monthly", "Quarterly", "Annually" ], "metadata": { "description": "The time covered by a budget. Tracking of the amount will be reset based on the time grain." } }, "startDate": { "type": "string", "defaultValue": "YYYY-MM-DD", "metadata": { "description": "The start date for the budget." } }, "endDate": { "type": "string", "defaultValue": "YYYY-MM-DD", "metadata": { "description": "The end date for the budget. If not provided, we default this to 10 years from the start date." } }, "operator": { "type": "string", "defaultValue": "GreaterThan", "allowedValues": [ "EqualTo", "GreaterThan", "GreaterThanOrEqualTo" ], "metadata": { "description": "The comparison operator." } }, "threshold": { "type": "string", "metadata": { "description": "Threshold value associated with a notification. Notification is sent when the cost exceeded the threshold. It is always percent and has to be between 0 and 1000." } }, "contactEmails": { "type": "array", "defaultValue": [ "abc<EMAIL>", "<EMAIL>" ], "metadata": { "description": "Email addresses to send the budget notification to when the threshold is exceeded." } }, "contactRoles": { "type": "array", "defaultValue": [ "Owner", "Contributor", "Reader" ], "metadata": { "description": "Contact roles to send the budget notification to when the threshold is exceeded." } }, "contactGroups": { "type": "array", "defaultValue": [ "/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/microsoft.insights/actionGroups/SampleActionGroup1" ], "metadata": { "description": "Contact roles to send the budget notification to when the threshold is exceeded." } }, "resourcesFilter": { "type": "array", "defaultValue": [ "/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/Microsoft.Compute/virtualMachines/vm1", "/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/Microsoft.Compute/virtualMachines/vm2" ], "metadata": { "description": "The list of filters on resources." } }, "metersFilter": { "type": "array", "defaultValue": [ "meterGuid1", "meterGuid2" ], "metadata": { "description": "The list of filters on meters, mandatory for budgets of usage category." } } }, "variables": {}, "resources": [ { "type": "Microsoft.Consumption/budgets", "name": "[parameters('budgetName')]", "apiVersion": "2018-01-31", "properties": { "category": "[parameters('budgetCategory')]", "amount": "[parameters('amount')]", "timeGrain": "[parameters('timeGrain')]", "timePeriod": { "startDate": "[parameters('startDate')]", "endDate": "[parameters('endDate')]" }, "notifications": { "First-Notification": { "enabled": true, "operator": "[parameters('operator')]", "threshold": "[parameters('threshold')]", "contactEmails": "[parameters('contactEmails')]", "contactRoles": "[parameters('contactRoles')]", "contactGroups": "[parameters('contactGroups')]" } }, "filters": { "resources": "[parameters('resourcesFilter')]", "meters": "[parameters('metersFilter')]" } } } ], "outputs": { "budgetName": { "type": "string", "value": "[parameters('budgetName')]" } } } <|start_filename|>test/colorization/real-examples/all-colors.json<|end_filename|> { "$schema": "http://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#", "contentVersion": "1.0.0.0", "parameters": { "networkSecurityGroupName": { "type": "string" } }, "variables": { "regular string": "Look, Ma, no hands!", "string in expression": "['Look, Ma, no hands!']", "builtin function": "[concat('a', 'b')]", "builtin runtime function": "[reference('resourceId')]", "user namespace+function": "[contoso.myFunction()]", "unknown function": "[unknownFunction()]", "parameters": "[parameters('networkSecurityGroupName')]", "variables": "[variables('networkSecurityGroupName')]", "array access": "[array()[123]]", "property access": "[variables('object').property1]", "escapedapostrophe": "['What''s up, Doc?']", "JSON string escapes": "['He said, \"Hi\"']", "invalid": "[whatever, dude!]", // // // "use-variables-to-get-rid-of-warnings": "[concat(variables('array'), variables('JSON string escapes'),variables('builtin runtime function'), variables('regular string'),variables('builtin function'),variables('escapedapostrophe'),variables('invalid'),variables('parameters'),variables('regular string'),variables('unknown function'),variables('user namespace+function'),variables('string in expression'),variables('use-variables-to-get-rid-of-warnings'),variables('array access'),variables('property access'), variables('variables'))]", "array": [ 1, 2, 3 ], "object": { "property1": 1 } }, "resources": [], "functions": [ { "namespace": "contoso", "members": { "uniqueName": { "output": { "type": "string", "value": "[concat(uniqueString(resourceGroup().id))]" } } } } ] }
sirarthur3/vscode-azurearmtools
<|start_filename|>Assets/Kvant/Lattice/Lattice.cs<|end_filename|> // // Lattice - fractal-deformed lattice renderer // using UnityEngine; using UnityEngine.Rendering; namespace Kvant { [ExecuteInEditMode] [AddComponentMenu("Kvant/Lattice")] public partial class Lattice : MonoBehaviour { #region Basic Properties [SerializeField] int _columns = 100; public int columns { get { return _columns; } } [SerializeField] int _rows = 100; public int rows { get { return _totalRows; } } [SerializeField] Vector2 _extent = Vector2.one * 50; public Vector2 extent { get { return _extent; } set { _extent = value; } } [SerializeField] Vector2 _offset = Vector2.zero; public Vector2 offset { get { return _offset; } set { _offset = value; } } #endregion #region Noise Parameters [SerializeField, Range(0, 1)] float _noiseFrequency = 0.3f; public float noiseFrequency { get { return _noiseFrequency; } set { _noiseFrequency = value; } } [SerializeField, Range(1, 5)] int _noiseDepth = 3; public int noiseDepth { get { return _noiseDepth; } set { _noiseDepth = value; } } [SerializeField] float _noiseClampMin = -1.0f; public float noiseClampMin { get { return _noiseClampMin; } set { _noiseClampMin = value; } } [SerializeField] float _noiseClampMax = 1.0f; public float noiseClampMax { get { return _noiseClampMax; } set { _noiseClampMax = value; } } [SerializeField] float _noiseElevation = 1.0f; public float noiseElevation { get { return _noiseElevation; } set { _noiseElevation = value; } } [SerializeField, Range(0, 1)] float _noiseWarp = 0.0f; public float noiseWarp { get { return _noiseWarp; } set { _noiseWarp = value; } } #endregion #region Render Settings [SerializeField] Material _material; bool _owningMaterial; // whether owning the material public Material sharedMaterial { get { return _material; } set { _material = value; } } public Material material { get { if (!_owningMaterial) { _material = Instantiate<Material>(_material); _owningMaterial = true; } return _material; } set { if (_owningMaterial) Destroy(_material, 0.1f); _material = value; _owningMaterial = false; } } [SerializeField] ShadowCastingMode _castShadows; public ShadowCastingMode shadowCastingMode { get { return _castShadows; } set { _castShadows = value; } } [SerializeField] bool _receiveShadows = false; public bool receiveShadows { get { return _receiveShadows; } set { _receiveShadows = value; } } [SerializeField, ColorUsage(true, true, 0, 8, 0.125f, 3)] Color _lineColor = new Color(0, 0, 0, 0.4f); public Color lineColor { get { return _lineColor; } set { _lineColor = value; } } #endregion // VJ05 [SerializeField, Range(0, 1)] float _cutoff = 0; public float cutoff { get { return _cutoff; } set { _cutoff = value; } } #region Editor Properties [SerializeField] bool _debug; #endregion #region Built-in Resources [SerializeField] Shader _kernelShader; [SerializeField] Shader _lineShader; [SerializeField] Shader _debugShader; #endregion #region Private Variables And Properties int _rowsPerSegment; int _totalRows; RenderTexture _positionBuffer; RenderTexture _normalBuffer1; RenderTexture _normalBuffer2; BulkMesh _bulkMesh; Material _kernelMaterial; Material _lineMaterial; Material _debugMaterial; bool _needsReset = true; float XOffset { get { return Mathf.Repeat(_offset.x, _extent.x / (_columns + 1)); } } float YOffset { get { return Mathf.Repeat(_offset.y, _extent.y / (_totalRows + 1) * 2); } } float UOffset { get { return XOffset - _offset.x; } } float VOffset { get { return YOffset - _offset.y; } } void UpdateColumnAndRowCounts() { // Sanitize the numbers. _columns = Mathf.Clamp(_columns, 4, 4096); _rows = Mathf.Clamp(_rows, 4, 4096); // Total number of vertices. var total_vc = (_columns + 1) * (_rows + 1) * 6; // Number of segments. var segments = total_vc / 65000 + 1; _rowsPerSegment = segments > 1 ? (_rows / segments) / 2 * 2 : _rows; _totalRows = _rowsPerSegment * segments; } #endregion #region Resource Management public void NotifyConfigChange() { _needsReset = true; } Material CreateMaterial(Shader shader) { var material = new Material(shader); material.hideFlags = HideFlags.DontSave; return material; } RenderTexture CreateBuffer() { var width = (_columns + 1) * 2; var height = _totalRows + 1; var buffer = new RenderTexture(width, height, 0, RenderTextureFormat.ARGBFloat); buffer.hideFlags = HideFlags.DontSave; buffer.filterMode = FilterMode.Point; buffer.wrapMode = TextureWrapMode.Repeat; return buffer; } void UpdateKernelShader() { var m = _kernelMaterial; m.SetVector("_Extent", _extent); m.SetVector("_Offset", new Vector2(UOffset, VOffset)); m.SetFloat("_Frequency", _noiseFrequency); m.SetVector("_Amplitude", new Vector3(_noiseWarp, 1, _noiseWarp) * _noiseElevation); m.SetVector("_ClampRange", new Vector2(_noiseClampMin, _noiseClampMax) * 1.415f); if (_noiseWarp > 0.0f) m.EnableKeyword("ENABLE_WARP"); else m.DisableKeyword("ENABLE_WARP"); for (var i = 1; i <= 5; i++) if (i == _noiseDepth) m.EnableKeyword("DEPTH" + i); else m.DisableKeyword("DEPTH" + i); } void ResetResources() { UpdateColumnAndRowCounts(); if (_bulkMesh == null) _bulkMesh = new BulkMesh(_columns, _rowsPerSegment, _totalRows); else _bulkMesh.Rebuild(_columns, _rowsPerSegment, _totalRows); if (_positionBuffer) DestroyImmediate(_positionBuffer); if (_normalBuffer1) DestroyImmediate(_normalBuffer1); if (_normalBuffer2) DestroyImmediate(_normalBuffer2); _positionBuffer = CreateBuffer(); _normalBuffer1 = CreateBuffer(); _normalBuffer2 = CreateBuffer(); if (!_kernelMaterial) _kernelMaterial = CreateMaterial(_kernelShader); if (!_lineMaterial) _lineMaterial = CreateMaterial(_lineShader); if (!_debugMaterial) _debugMaterial = CreateMaterial(_debugShader); _lineMaterial.SetTexture("_PositionBuffer", _positionBuffer); _needsReset = false; } #endregion #region MonoBehaviour Functions void Reset() { _needsReset = true; } void OnDestroy() { if (_bulkMesh != null) _bulkMesh.Release(); if (_positionBuffer) DestroyImmediate(_positionBuffer); if (_normalBuffer1) DestroyImmediate(_normalBuffer1); if (_normalBuffer2) DestroyImmediate(_normalBuffer2); if (_kernelMaterial) DestroyImmediate(_kernelMaterial); if (_lineMaterial) DestroyImmediate(_lineMaterial); if (_debugMaterial) DestroyImmediate(_debugMaterial); } void LateUpdate() { if (_needsReset) ResetResources(); // Call the kernels. UpdateKernelShader(); Graphics.Blit(null, _positionBuffer, _kernelMaterial, 0); Graphics.Blit(_positionBuffer, _normalBuffer1, _kernelMaterial, 1); Graphics.Blit(_positionBuffer, _normalBuffer2, _kernelMaterial, 2); // Update the line material. _lineMaterial.SetColor("_Color", _lineColor); // Make a material property block for the following drawcalls. var props1 = new MaterialPropertyBlock(); var props2 = new MaterialPropertyBlock(); props1.SetTexture("_PositionBuffer", _positionBuffer); props2.SetTexture("_PositionBuffer", _positionBuffer); props1.SetTexture("_NormalBuffer", _normalBuffer1); props2.SetTexture("_NormalBuffer", _normalBuffer2); var mapOffs = new Vector3(UOffset, 0, VOffset); props1.SetVector("_MapOffset", mapOffs); props2.SetVector("_MapOffset", mapOffs); props1.SetFloat("_UseBuffer", 1); props2.SetFloat("_UseBuffer", 1); // VJ05 props1.SetFloat("_Cutoff", _cutoff); props2.SetFloat("_Cutoff", _cutoff); // Temporary variables. var mesh = _bulkMesh.mesh; var position = transform.position; var rotation = transform.rotation; var uv = new Vector2(0.5f / _positionBuffer.width, 0); position += transform.right * XOffset; position += transform.forward * YOffset; // Draw mesh segments. for (var i = 0; i < _totalRows; i += _rowsPerSegment) { uv.y = (0.5f + i) / _positionBuffer.height; props1.SetVector("_BufferOffset", uv); props2.SetVector("_BufferOffset", uv); if (_material) { // 1st half Graphics.DrawMesh( mesh, position, rotation, _material, 0, null, 0, props1, _castShadows, _receiveShadows); // 2nd half Graphics.DrawMesh( mesh, position, rotation, _material, 0, null, 1, props2, _castShadows, _receiveShadows); } // lines if (_lineColor.a > 0.0f) Graphics.DrawMesh( mesh, position, rotation, _lineMaterial, 0, null, 2, props1, false, false); } } void OnGUI() { if (_debug && Event.current.type.Equals(EventType.Repaint)) { if (_debugMaterial && _positionBuffer && _normalBuffer1 && _normalBuffer2) { var rect = new Rect(0, 0, (_columns + 1) * 2, _totalRows + 1); Graphics.DrawTexture(rect, _positionBuffer, _debugMaterial); rect.y += rect.height; Graphics.DrawTexture(rect, _normalBuffer1, _debugMaterial); rect.y += rect.height; Graphics.DrawTexture(rect, _normalBuffer2, _debugMaterial); } } } #endregion } } <|start_filename|>Assets/Kvant/Tunnel/TunnelScroller.cs<|end_filename|> // // Scroller script for Tunnel // using UnityEngine; namespace Kvant { [RequireComponent(typeof(Tunnel))] [AddComponentMenu("Kvant/Tunnel Scroller")] public class TunnelScroller : MonoBehaviour { [SerializeField] float _speed; public float speed { get { return _speed; } set { _speed = value; } } void Update() { GetComponent<Tunnel>().offset += _speed * Time.deltaTime; } } } <|start_filename|>Assets/ImageSequenceOut/ImageSequenceOut.cs<|end_filename|> // Image Sequence Output Utility // http://github.com/keijiro/SequenceOut using UnityEngine; public class ImageSequenceOut : MonoBehaviour { #region Properties [SerializeField, Range(1, 60)] int _frameRate = 30; public int frameRate { get { return _frameRate; } set { _frameRate = value; } } [SerializeField, Range(1, 4)] public int _superSampling = 1; public int superSampling { get { return _superSampling; } set { _superSampling = value; } } [SerializeField] public bool _recordOnStart; public bool isRecording { get; private set; } public int frameCount { get; private set; } #endregion #region Public Methods public void StartRecording() { System.IO.Directory.CreateDirectory("Capture"); Time.captureFramerate = _frameRate; frameCount = -1; isRecording = true; } public void StopRecording() { Time.captureFramerate = 0; isRecording = false; } #endregion #region MonoBehaviour Functions void Start() { if (_recordOnStart) StartRecording(); } void Update() { if (isRecording) { if (frameCount > 0) { var name = "Capture/frame" + frameCount.ToString("0000") + ".png"; Application.CaptureScreenshot(name, _superSampling); } frameCount++; } } #endregion } <|start_filename|>Assets/Kino/Contour/Shader/Contour.shader<|end_filename|> // // KinoContour - Contour line effect // // Copyright (C) 2015 <NAME> // // 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. // Shader "Hidden/Kino/Contour" { Properties { _MainTex ("-", 2D) = "" {} _Color ("-", Color) = (0, 0, 0, 1) _BgColor ("-", Color) = (1, 1, 1, 0) } CGINCLUDE #include "UnityCG.cginc" sampler2D _MainTex; float2 _MainTex_TexelSize; float _Strength; float _Threshold; float _FallOffDepth; half4 _Color; half4 _BgColor; sampler2D_float _CameraDepthTexture; float get_depth(float2 uv) { return Linear01Depth(SAMPLE_DEPTH_TEXTURE(_CameraDepthTexture, uv)); } half4 frag(v2f_img i) : SV_Target { half4 source = tex2D(_MainTex, i.uv); float4 d = float4(_MainTex_TexelSize.xy, -_MainTex_TexelSize.x, 0); float z0_sample = SAMPLE_DEPTH_TEXTURE(_CameraDepthTexture, i.uv); float z0_real = LinearEyeDepth(z0_sample); float z0 = Linear01Depth(z0_sample); float4 z_diag = float4( get_depth(i.uv + d.xy), // TR get_depth(i.uv + d.zy), // TL get_depth(i.uv - d.zy), // BR get_depth(i.uv - d.xy) // BL ); float4 z_axis = float4( get_depth(i.uv + d.wy), // T get_depth(i.uv - d.xw), // L get_depth(i.uv + d.xw), // R get_depth(i.uv - d.wy) // B ); z_diag = max(z_diag, z0.xxxx); z_axis = max(z_axis, z0.xxxx); z_diag -= z0; z_axis /= z0; float4 sobel_h = z_diag * float4( 1, 1, -1, -1) + z_axis * float4( 1, 0, 0, -1); float4 sobel_v = z_diag * float4(-1, 1, -1, 1) + z_axis * float4( 0, 1, -1, 0); float sobel_x = dot(sobel_h, (float4)1); float sobel_y = dot(sobel_v, (float4)1); float sobel = sqrt(sobel_x * sobel_x + sobel_y * sobel_y); float falloff = 1.0 - saturate(z0_real / _FallOffDepth); float op = saturate((sobel * falloff - _Threshold) * _Strength); half3 c_0 = lerp(source.rgb, _BgColor.rgb, _BgColor.a); half3 c_o = lerp(c_0, _Color.rgb, op * _Color.a); return half4(c_o, source.a); } ENDCG SubShader { Pass { ZTest Always Cull Off ZWrite Off CGPROGRAM #pragma vertex vert_img #pragma fragment frag #pragma target 3.0 ENDCG } } } <|start_filename|>Assets/Kino/Contour/Contour.cs<|end_filename|> // // KinoContour - Contour line effect // // Copyright (C) 2015 <NAME> // // 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. // using UnityEngine; namespace Kino { [ExecuteInEditMode] [RequireComponent(typeof(Camera))] [AddComponentMenu("Kino Image Effects/Contour")] public class Contour : MonoBehaviour { #region Public Properties // Line color [SerializeField] Color _lineColor = Color.black; public Color lineColor { get { return _lineColor; } set { _lineColor = value; } } // Filter strength [SerializeField, Range(1, 10)] float _filterStrength = 1; public float filterStrength { get { return _filterStrength; } set { _filterStrength = value; } } // Filter threshold [SerializeField, Range(0.1f, 1.0f)] float _filterThreshold = 0.1f; public float filterThreshold { get { return _filterThreshold; } set { _filterThreshold = value; } } // Depth fall-off [SerializeField] float _fallOffDepth = 40; public float fallOffDepth { get { return _fallOffDepth; } set { _fallOffDepth = value; } } // Background color [SerializeField] Color _backgroundColor = new Color(1, 1, 1, 0); public Color backgroundColor { get { return _backgroundColor; } set { _backgroundColor = value; } } #endregion #region Private Properties [SerializeField] Shader _shader; Material _material; #endregion #region MonoBehaviour Functions void OnEnable() { GetComponent<Camera>().depthTextureMode |= DepthTextureMode.Depth; } void OnRenderImage(RenderTexture source, RenderTexture destination) { if (_material == null) { _material = new Material(_shader); _material.hideFlags = HideFlags.DontSave; } _material.SetFloat("_Strength", _filterStrength); _material.SetFloat("_Threshold", _filterThreshold); _material.SetFloat("_FallOffDepth", _fallOffDepth); _material.SetColor("_Color", _lineColor); _material.SetColor("_BgColor", _backgroundColor); Graphics.Blit(source, destination, _material); } #endregion } } <|start_filename|>Assets/Kvant/Tunnel/Editor/TunnelMaterialEditor.cs<|end_filename|> // // Custom material editor for Tunnel surface shader // using UnityEngine; using UnityEditor; namespace Kvant { public class TunnelMaterialEditor : ShaderGUI { MaterialProperty _color; MaterialProperty _metallic; MaterialProperty _smoothness; MaterialProperty _albedoMap; MaterialProperty _normalMap; MaterialProperty _normalScale; MaterialProperty _occlusionMap; MaterialProperty _occlusionStr; MaterialProperty _mapScale; static GUIContent _albedoText = new GUIContent("Albedo"); static GUIContent _normalMapText = new GUIContent("Normal Map"); static GUIContent _occlusionText = new GUIContent("Occlusion"); bool _initial = true; void FindProperties(MaterialProperty[] props) { _color = FindProperty("_Color", props); _metallic = FindProperty("_Metallic", props); _smoothness = FindProperty("_Smoothness", props); _albedoMap = FindProperty("_MainTex", props); _normalMap = FindProperty("_NormalMap", props); _normalScale = FindProperty("_NormalScale", props); _occlusionMap = FindProperty("_OcclusionMap", props); _occlusionStr = FindProperty("_OcclusionStr", props); _mapScale = FindProperty("_MapScale", props); } public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] properties) { FindProperties(properties); if (ShaderPropertiesGUI(materialEditor) || _initial) foreach (Material m in materialEditor.targets) SetMaterialKeywords(m); _initial = false; } bool ShaderPropertiesGUI(MaterialEditor materialEditor) { EditorGUI.BeginChangeCheck(); materialEditor.ShaderProperty(_color, "Color"); materialEditor.ShaderProperty(_metallic, "Metallic"); materialEditor.ShaderProperty(_smoothness, "Smoothness"); EditorGUILayout.Space(); materialEditor.TexturePropertySingleLine(_albedoText, _albedoMap, null); var scale = _normalMap.textureValue ? _normalScale : null; materialEditor.TexturePropertySingleLine(_normalMapText, _normalMap, scale); var str = _occlusionMap.textureValue ? _occlusionStr : null; materialEditor.TexturePropertySingleLine(_occlusionText, _occlusionMap, str); if (_albedoMap.textureValue || _normalMap.textureValue || _occlusionMap.textureValue) materialEditor.ShaderProperty(_mapScale, "Scale"); return EditorGUI.EndChangeCheck(); } static void SetMaterialKeywords(Material material) { SetKeyword(material, "_ALBEDOMAP", material.GetTexture("_MainTex")); SetKeyword(material, "_NORMALMAP", material.GetTexture("_NormalMap")); SetKeyword(material, "_OCCLUSIONMAP", material.GetTexture("_OcclusionMap")); } static void SetKeyword(Material m, string keyword, bool state) { if (state) m.EnableKeyword(keyword); else m.DisableKeyword(keyword); } } } <|start_filename|>Assets/Kvant/Spray/Editor/SprayEditor.cs<|end_filename|> // // Custom editor class for Spray // using UnityEngine; using UnityEditor; namespace Kvant { [CanEditMultipleObjects] [CustomEditor(typeof(Spray))] public class SprayEditor : Editor { SerializedProperty _maxParticles; SerializedProperty _emitterCenter; SerializedProperty _emitterSize; SerializedProperty _throttle; SerializedProperty _minLife; SerializedProperty _maxLife; SerializedProperty _minSpeed; SerializedProperty _maxSpeed; SerializedProperty _direction; SerializedProperty _spread; SerializedProperty _minSpin; SerializedProperty _maxSpin; SerializedProperty _noiseAmplitude; SerializedProperty _noiseFrequency; SerializedProperty _noiseSpeed; SerializedProperty _shapes; SerializedProperty _minScale; SerializedProperty _maxScale; SerializedProperty _material; SerializedProperty _castShadows; SerializedProperty _receiveShadows; SerializedProperty _randomSeed; SerializedProperty _debug; static GUIContent _textCenter = new GUIContent("Center"); static GUIContent _textSize = new GUIContent("Size"); static GUIContent _textLife = new GUIContent("Life"); static GUIContent _textSpeed = new GUIContent("Speed"); static GUIContent _textSpin = new GUIContent("Spin"); static GUIContent _textAmplitude = new GUIContent("Amplitude"); static GUIContent _textFrequency = new GUIContent("Frequency"); static GUIContent _textScale = new GUIContent("Scale"); void OnEnable() { _maxParticles = serializedObject.FindProperty("_maxParticles"); _emitterCenter = serializedObject.FindProperty("_emitterCenter"); _emitterSize = serializedObject.FindProperty("_emitterSize"); _throttle = serializedObject.FindProperty("_throttle"); _minLife = serializedObject.FindProperty("_minLife"); _maxLife = serializedObject.FindProperty("_maxLife"); _minSpeed = serializedObject.FindProperty("_minSpeed"); _maxSpeed = serializedObject.FindProperty("_maxSpeed"); _direction = serializedObject.FindProperty("_direction"); _spread = serializedObject.FindProperty("_spread"); _minSpin = serializedObject.FindProperty("_minSpin"); _maxSpin = serializedObject.FindProperty("_maxSpin"); _noiseAmplitude = serializedObject.FindProperty("_noiseAmplitude"); _noiseFrequency = serializedObject.FindProperty("_noiseFrequency"); _noiseSpeed = serializedObject.FindProperty("_noiseSpeed"); _shapes = serializedObject.FindProperty("_shapes"); _minScale = serializedObject.FindProperty("_minScale"); _maxScale = serializedObject.FindProperty("_maxScale"); _material = serializedObject.FindProperty("_material"); _castShadows = serializedObject.FindProperty("_castShadows"); _receiveShadows = serializedObject.FindProperty("_receiveShadows"); _randomSeed = serializedObject.FindProperty("_randomSeed"); _debug = serializedObject.FindProperty("_debug"); } public override void OnInspectorGUI() { var targetSpray = target as Spray; serializedObject.Update(); EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(_maxParticles); if (!_maxParticles.hasMultipleDifferentValues) { var note = "Allocated: " + targetSpray.maxParticles; EditorGUILayout.LabelField(" ", note, EditorStyles.miniLabel); } if (EditorGUI.EndChangeCheck()) targetSpray.NotifyConfigChange(); EditorGUILayout.LabelField("Emitter", EditorStyles.boldLabel); EditorGUILayout.PropertyField(_emitterCenter, _textCenter); EditorGUILayout.PropertyField(_emitterSize, _textSize); EditorGUILayout.PropertyField(_throttle); EditorGUILayout.Space(); MinMaxSlider(_textLife, _minLife, _maxLife, 0.1f, 5.0f); EditorGUILayout.Space(); EditorGUILayout.LabelField("Velocity", EditorStyles.boldLabel); MinMaxSlider(_textSpeed, _minSpeed, _maxSpeed, 0.0f, 30.0f); EditorGUILayout.PropertyField(_direction); EditorGUILayout.PropertyField(_spread); MinMaxSlider(_textSpin, _minSpin, _maxSpin, 0.0f, 1000.0f); EditorGUILayout.Space(); EditorGUILayout.LabelField("Turbulent Noise", EditorStyles.boldLabel); EditorGUILayout.Slider(_noiseAmplitude, 0.0f, 20.0f, _textAmplitude); EditorGUILayout.Slider(_noiseFrequency, 0.01f, 1.0f, _textFrequency); EditorGUILayout.Slider(_noiseSpeed, 0.0f, 10.0f, _textSpeed); EditorGUILayout.Space(); EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(_shapes, true); if (EditorGUI.EndChangeCheck()) targetSpray.NotifyConfigChange(); MinMaxSlider(_textScale, _minScale, _maxScale, 0.01f, 2.0f); EditorGUILayout.PropertyField(_material); EditorGUILayout.PropertyField(_castShadows); EditorGUILayout.PropertyField(_receiveShadows); EditorGUILayout.Space(); EditorGUILayout.PropertyField(_randomSeed); EditorGUILayout.PropertyField(_debug); serializedObject.ApplyModifiedProperties(); } void MinMaxSlider(GUIContent label, SerializedProperty propMin, SerializedProperty propMax, float minLimit, float maxLimit) { var min = propMin.floatValue; var max = propMax.floatValue; EditorGUI.BeginChangeCheck(); // Min-max slider. EditorGUILayout.MinMaxSlider(label, ref min, ref max, minLimit, maxLimit); var prevIndent = EditorGUI.indentLevel; EditorGUI.indentLevel = 0; // Float value boxes. var rect = EditorGUILayout.GetControlRect(); rect.x += EditorGUIUtility.labelWidth; rect.width = (rect.width - EditorGUIUtility.labelWidth) / 2 - 2; if (EditorGUIUtility.wideMode) { EditorGUIUtility.labelWidth = 28; min = Mathf.Clamp(EditorGUI.FloatField(rect, "min", min), minLimit, max); rect.x += rect.width + 4; max = Mathf.Clamp(EditorGUI.FloatField(rect, "max", max), min, maxLimit); EditorGUIUtility.labelWidth = 0; } else { min = Mathf.Clamp(EditorGUI.FloatField(rect, min), minLimit, max); rect.x += rect.width + 4; max = Mathf.Clamp(EditorGUI.FloatField(rect, max), min, maxLimit); } EditorGUI.indentLevel = prevIndent; if (EditorGUI.EndChangeCheck()) { propMin.floatValue = min; propMax.floatValue = max; } } } } <|start_filename|>Assets/Kvant/Wall/Editor/WallMaterialEditor.cs<|end_filename|> // // Custom material editor for Wall surface shader // using UnityEngine; using UnityEditor; namespace Kvant { public class WallMaterialEditor : ShaderGUI { MaterialProperty _colorMode; MaterialProperty _color; MaterialProperty _color2; MaterialProperty _metallic; MaterialProperty _smoothness; MaterialProperty _albedoMap; MaterialProperty _normalMap; MaterialProperty _normalScale; MaterialProperty _occlusionMap; MaterialProperty _occlusionStr; MaterialProperty _randomUV; static GUIContent _albedoText = new GUIContent("Albedo"); static GUIContent _normalMapText = new GUIContent("Normal Map"); static GUIContent _occlusionText = new GUIContent("Occlusion"); bool _initial = true; void FindProperties(MaterialProperty[] props) { _colorMode = FindProperty("_ColorMode", props); _color = FindProperty("_Color", props); _color2 = FindProperty("_Color2", props); _metallic = FindProperty("_Metallic", props); _smoothness = FindProperty("_Smoothness", props); _albedoMap = FindProperty("_MainTex", props); _normalMap = FindProperty("_NormalMap", props); _normalScale = FindProperty("_NormalScale", props); _occlusionMap = FindProperty("_OcclusionMap", props); _occlusionStr = FindProperty("_OcclusionStr", props); _randomUV = FindProperty("_RandomUV", props); } public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] properties) { FindProperties(properties); if (ShaderPropertiesGUI(materialEditor) || _initial) foreach (Material m in materialEditor.targets) SetMaterialKeywords(m); _initial = false; } bool ShaderPropertiesGUI(MaterialEditor materialEditor) { EditorGUI.BeginChangeCheck(); materialEditor.ShaderProperty(_colorMode, "Color Mode"); if (_colorMode.floatValue > 0) { var rect = EditorGUILayout.GetControlRect(); rect.x += EditorGUIUtility.labelWidth; rect.width = (rect.width - EditorGUIUtility.labelWidth) / 2 - 2; materialEditor.ShaderProperty(rect, _color, ""); rect.x += rect.width + 4; materialEditor.ShaderProperty(rect, _color2, ""); } else { materialEditor.ShaderProperty(_color, " "); } EditorGUILayout.Space(); materialEditor.ShaderProperty(_metallic, "Metallic"); materialEditor.ShaderProperty(_smoothness, "Smoothness"); EditorGUILayout.Space(); materialEditor.TexturePropertySingleLine(_albedoText, _albedoMap, null); materialEditor.TexturePropertySingleLine(_normalMapText, _normalMap, _normalMap.textureValue ? _normalScale : null); materialEditor.TexturePropertySingleLine(_occlusionText, _occlusionMap, _occlusionMap.textureValue ? _occlusionStr : null); materialEditor.TextureScaleOffsetProperty(_albedoMap); EditorGUILayout.Space(); materialEditor.ShaderProperty(_randomUV, "Random UV"); return EditorGUI.EndChangeCheck(); } static void SetMaterialKeywords(Material material) { SetKeyword(material, "_ALBEDOMAP", material.GetTexture("_MainTex")); SetKeyword(material, "_NORMALMAP", material.GetTexture("_NormalMap")); SetKeyword(material, "_OCCLUSIONMAP", material.GetTexture("_OcclusionMap")); } static void SetKeyword(Material m, string keyword, bool state) { if (state) m.EnableKeyword(keyword); else m.DisableKeyword(keyword); } } } <|start_filename|>Assets/ImageSequenceOut/Editor/ImageSequenceOutEditor.cs<|end_filename|> // Image Sequence Output Utility // http://github.com/keijiro/SequenceOut using UnityEngine; using UnityEditor; [CustomEditor(typeof(ImageSequenceOut))] public class ImageSequenceOutEditor : Editor { SerializedProperty _frameRate; SerializedProperty _superSampling; SerializedProperty _recordOnStart; void OnEnable() { _frameRate = serializedObject.FindProperty("_frameRate"); _superSampling = serializedObject.FindProperty("_superSampling"); _recordOnStart = serializedObject.FindProperty("_recordOnStart"); } public override void OnInspectorGUI() { serializedObject.Update(); EditorGUILayout.PropertyField(_frameRate); EditorGUILayout.PropertyField(_superSampling); if (Application.isPlaying) { var iso = (ImageSequenceOut)target; var buttonStyle = GUILayout.Height(30); if (iso.isRecording) { var time = (float)iso.frameCount / iso.frameRate; var label = "STOP (" + time.ToString("0.0") + "s)"; if (GUILayout.Button(label, buttonStyle)) iso.StopRecording(); EditorUtility.SetDirty(target); // force repaint } else { if (GUILayout.Button("REC", buttonStyle)) iso.StartRecording(); } } else { EditorGUILayout.PropertyField(_recordOnStart); } serializedObject.ApplyModifiedProperties(); } } <|start_filename|>Assets/Squamata/Shader/Squamata.shader<|end_filename|> Shader "Custom/Squamata" { Properties { _Color ("Color", Color) = (1,1,1,1) _Metallic ("Metallic", Range(0,1)) = 0.5 _Smoothness ("Smoothness", Range(0,1)) = 0.5 } SubShader { Tags { "RenderType"="Opaque" } CGPROGRAM #pragma surface surf Standard vertex:vert nolightmap addshadow #pragma target 3.0 #include "ClassicNoise3D.cginc" struct Input { float dummy; }; half4 _Color; half _Smoothness; half _Metallic; float3 _NoiseOffset; float _NoiseFrequency; float _NoiseAmplitude; float _Opacity; float _Radius; void vert(inout appdata_full v) { float n = cnoise(mul(_Object2World, v.color) * _NoiseFrequency + _NoiseOffset); n = saturate((n + _Opacity * 2 - 1) * _NoiseAmplitude); v.vertex.xyz = lerp(v.color.xyz, v.vertex.xyz, n) * _Radius; } void surf(Input IN, inout SurfaceOutputStandard o) { o.Albedo = _Color.rgb; o.Metallic = _Metallic; o.Smoothness = _Smoothness; } ENDCG } } <|start_filename|>Assets/Kvant/Spray/Spray.cs<|end_filename|> // // Spray - mesh particle system // using UnityEngine; using UnityEngine.Rendering; namespace Kvant { [ExecuteInEditMode] [AddComponentMenu("Kvant/Spray")] public partial class Spray : MonoBehaviour { #region Basic Properties [SerializeField] int _maxParticles = 1000; public int maxParticles { get { // Returns actual number of particles. if (_bulkMesh == null || _bulkMesh.copyCount < 1) return 0; return (_maxParticles / _bulkMesh.copyCount + 1) * _bulkMesh.copyCount; } } #endregion #region Emitter Settings [SerializeField] Vector3 _emitterCenter = Vector3.zero; public Vector3 emitterCenter { get { return _emitterCenter; } set { _emitterCenter = value; } } [SerializeField] Vector3 _emitterSize = Vector3.one; public Vector3 emitterSize { get { return _emitterSize; } set { _emitterSize = value; } } [SerializeField, Range(0, 1)] float _throttle = 1.0f; public float throttle { get { return _throttle; } set { _throttle = value; } } #endregion #region Life Parameters [SerializeField] float _minLife = 1.0f; public float minLife { get { return _minLife; } set { _minLife = value; } } [SerializeField] float _maxLife = 4.0f; public float maxLife { get { return _maxLife; } set { _maxLife = value; } } #endregion #region Velocity Parameters [SerializeField] float _minSpeed = 2.0f; public float minSpeed { get { return _minSpeed; } set { _minSpeed = value; } } [SerializeField] float _maxSpeed = 10.0f; public float maxSpeed { get { return _maxSpeed; } set { _maxSpeed = value; } } [SerializeField] Vector3 _direction = Vector3.forward; public Vector3 direction { get { return _direction; } set { _direction = value; } } [SerializeField, Range(0, 1)] float _spread = 0.2f; public float spread { get { return _spread; } set { _spread = value; } } [SerializeField] float _minSpin = 30.0f; public float minSpin { get { return _minSpin; } set { _minSpin = value; } } [SerializeField] float _maxSpin = 200.0f; public float maxSpin { get { return _maxSpin; } set { _maxSpin = value; } } #endregion #region Noise Parameters [SerializeField] float _noiseAmplitude = 5.0f; public float noiseAmplitude { get { return _noiseAmplitude; } set { _noiseAmplitude = value; } } [SerializeField] float _noiseFrequency = 0.2f; public float noiseFrequency { get { return _noiseFrequency; } set { _noiseFrequency = value; } } [SerializeField] float _noiseSpeed = 1.0f; public float noiseSpeed { get { return _noiseSpeed; } set { _noiseSpeed = value; } } #endregion #region Render Settings [SerializeField] Mesh[] _shapes = new Mesh[1]; [SerializeField] float _minScale = 0.1f; public float minScale { get { return _minScale; } set { _minScale = value; } } [SerializeField] float _maxScale = 1.2f; public float maxScale { get { return _maxScale; } set { _maxScale = value; } } [SerializeField] Material _material; bool _owningMaterial; // whether owning the material public Material sharedMaterial { get { return _material; } set { _material = value; } } public Material material { get { if (!_owningMaterial) { _material = Instantiate<Material>(_material); _owningMaterial = true; } return _material; } set { if (_owningMaterial) Destroy(_material, 0.1f); _material = value; _owningMaterial = false; } } [SerializeField] ShadowCastingMode _castShadows; public ShadowCastingMode shadowCastingMode { get { return _castShadows; } set { _castShadows = value; } } [SerializeField] bool _receiveShadows = false; public bool receiveShadows { get { return _receiveShadows; } set { _receiveShadows = value; } } #endregion #region Misc Settings [SerializeField] int _randomSeed = 0; public int randomSeed { get { return _randomSeed; } set { _randomSeed = value; } } [SerializeField] bool _debug; #endregion #region Built-in Resources [SerializeField] Material _defaultMaterial; [SerializeField] Shader _kernelShader; [SerializeField] Shader _debugShader; #endregion #region Private Variables And Properties RenderTexture _positionBuffer1; RenderTexture _positionBuffer2; RenderTexture _rotationBuffer1; RenderTexture _rotationBuffer2; BulkMesh _bulkMesh; Material _kernelMaterial; Material _debugMaterial; bool _needsReset = true; static float deltaTime { get { var isEditor = !Application.isPlaying || Time.frameCount < 2; return isEditor ? 1.0f / 10 : Time.deltaTime; } } #endregion #region Resource Management public void NotifyConfigChange() { _needsReset = true; } Material CreateMaterial(Shader shader) { var material = new Material(shader); material.hideFlags = HideFlags.DontSave; return material; } RenderTexture CreateBuffer() { var width = _bulkMesh.copyCount; var height = _maxParticles / width + 1; var buffer = new RenderTexture(width, height, 0, RenderTextureFormat.ARGBFloat); buffer.hideFlags = HideFlags.DontSave; buffer.filterMode = FilterMode.Point; buffer.wrapMode = TextureWrapMode.Repeat; return buffer; } void UpdateKernelShader() { var m = _kernelMaterial; m.SetVector("_EmitterPos", _emitterCenter); m.SetVector("_EmitterSize", _emitterSize); m.SetVector("_LifeParams", new Vector2(1.0f / _minLife, 1.0f / _maxLife)); var dir = new Vector4(_direction.x, _direction.y, _direction.z, _spread); m.SetVector("_Direction", dir); var pi360 = Mathf.PI / 360; var sparams = new Vector4(_minSpeed, _maxSpeed, _minSpin * pi360, _maxSpin * pi360); m.SetVector("_SpeedParams", sparams); var np = new Vector3(_noiseFrequency, _noiseAmplitude, _noiseSpeed); m.SetVector("_NoiseParams", np); m.SetVector("_Config", new Vector4(_throttle, _randomSeed, deltaTime, Time.time)); } void ResetResources() { if (_bulkMesh == null) _bulkMesh = new BulkMesh(_shapes); else _bulkMesh.Rebuild(_shapes); if (_positionBuffer1) DestroyImmediate(_positionBuffer1); if (_positionBuffer2) DestroyImmediate(_positionBuffer2); if (_rotationBuffer1) DestroyImmediate(_rotationBuffer1); if (_rotationBuffer2) DestroyImmediate(_rotationBuffer2); _positionBuffer1 = CreateBuffer(); _positionBuffer2 = CreateBuffer(); _rotationBuffer1 = CreateBuffer(); _rotationBuffer2 = CreateBuffer(); if (!_kernelMaterial) _kernelMaterial = CreateMaterial(_kernelShader); if (!_debugMaterial) _debugMaterial = CreateMaterial(_debugShader); // Warming up UpdateKernelShader(); InitializeAndPrewarmBuffers(); _needsReset = false; } void InitializeAndPrewarmBuffers() { Graphics.Blit(null, _positionBuffer2, _kernelMaterial, 0); Graphics.Blit(null, _rotationBuffer2, _kernelMaterial, 1); // Call the update kernels repeatedly. for (var i = 0; i < 8; i++) { Graphics.Blit(_positionBuffer2, _positionBuffer1, _kernelMaterial, 2); Graphics.Blit(_rotationBuffer2, _rotationBuffer1, _kernelMaterial, 3); Graphics.Blit(_positionBuffer1, _positionBuffer2, _kernelMaterial, 2); Graphics.Blit(_rotationBuffer1, _rotationBuffer2, _kernelMaterial, 3); } } #endregion #region MonoBehaviour Functions void Reset() { _needsReset = true; } void OnDestroy() { if (_bulkMesh != null) _bulkMesh.Release(); if (_positionBuffer1) DestroyImmediate(_positionBuffer1); if (_positionBuffer2) DestroyImmediate(_positionBuffer2); if (_rotationBuffer1) DestroyImmediate(_rotationBuffer1); if (_rotationBuffer2) DestroyImmediate(_rotationBuffer2); if (_kernelMaterial) DestroyImmediate(_kernelMaterial); if (_debugMaterial) DestroyImmediate(_debugMaterial); } void Update() { if (_needsReset) ResetResources(); UpdateKernelShader(); if (Application.isPlaying) { // Swap the particle buffers. var temp = _positionBuffer1; _positionBuffer1 = _positionBuffer2; _positionBuffer2 = temp; temp = _rotationBuffer1; _rotationBuffer1 = _rotationBuffer2; _rotationBuffer2 = temp; // Call the kernel shader. Graphics.Blit(_positionBuffer1, _positionBuffer2, _kernelMaterial, 2); Graphics.Blit(_rotationBuffer1, _rotationBuffer2, _kernelMaterial, 3); } else { InitializeAndPrewarmBuffers(); } // Make a material property block for the following drawcalls. var props = new MaterialPropertyBlock(); props.SetTexture("_PositionBuffer", _positionBuffer2); props.SetTexture("_RotationBuffer", _rotationBuffer2); props.SetFloat("_ScaleMin", _minScale); props.SetFloat("_ScaleMax", _maxScale); props.SetFloat("_RandomSeed", _randomSeed); // Temporary variables var mesh = _bulkMesh.mesh; var position = transform.position; var rotation = transform.rotation; var material = _material ? _material : _defaultMaterial; var uv = new Vector2(0.5f / _positionBuffer2.width, 0); // Draw a bulk mesh repeatedly. for (var i = 0; i < _positionBuffer2.height; i++) { uv.y = (0.5f + i) / _positionBuffer2.height; props.AddVector("_BufferOffset", uv); Graphics.DrawMesh( mesh, position, rotation, material, 0, null, 0, props, _castShadows, _receiveShadows); } } void OnGUI() { if (_debug && Event.current.type.Equals(EventType.Repaint)) { if (_debugMaterial && _positionBuffer2 && _rotationBuffer2) { var w = _positionBuffer2.width; var h = _positionBuffer2.height; var rect = new Rect(0, 0, w, h); Graphics.DrawTexture(rect, _positionBuffer2, _debugMaterial); rect.y += h; Graphics.DrawTexture(rect, _rotationBuffer2, _debugMaterial); } } } void OnDrawGizmosSelected() { Gizmos.color = Color.yellow; Gizmos.matrix = transform.localToWorldMatrix; Gizmos.DrawWireCube(_emitterCenter, _emitterSize); } #endregion } } <|start_filename|>Assets/Kino/Contour/Editor/ContourEditor.cs<|end_filename|> // // KinoContour - Contour line effect // // Copyright (C) 2015 <NAME> // // 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. // using UnityEngine; using UnityEditor; namespace Kino { [CanEditMultipleObjects] [CustomEditor(typeof(Contour))] public class ContourEditor : Editor { SerializedProperty _lineColor; SerializedProperty _filterStrength; SerializedProperty _filterThreshold; SerializedProperty _fallOffDepth; SerializedProperty _backgroundColor; void OnEnable() { _lineColor = serializedObject.FindProperty("_lineColor"); _filterStrength = serializedObject.FindProperty("_filterStrength"); _filterThreshold = serializedObject.FindProperty("_filterThreshold"); _fallOffDepth = serializedObject.FindProperty("_fallOffDepth"); _backgroundColor = serializedObject.FindProperty("_backgroundColor"); } public override void OnInspectorGUI() { serializedObject.Update(); EditorGUILayout.PropertyField(_lineColor); EditorGUILayout.PropertyField(_filterStrength); EditorGUILayout.PropertyField(_filterThreshold); EditorGUILayout.PropertyField(_fallOffDepth); EditorGUILayout.PropertyField(_backgroundColor); serializedObject.ApplyModifiedProperties(); } } } <|start_filename|>Assets/Shell/ShellRenderer.cs<|end_filename|> // // Deforming shell like thing // using UnityEngine; using UnityEngine.Rendering; using Emgen; [ExecuteInEditMode] public class ShellRenderer : MonoBehaviour { #region Public Properties // Subdivision level [SerializeField, Range(0, 4)] int _subdivision = 2; public int subdivision { get { return _subdivision; } set { _subdivision = Mathf.Clamp(value, 0, 4); } } // Wave speed [SerializeField, Header("Wave Parameters")] float _waveSpeed = 8; public float waveSpeed { get { return _waveSpeed; } set { _waveSpeed = value; } } // Wave parameter alpha [SerializeField] float _waveAlpha = 1; public float waveAlpha { get { return _waveAlpha; } set { _waveAlpha = value; } } // Wave parameter beta [SerializeField] float _waveBeta = 1; public float waveBeta { get { return _waveBeta; } set { _waveBeta = value; } } // Cutoff level [SerializeField, Range(0, 1)] float _cutoff = 0.5f; public float cutoff { get { return _cutoff; } set { _cutoff = value; } } // Noise amplitude [SerializeField, Header("Noise Parameters")] float _noiseAmplitude = 5; public float noiseAmplitude { get { return _noiseAmplitude; } set { _noiseAmplitude = value; } } // Exponent of noise amplitude [SerializeField] float _noiseExponent = 4.5f; public float noiseExponent { get { return _noiseExponent; } set { _noiseExponent = value; } } // Noise frequency [SerializeField] float _noiseFrequency = 3; public float noiseFrequency { get { return _noiseFrequency; } set { _noiseFrequency = value; } } // Noise speed [SerializeField] float _noiseSpeed = 3; public float noiseSpeed { get { return _noiseSpeed; } set { _noiseSpeed = value; } } // Rendering settings [SerializeField, Header("Rendering")] Material _material; bool _owningMaterial; // whether owning the material public Material sharedMaterial { get { return _material; } set { _material = value; } } public Material material { get { if (!_owningMaterial) { _material = Instantiate<Material>(_material); _owningMaterial = true; } return _material; } set { if (_owningMaterial) Destroy(_material, 0.1f); _material = value; _owningMaterial = false; } } [SerializeField] bool _receiveShadows; [SerializeField] ShadowCastingMode _shadowCastingMode; #endregion #region Private Members Mesh _mesh; int _subdivided = -1; float _waveTime; Vector3 _noiseOffset; #endregion #region MonoBehaviour Functions void Update() { if (_subdivided != _subdivision) RebuildMesh(); var noiseDir = new Vector3(1, 0.5f, 0.2f).normalized; _waveTime += Time.deltaTime * _waveSpeed; _noiseOffset += noiseDir * (Time.deltaTime * _noiseSpeed); var props = new MaterialPropertyBlock(); props.SetFloat("_Cutoff", _cutoff); Vector3 wparam1 = new Vector3(3.1f, 2.3f, 6.3f); Vector3 wparam2 = new Vector3(0.031f, 0.022f, 0.039f); Vector3 wparam3 = new Vector3(1.21f, 0.93f, 1.73f); props.SetFloat("_WTime", _waveTime); props.SetVector("_WParams1", wparam1 * _waveAlpha); props.SetVector("_WParams2", wparam2); props.SetVector("_WParams3", wparam3 * _waveBeta); props.SetVector("_NOffset", _noiseOffset); var np = new Vector3(_noiseFrequency, _noiseAmplitude, _noiseExponent); props.SetVector("_NParams", np); Graphics.DrawMesh( _mesh, transform.localToWorldMatrix, _material, 0, null, 0, props, _shadowCastingMode, _receiveShadows); } #endregion #region Mesh Builder void RebuildMesh() { if (_mesh) DestroyImmediate(_mesh); // The Shell vertex shader needs positions of three vertices in a triangle // to calculate the normal vector. To provide these information, it uses // not only the position attribute but also the normal and tangent attributes // to store the 2nd and 3rd vertex position. IcosphereBuilder ib = new IcosphereBuilder(); for (var i = 0; i < _subdivision; i++) ib.Subdivide(); var vc = ib.vertexCache; var vcount = 3 * vc.triangles.Count; var va1 = new Vector3[vcount]; var va2 = new Vector3[vcount]; var va3 = new Vector4[vcount]; var vi = 0; foreach (var t in vc.triangles) { var v1 = vc.vertices[t.i1]; var v2 = vc.vertices[t.i2]; var v3 = vc.vertices[t.i3]; va1[vi + 0] = v1; va2[vi + 0] = v2; va3[vi + 0] = v3; va1[vi + 1] = v2; va2[vi + 1] = v3; va3[vi + 1] = v1; va1[vi + 2] = v3; va2[vi + 2] = v1; va3[vi + 2] = v2; vi += 3; } _mesh = new Mesh(); _mesh.hideFlags = HideFlags.DontSave; _mesh.bounds = new Bounds(Vector3.zero, Vector3.one * 10); _mesh.vertices = va1; _mesh.normals = va2; _mesh.tangents = va3; _mesh.SetIndices(vc.MakeIndexArrayForFlatMesh(), MeshTopology.Triangles, 0); _subdivided = _subdivision; } #endregion } <|start_filename|>Assets/Emgen/Icosphere.cs<|end_filename|> // // Emgen - Mesh generator class library // using UnityEngine; using System.Collections.Generic; namespace Emgen { public class IcosphereBuilder { #region Internal Classes // Midpoint table class // Provides midpoints of edges without making duplication. class MidpointTable { VertexCache _vc; Dictionary<int, int> _table; // Generates a key for the table from a pair of indices. static int IndexPairToKey(int i1, int i2) { if (i1 < i2) return i1 | (i2 << 16); else return (i1 << 16) | i2; } // Constructor. public MidpointTable(VertexCache vc) { _vc = vc; _table = new Dictionary<int, int>(); } // Returns a midpoint with retrieving an existing vertex or adding a new one. public int GetMidpoint(int i1, int i2) { var key = IndexPairToKey(i1, i2); if (_table.ContainsKey(key)) return _table[key]; var mid = (_vc.vertices[i1] + _vc.vertices[i2]) * 0.5f; var i = _vc.AddVertex(mid.normalized); _table[key] = i; return i; } } #endregion #region Public Members public VertexCache vertexCache; #endregion #region Constructor public IcosphereBuilder() { var t = (Mathf.Sqrt(5) + 1) / 2; vertexCache = new VertexCache(); vertexCache.AddVertex(new Vector3(-1, +t, 0).normalized); vertexCache.AddVertex(new Vector3(+1, +t, 0).normalized); vertexCache.AddVertex(new Vector3(-1, -t, 0).normalized); vertexCache.AddVertex(new Vector3(+1, -t, 0).normalized); vertexCache.AddVertex(new Vector3(0, -1, +t).normalized); vertexCache.AddVertex(new Vector3(0, +1, +t).normalized); vertexCache.AddVertex(new Vector3(0, -1, -t).normalized); vertexCache.AddVertex(new Vector3(0, +1, -t).normalized); vertexCache.AddVertex(new Vector3(+t, 0, -1).normalized); vertexCache.AddVertex(new Vector3(+t, 0, +1).normalized); vertexCache.AddVertex(new Vector3(-t, 0, -1).normalized); vertexCache.AddVertex(new Vector3(-t, 0, +1).normalized); vertexCache.AddTriangle(0, 11, 5); vertexCache.AddTriangle(0, 5, 1); vertexCache.AddTriangle(0, 1, 7); vertexCache.AddTriangle(0, 7, 10); vertexCache.AddTriangle(0, 10, 11); vertexCache.AddTriangle(1, 5, 9); vertexCache.AddTriangle(5, 11, 4); vertexCache.AddTriangle(11, 10, 2); vertexCache.AddTriangle(10, 7, 6); vertexCache.AddTriangle(7, 1, 8); vertexCache.AddTriangle(3, 9, 4); vertexCache.AddTriangle(3, 4, 2); vertexCache.AddTriangle(3, 2, 6); vertexCache.AddTriangle(3, 6, 8); vertexCache.AddTriangle(3, 8, 9); vertexCache.AddTriangle(4, 9, 5); vertexCache.AddTriangle(2, 4, 11); vertexCache.AddTriangle(6, 2, 10); vertexCache.AddTriangle(8, 6, 7); vertexCache.AddTriangle(9, 8, 1); } #endregion #region Mesh Operation Methods public void Subdivide() { var vc = new VertexCache(); vc.vertices.AddRange(vertexCache.vertices); var midPoints = new MidpointTable(vc); foreach (var t in vertexCache.triangles) { var m1 = midPoints.GetMidpoint(t.i1, t.i2); var m2 = midPoints.GetMidpoint(t.i2, t.i3); var m3 = midPoints.GetMidpoint(t.i3, t.i1); vc.AddTriangle(t.i1, m1, m3); vc.AddTriangle(m1, t.i2, m2); vc.AddTriangle(m3, m2, t.i3); vc.AddTriangle(m1, m2, m3); } vertexCache = vc; } #endregion } } <|start_filename|>Assets/Kvant/Tunnel/Tunnel.cs<|end_filename|> // // Tunnel - fractal-deformed tunnel renderer // using UnityEngine; using UnityEngine.Rendering; namespace Kvant { [ExecuteInEditMode] [AddComponentMenu("Kvant/Tunnel")] public partial class Tunnel : MonoBehaviour { #region Basic Properties [SerializeField] int _slices = 40; public int slices { get { return _slices; } } [SerializeField] int _stacks = 100; public int stacks { get { return _totalStacks; } } [SerializeField] float _radius = 5; public float radius { get { return _radius; } set { _radius = value; } } [SerializeField] float _height = 50; public float height { get { return _height; } set { _height = value; } } [SerializeField] float _offset = 0; public float offset { get { return _offset; } set { _offset = value; } } #endregion #region Noise Parameters [SerializeField] int _noiseRepeat = 2; public int noiseRepeat { get { return _noiseRepeat; } set { _noiseRepeat = value; } } [SerializeField] float _noiseFrequency = 0.05f; public float noiseFrequency { get { return _noiseFrequency; } set { _noiseFrequency = value; } } [SerializeField, Range(1, 5)] int _noiseDepth = 3; public int noiseDepth { get { return _noiseDepth; } set { _noiseDepth = value; } } [SerializeField] float _noiseClampMin = -1.0f; public float noiseClampMin { get { return _noiseClampMin; } set { _noiseClampMin = value; } } [SerializeField] float _noiseClampMax = 1.0f; public float noiseClampMax { get { return _noiseClampMax; } set { _noiseClampMax = value; } } [SerializeField] float _noiseElevation = 1.0f; public float noiseElevation { get { return _noiseElevation; } set { _noiseElevation = value; } } [SerializeField, Range(0, 1)] float _noiseWarp = 0.0f; public float noiseWarp { get { return _noiseWarp; } set { _noiseWarp = value; } } #endregion #region Render Settings [SerializeField] Material _material; bool _owningMaterial; // whether owning the material public Material sharedMaterial { get { return _material; } set { _material = value; } } public Material material { get { if (!_owningMaterial) { _material = Instantiate<Material>(_material); _owningMaterial = true; } return _material; } set { if (_owningMaterial) Destroy(_material, 0.1f); _material = value; _owningMaterial = false; } } [SerializeField] ShadowCastingMode _castShadows; public ShadowCastingMode shadowCastingMode { get { return _castShadows; } set { _castShadows = value; } } [SerializeField] bool _receiveShadows = false; public bool receiveShadows { get { return _receiveShadows; } set { _receiveShadows = value; } } [SerializeField, ColorUsage(true, true, 0, 8, 0.125f, 3)] Color _lineColor = new Color(0, 0, 0, 0.4f); public Color lineColor { get { return _lineColor; } set { _lineColor = value; } } #endregion #region Editor Properties [SerializeField] bool _debug; #endregion #region Built-in Resources [SerializeField] Shader _kernelShader; [SerializeField] Shader _lineShader; [SerializeField] Shader _debugShader; #endregion #region Private Variables And Properties int _stacksPerSegment; int _totalStacks; RenderTexture _positionBuffer; RenderTexture _normalBuffer1; RenderTexture _normalBuffer2; BulkMesh _bulkMesh; Material _kernelMaterial; Material _lineMaterial; Material _debugMaterial; bool _needsReset = true; float ZOffset { get { return Mathf.Repeat(_offset, _height / _totalStacks * 2); } } float VOffset { get { return ZOffset - _offset; } } void UpdateColumnAndRowCounts() { // Sanitize the numbers. _slices = Mathf.Clamp(_slices, 4, 4096); _stacks = Mathf.Clamp(_stacks, 4, 4096); // Total number of vertices. var total_vc = _slices * (_stacks + 1) * 6; // Number of segments. var segments = total_vc / 65000 + 1; _stacksPerSegment = segments > 1 ? (_stacks / segments) / 2 * 2 : _stacks; _totalStacks = _stacksPerSegment * segments; } #endregion #region Resource Management public void NotifyConfigChange() { _needsReset = true; } Material CreateMaterial(Shader shader) { var material = new Material(shader); material.hideFlags = HideFlags.DontSave; return material; } RenderTexture CreateBuffer() { var width = _slices * 2; var height = _totalStacks + 1; var buffer = new RenderTexture(width, height, 0, RenderTextureFormat.ARGBFloat); buffer.hideFlags = HideFlags.DontSave; buffer.filterMode = FilterMode.Point; buffer.wrapMode = TextureWrapMode.Repeat; return buffer; } void UpdateKernelShader() { var m = _kernelMaterial; m.SetVector("_Extent", new Vector2(_radius, _height)); m.SetFloat("_Offset", VOffset); m.SetVector("_Frequency", new Vector2(_noiseRepeat, _noiseFrequency)); m.SetVector("_Amplitude", new Vector3(1, _noiseWarp, _noiseWarp) * _noiseElevation); m.SetVector("_ClampRange", new Vector2(_noiseClampMin, _noiseClampMax) * 1.415f); if (_noiseWarp > 0.0f) m.EnableKeyword("ENABLE_WARP"); else m.DisableKeyword("ENABLE_WARP"); for (var i = 1; i <= 5; i++) if (i == _noiseDepth) m.EnableKeyword("DEPTH" + i); else m.DisableKeyword("DEPTH" + i); } void ResetResources() { UpdateColumnAndRowCounts(); if (_bulkMesh == null) _bulkMesh = new BulkMesh(_slices, _stacksPerSegment, _totalStacks); else _bulkMesh.Rebuild(_slices, _stacksPerSegment, _totalStacks); if (_positionBuffer) DestroyImmediate(_positionBuffer); if (_normalBuffer1) DestroyImmediate(_normalBuffer1); if (_normalBuffer2) DestroyImmediate(_normalBuffer2); _positionBuffer = CreateBuffer(); _normalBuffer1 = CreateBuffer(); _normalBuffer2 = CreateBuffer(); if (!_kernelMaterial) _kernelMaterial = CreateMaterial(_kernelShader); if (!_lineMaterial) _lineMaterial = CreateMaterial(_lineShader); if (!_debugMaterial) _debugMaterial = CreateMaterial(_debugShader); _lineMaterial.SetTexture("_PositionBuffer", _positionBuffer); _needsReset = false; } #endregion #region MonoBehaviour Functions void Reset() { _needsReset = true; } void OnDestroy() { if (_bulkMesh != null) _bulkMesh.Release(); if (_positionBuffer) DestroyImmediate(_positionBuffer); if (_normalBuffer1) DestroyImmediate(_normalBuffer1); if (_normalBuffer2) DestroyImmediate(_normalBuffer2); if (_kernelMaterial) DestroyImmediate(_kernelMaterial); if (_lineMaterial) DestroyImmediate(_lineMaterial); if (_debugMaterial) DestroyImmediate(_debugMaterial); } void LateUpdate() { if (_needsReset) ResetResources(); // Call the kernels. UpdateKernelShader(); Graphics.Blit(null, _positionBuffer, _kernelMaterial, 0); Graphics.Blit(_positionBuffer, _normalBuffer1, _kernelMaterial, 1); Graphics.Blit(_positionBuffer, _normalBuffer2, _kernelMaterial, 2); // Update the line material. _lineMaterial.SetColor("_Color", _lineColor); // Make a material property block for the following drawcalls. var props1 = new MaterialPropertyBlock(); var props2 = new MaterialPropertyBlock(); props1.SetTexture("_PositionBuffer", _positionBuffer); props2.SetTexture("_PositionBuffer", _positionBuffer); props1.SetTexture("_NormalBuffer", _normalBuffer1); props2.SetTexture("_NormalBuffer", _normalBuffer2); var mapOffs = new Vector3(0, 0, VOffset); props1.SetVector("_MapOffset", mapOffs); props2.SetVector("_MapOffset", mapOffs); props1.SetFloat("_UseBuffer", 1); props2.SetFloat("_UseBuffer", 1); // VJ05 props1.SetFloat("_Darken", _lineColor.a); props2.SetFloat("_Darken", _lineColor.a); // Temporary variables. var mesh = _bulkMesh.mesh; var position = transform.position; var rotation = transform.rotation; var uv = new Vector2(0.5f / _positionBuffer.width, 0); position += transform.forward * ZOffset; // Draw mesh segments. for (var i = 0; i < _totalStacks; i += _stacksPerSegment) { uv.y = (0.5f + i) / _positionBuffer.height; props1.SetVector("_BufferOffset", uv); props2.SetVector("_BufferOffset", uv); if (_material) { // 1st half Graphics.DrawMesh( mesh, position, rotation, _material, 0, null, 0, props1, _castShadows, _receiveShadows); // 2nd half Graphics.DrawMesh( mesh, position, rotation, _material, 0, null, 1, props2, _castShadows, _receiveShadows); } // lines if (_lineColor.a > 0.0f) Graphics.DrawMesh( mesh, position, rotation, _lineMaterial, 0, null, 2, props1, false, false); } } void OnGUI() { if (_debug && Event.current.type.Equals(EventType.Repaint)) { if (_debugMaterial && _positionBuffer && _normalBuffer1 && _normalBuffer2) { var rect = new Rect(0, 0, (_slices + 1) * 2, _totalStacks + 1); Graphics.DrawTexture(rect, _positionBuffer, _debugMaterial); rect.y += rect.height; Graphics.DrawTexture(rect, _normalBuffer1, _debugMaterial); rect.y += rect.height; Graphics.DrawTexture(rect, _normalBuffer2, _debugMaterial); } } } #endregion } } <|start_filename|>Assets/VJ05/FogBgGear.cs<|end_filename|> using UnityEngine; public class FogBgGear : MonoBehaviour { public Reaktion.ReaktorLink reaktor; public Gradient gradient; void Awake() { reaktor.Initialize(this); } void Update() { var color = gradient.Evaluate(reaktor.Output); Camera.main.backgroundColor = color; RenderSettings.fogColor = color; } } <|start_filename|>Assets/Shell/Shader/Shell.shader<|end_filename|> Shader "Custom/Shell" { Properties { _Color1 ("Albedo (front)", Color) = (1,1,1,1) _Color2 ("Albedo (back)", Color) = (1,1,1,1) _Glossiness1 ("Smoothness (front)", Range(0,1)) = 0.5 _Glossiness2 ("Smoothness (back)", Range(0,1)) = 0.5 _Metallic1 ("Metallic (front)", Range(0,1)) = 0.0 _Metallic2 ("Metallic (back)", Range(0,1)) = 0.0 [HDR] _Emission ("Emission (front)", Color) = (1,1,1,1) } CGINCLUDE #include "ClassicNoise3D.cginc" float _WTime; float3 _WParams1; float3 _WParams2; float3 _WParams3; float3 _NOffset; float3 _NParams; // frequency, amplitude, exponent float wave_alpha(float3 p) { float a = sin(p.x * _WParams1.x * sin(_WTime * _WParams2.x) * _WParams3.x + sin(p.y * _WParams1.y * sin(_WTime * _WParams2.y)) * _WParams3.y + sin(p.z * _WParams1.z * sin(_WTime * _WParams2.z)) * _WParams3.z + _WTime); return (a + 1) / 2; } float3 noise_disp(float3 vp) { float n = cnoise(vp * _NParams.x + _NOffset); return vp * (1.0 + pow(abs(n), _NParams.z) * _NParams.y); } ENDCG SubShader { Tags { "RenderType"="TransparentCutout" "Queue"="AlphaTest" } // front-face Cull Back CGPROGRAM #pragma surface surf Standard vertex:vert alphatest:_Cutoff nolightmap addshadow #pragma target 3.0 struct Input { float3 worldPos; }; half4 _Color1; half _Glossiness1; half _Metallic1; half4 _Emission; void vert(inout appdata_full v) { float3 v1 = noise_disp(v.vertex.xyz); float3 v2 = noise_disp(v.normal); float3 v3 = noise_disp(v.tangent.xyz); v.vertex.xyz = v1; v.normal = normalize(cross(v2 - v1, v3 - v1)); } void surf(Input IN, inout SurfaceOutputStandard o) { o.Albedo = _Color1.rgb; o.Metallic = _Metallic1; o.Smoothness = _Glossiness1; o.Emission = _Emission; o.Alpha = wave_alpha(IN.worldPos); } ENDCG // back-face Cull Front CGPROGRAM #pragma surface surf Standard vertex:vert alphatest:_Cutoff nolightmap addshadow #pragma target 3.0 struct Input { float3 worldPos; }; half4 _Color2; half _Glossiness2; half _Metallic2; void vert(inout appdata_full v) { float3 v1 = noise_disp(v.vertex.xyz); float3 v2 = noise_disp(v.normal); float3 v3 = noise_disp(v.tangent.xyz); v.vertex.xyz = v1; v.normal = -normalize(cross(v2 - v1, v3 - v1)); } void surf(Input IN, inout SurfaceOutputStandard o) { o.Albedo = _Color2.rgb; o.Metallic = _Metallic2; o.Smoothness = _Glossiness2; o.Alpha = wave_alpha(IN.worldPos); } ENDCG } } <|start_filename|>Assets/Kvant/Spray/Shaders/Kernel.shader<|end_filename|> // // GPGPU kernels for Spray // // Texture format for position kernels: // .xyz = particle position // .w = life (+0.5 -> -0.5) // // Texture format for rotation kernels: // .xyzw = particle rotation // Shader "Hidden/Kvant/Spray/Kernel" { Properties { _MainTex ("-", 2D) = ""{} } CGINCLUDE #include "UnityCG.cginc" #include "ClassicNoise3D.cginc" sampler2D _MainTex; float3 _EmitterPos; float3 _EmitterSize; float2 _LifeParams; // 1/min, 1/max float4 _Direction; // x, y, z, spread float4 _SpeedParams; // min, max, minSpin, maxSpin float4 _NoiseParams; // freq, amp, speed float4 _Config; // throttle, random seed, dT, time // PRNG function float nrand(float2 uv, float salt) { uv += float2(salt, _Config.y); return frac(sin(dot(uv, float2(12.9898, 78.233))) * 43758.5453); } // Quaternion multiplication // http://mathworld.wolfram.com/Quaternion.html float4 qmul(float4 q1, float4 q2) { return float4( q2.xyz * q1.w + q1.xyz * q2.w + cross(q1.xyz, q2.xyz), q1.w * q2.w - dot(q1.xyz, q2.xyz) ); } // Particle generator functions float4 new_particle_position(float2 uv) { float t = _Config.w; // Random position float3 p = float3(nrand(uv, t), nrand(uv, t + 1), nrand(uv, t + 2)); p = (p - (float3)0.5) * _EmitterSize + _EmitterPos; // Throttling: discards particle emission by adding offset. float4 offs = float4(1e10, 1e10, 1e10, -1) * (uv.x > _Config.x); return float4(p, 0.5) + offs; } float4 new_particle_rotation(float2 uv) { // Uniform random unit quaternion // http://www.realtimerendering.com/resources/GraphicsGems/gemsiii/urot.c float r = nrand(uv, 3); float r1 = sqrt(1.0 - r); float r2 = sqrt(r); float t1 = UNITY_PI * 2 * nrand(uv, 4); float t2 = UNITY_PI * 2 * nrand(uv, 5); return float4(sin(t1) * r1, cos(t1) * r1, sin(t2) * r2, cos(t2) * r2); } // Position dependant velocity field float3 get_velocity(float3 p, float2 uv) { // Random vector float3 v = float3(nrand(uv, 6), nrand(uv, 7), nrand(uv, 8)); v = (v - (float3)0.5) * 2; // Spreading v = lerp(_Direction.xyz, v, _Direction.w); // Random speed v = normalize(v) * lerp(_SpeedParams.x, _SpeedParams.y, nrand(uv, 9)); // Noise vector p = (p + _Config.w * _NoiseParams.z) * _NoiseParams.x; float nx = cnoise(p + float3(138.2, 0, 0)); float ny = cnoise(p + float3(0, 138.2, 0)); float nz = cnoise(p + float3(0, 0, 138.2)); return v + float3(nx, ny, nz) * _NoiseParams.y; } // Deterministic random rotation axis float3 get_rotation_axis(float2 uv) { // Uniformaly distributed points // http://mathworld.wolfram.com/SpherePointPicking.html float u = nrand(uv, 10) * 2 - 1; float theta = nrand(uv, 11) * UNITY_PI * 2; float u2 = sqrt(1 - u * u); return float3(u2 * cos(theta), u2 * sin(theta), u); } // Pass 0: position initialization kernel float4 frag_init_position(v2f_img i) : SV_Target { return new_particle_position(i.uv); } // Pass 1: rotation initializatin kernel float4 frag_init_rotation(v2f_img i) : SV_Target { return new_particle_rotation(i.uv); } // Pass 2: position update kernel float4 frag_update_position(v2f_img i) : SV_Target { float4 p = tex2D(_MainTex, i.uv); // Decaying float dt = _Config.z; p.w -= lerp(_LifeParams.x, _LifeParams.y, nrand(i.uv, 12)) * dt; if (p.w > -0.5) { // Position update p.xyz += get_velocity(p.xyz, i.uv) * dt; return p; } else { // Respawn return new_particle_position(i.uv); } } // Pass 3: rotation update kernel float4 frag_update_rotation(v2f_img i) : SV_Target { float4 r = tex2D(_MainTex, i.uv); // Delta rotation float dt = _Config.z; float theta = lerp(_SpeedParams.z, _SpeedParams.w, nrand(i.uv, 13)) * dt; float4 dq = float4(get_rotation_axis(i.uv) * sin(theta), cos(theta)); // Applying delta rotation and normalization. return normalize(qmul(dq, r)); } ENDCG SubShader { Pass { CGPROGRAM #pragma target 3.0 #pragma vertex vert_img #pragma fragment frag_init_position ENDCG } Pass { CGPROGRAM #pragma target 3.0 #pragma vertex vert_img #pragma fragment frag_init_rotation ENDCG } Pass { CGPROGRAM #pragma target 3.0 #pragma vertex vert_img #pragma fragment frag_update_position ENDCG } Pass { CGPROGRAM #pragma target 3.0 #pragma vertex vert_img #pragma fragment frag_update_rotation ENDCG } } } <|start_filename|>Assets/Shaders/ImageEffects/Bloom_V2/VideoBloom.cs<|end_filename|> using UnityEngine; using System; [ExecuteInEditMode] [AddComponentMenu("Image Effects/Other/VideoBloom")] [RequireComponent(typeof(Camera))] public class VideoBloom : PostEffectsBase { public enum TweakMode { Basic = 0, Advanced = 1 } public enum BlendingMode { Add = 0, Screen = 1, } public TweakMode tweakMode = TweakMode.Basic; [Range(0.0f, 4.0f)] public float Threshold = 0.75f; [Range(0.0f, 5.0f)] public float MasterAmount = 0.5f; [Range(0.0f, 5.0f)] public float MediumAmount = 1.0f; [Range(0.0f, 100.0f)] public float LargeAmount = 0.0f; public Color Tint = new Color(1.0f, 1.0f, 1.0f, 1.0f); [Range(10.0f, 100.0f)] public float KernelSize = 50.0f; [Range(1.0f, 20.0f)] public float MediumKernelScale = 1.0f; [Range(3.0f, 20.0f)] public float LargeKernelScale = 3.0f; public BlendingMode BlendMode = BlendingMode.Add; public bool HighQuality = true; public float masterAmount { get { return MasterAmount; } set { MasterAmount = value; } } public Shader videoBloomShader; private Material videoBloomMaterial; public override bool CheckResources () { CheckSupport (false, true); videoBloomMaterial = CheckShaderAndCreateMaterial (videoBloomShader, videoBloomMaterial); if (!isSupported) ReportAutoDisable (); return isSupported; } float videoBlurGetMaxScaleFor(float radius) { double x = (double)radius; double sc = x < 10.0 ? (0.1*x * 1.468417):(x < 36.3287 ? (0.127368 * x + 0.194737):(0.8*(float)Math.Sqrt(x))); return sc <= 0.0 ? 0.0f:(float)sc; } void BloomBlit(RenderTexture source, RenderTexture blur1, RenderTexture blur2, float radius1, float radius2) { const float kd0 = (4.0f/3.0f); const float kd1 = (1.0f/3.0f); float maxScale = videoBlurGetMaxScaleFor(radius1); int blurIteration1 = (int)maxScale; float lerp1 = (maxScale - (float)blurIteration1); maxScale = videoBlurGetMaxScaleFor(radius2); int blurIteration2 = (int)maxScale; float dUV = 1.0f; int rtW = source.width; int rtH = source.height; float s0 = blurIteration1 != 0 ? 1.0f:-1.0f; Vector4 v; int i; if (radius1 == 0.0f) { Graphics.Blit(source, blur1); return; } RenderTexture rt = RenderTexture.GetTemporary(rtW, rtH, 0, RenderTextureFormat.ARGBHalf); rt.filterMode = FilterMode.Bilinear; rt.wrapMode = TextureWrapMode.Clamp; Graphics.Blit(source, rt); for (i = 0; i < blurIteration1; i++) { s0 = (i % 2 != 0 ? -1.0f:1.0f); v = new Vector4(s0 * dUV * kd0, dUV * kd1, s0 * dUV * kd1, -dUV * kd0); videoBloomMaterial.SetVector("_Param0", v); RenderTexture rt2 = RenderTexture.GetTemporary(rtW, rtH, 0, RenderTextureFormat.ARGBHalf); rt2.filterMode = FilterMode.Bilinear; rt2.wrapMode = TextureWrapMode.Clamp; videoBloomMaterial.SetTexture("_MainTex", rt); Graphics.Blit (rt, rt2, videoBloomMaterial, 0); RenderTexture.ReleaseTemporary(rt); rt = rt2; dUV = dUV * 1.414213562373095f; } v = new Vector4(-s0 * dUV * kd0, dUV * kd1, -s0 * dUV * kd1, -dUV * kd0); videoBloomMaterial.SetVector("_Param0", v); videoBloomMaterial.SetFloat("_Param2", lerp1); videoBloomMaterial.SetTexture("_MainTex", rt); Graphics.Blit (rt, blur1, videoBloomMaterial, 1); if (blur2 != null) { for ( ; i < blurIteration2; i++) { s0 = (i % 2 != 0 ? -1.0f:1.0f); v = new Vector4(s0 * dUV * kd0, dUV * kd1, s0 * dUV * kd1, -dUV * kd0); videoBloomMaterial.SetVector("_Param0", v); RenderTexture rt2 = RenderTexture.GetTemporary(rtW, rtH, 0, RenderTextureFormat.ARGBHalf); rt2.filterMode = FilterMode.Bilinear; rt2.wrapMode = TextureWrapMode.Clamp; videoBloomMaterial.SetTexture("_MainTex", rt); Graphics.Blit (rt, rt2, videoBloomMaterial, 0); RenderTexture.ReleaseTemporary(rt); rt = rt2; dUV = dUV * 1.414213562373095f; } v = new Vector4(-s0 * dUV * kd0, dUV * kd1, -s0 * dUV * kd1, -dUV * kd0); videoBloomMaterial.SetVector("_Param0", v); videoBloomMaterial.SetFloat("_Param2", (maxScale - (float)blurIteration2)); videoBloomMaterial.SetTexture("_MainTex", rt); Graphics.Blit (rt, blur2, videoBloomMaterial, 1); } RenderTexture.ReleaseTemporary(rt); } //[ImageEffectOpaque] void OnRenderImage (RenderTexture source, RenderTexture destination) { if ((MediumAmount == 0.0f && LargeAmount == 0.0f) || MasterAmount == 0.0f || !CheckResources( )) { Graphics.Blit(source, destination); return; } float coe = HighQuality == true ? 1.0f:0.25f; int rtW = (int)(coe * (float)source.width); int rtH = (int)(coe * (float)source.height); Vector4 weight = new Vector4(0.5f * MasterAmount*MediumAmount, 0.5f * MasterAmount*LargeAmount, 0.0f, 0.0f); Vector4 tint = new Vector4(Tint.r, Tint.g, Tint.b, 1.0f); float radius1 = KernelSize * MediumKernelScale * coe; float radius2 = KernelSize * LargeKernelScale * coe; RenderTexture tmp1 = RenderTexture.GetTemporary(rtW, rtH, 0, RenderTextureFormat.ARGBHalf); RenderTexture tmp2 = RenderTexture.GetTemporary(rtW, rtH, 0, RenderTextureFormat.ARGBHalf); RenderTexture tmp3 = null; tmp1.filterMode = FilterMode.Bilinear; tmp1.wrapMode = TextureWrapMode.Clamp; tmp2.filterMode = FilterMode.Bilinear; tmp2.wrapMode = TextureWrapMode.Clamp; if (HighQuality == true) { videoBloomMaterial.SetFloat("_Param2", Threshold); Graphics.Blit(source, tmp1, videoBloomMaterial, 2); } else { tmp3 = RenderTexture.GetTemporary(2 * rtW, 2 * rtH, 0, RenderTextureFormat.ARGBHalf); tmp3.filterMode = FilterMode.Bilinear; tmp3.wrapMode = TextureWrapMode.Clamp; Graphics.Blit(source, tmp3); videoBloomMaterial.SetFloat("_Param2", Threshold); Graphics.Blit(tmp3, tmp1, videoBloomMaterial, 2); RenderTexture.ReleaseTemporary(tmp3); tmp3 = null; } if (LargeAmount != 0.0f) { tmp3 = RenderTexture.GetTemporary(rtW, rtH, 0, RenderTextureFormat.ARGBHalf); tmp3.filterMode = FilterMode.Bilinear; tmp3.wrapMode = TextureWrapMode.Clamp; } BloomBlit(tmp1, tmp2, tmp3, radius1, radius2 >= radius1 ? radius2:radius1); videoBloomMaterial.SetTexture("_MainTex", source); videoBloomMaterial.SetTexture("_MediumBloom", tmp2); videoBloomMaterial.SetTexture("_LargeBloom", tmp3); videoBloomMaterial.SetVector("_Param0", weight); videoBloomMaterial.SetVector("_Param1", tint); Graphics.Blit(source, destination, videoBloomMaterial, BlendMode == BlendingMode.Screen ? 4:3); RenderTexture.ReleaseTemporary(tmp1); RenderTexture.ReleaseTemporary(tmp2); if (tmp3 != null) RenderTexture.ReleaseTemporary(tmp3); } } <|start_filename|>Assets/VJ05/AnalogGlitchController.cs<|end_filename|> using UnityEngine; public class AnalogGlitchController : MonoBehaviour { public Kino.AnalogGlitch target; public AnimationCurve kickCurve1; public AnimationCurve kickCurve2; public float ScanLineJitter { get; set; } public float ColorDrift { get; set; } public float VerticalJump { get; set; } public float HorizontalShake { get; set; } float curveTime = 100; float kickIntensity = 1; public void Kick(float intensity) { kickIntensity = intensity; curveTime = 0; } void Update() { var v1 = kickCurve1.Evaluate(curveTime) * kickIntensity; var v2 = kickCurve2.Evaluate(curveTime) * kickIntensity; var sj = Mathf.Clamp01(v1 + ScanLineJitter); var cd = Mathf.Clamp01(v1 + ColorDrift); var vj = Mathf.Clamp01(v2 + VerticalJump); var hs = Mathf.Clamp01(v2 + HorizontalShake); if (sj > 0 || cd > 0 || vj > 0 || hs > 0) { target.enabled = true; target.scanLineJitter = sj; target.colorDrift = cd; target.verticalJump = vj; target.horizontalShake = hs; } else { target.enabled = false; } curveTime += Time.deltaTime; } } <|start_filename|>Assets/Kvant/Lattice/Shaders/Kernels.shader<|end_filename|> // // GPGPU kernels for Lattice // Shader "Hidden/Kvant/Lattice/Kernels" { Properties { _MainTex ("-", 2D) = ""{} } CGINCLUDE #pragma multi_compile DEPTH1 DEPTH2 DEPTH3 DEPTH4 DEPTH5 #pragma multi_compile _ ENABLE_WARP #include "UnityCG.cginc" #include "ClassicNoise3D.cginc" sampler2D _MainTex; float2 _MainTex_TexelSize; float2 _Extent; float2 _Offset; float _Frequency; float3 _Amplitude; float2 _ClampRange; // Pass 0: Calculates vertex positions float4 frag_position(v2f_img i) : SV_Target { float2 vp = (i.uv.xy - (float2)0.5) * _Extent; float3 nc1 = float3((vp + _Offset) * _Frequency, _Time.x); #if ENABLE_WARP float3 nc2 = nc1 + float3(124.343, 311.591, 0); float3 nc3 = nc1 + float3(273.534, 178.392, 0); #endif float3 np = float3(100000, 100000, 100000); float n1 = pnoise(nc1, np); #if ENABLE_WARP float n2 = pnoise(nc2, np); float n3 = pnoise(nc3, np); #endif #if DEPTH2 || DEPTH3 || DEPTH4 || DEPTH5 n1 += pnoise(nc1 * 2, np * 2) * 0.5; #if ENABLE_WARP n2 += pnoise(nc2 * 2, np * 2) * 0.5; n3 += pnoise(nc3 * 2, np * 2) * 0.5; #endif #endif #if DEPTH3 || DEPTH4 || DEPTH5 n1 += pnoise(nc1 * 4, np * 4) * 0.25; #if ENABLE_WARP n2 += pnoise(nc2 * 4, np * 4) * 0.25; n3 += pnoise(nc3 * 4, np * 4) * 0.25; #endif #endif #if DEPTH4 || DEPTH5 n1 += pnoise(nc1 * 8, np * 8) * 0.125; #if ENABLE_WARP n2 += pnoise(nc1 * 8, np * 8) * 0.125; n3 += pnoise(nc1 * 8, np * 8) * 0.125; #endif #endif #if DEPTH5 n1 += pnoise(nc1 * 16, np * 16) * 0.0625; #if ENABLE_WARP n2 += pnoise(nc1 * 16, np * 16) * 0.0625; n3 += pnoise(nc1 * 16, np * 16) * 0.0625; #endif #endif float3 op = float3(vp.x, 0, vp.y); #if ENABLE_WARP float3 d = float3(n2, n1, n3); #else float3 d = float3(0, n1, 0); #endif op += clamp(d, _ClampRange.x, _ClampRange.y) * _Amplitude; return float4(op, 1); } // Pass 1: Calculates normal vectors for the 1st submesh float4 frag_normal1(v2f_img i) : SV_Target { float2 duv = _MainTex_TexelSize; float3 v1 = tex2D(_MainTex, i.uv + float2(0, 0) * duv).xyz; float3 v2 = tex2D(_MainTex, i.uv + float2(1, 1) * duv).xyz; float3 v3 = tex2D(_MainTex, i.uv + float2(2, 0) * duv).xyz; float3 n = normalize(cross(v2 - v1, v3 - v1)); return float4(n, 0); } // Pass 2: Calculates normal vectors for the 2nd submesh float4 frag_normal2(v2f_img i) : SV_Target { float2 duv = _MainTex_TexelSize; float3 v1 = tex2D(_MainTex, i.uv + float2( 0, 0) * duv).xyz; float3 v2 = tex2D(_MainTex, i.uv + float2(-1, 1) * duv).xyz; float3 v3 = tex2D(_MainTex, i.uv + float2( 1, 1) * duv).xyz; float3 n = normalize(cross(v2 - v1, v3 - v1)); return float4(n, 0); } ENDCG SubShader { Pass { CGPROGRAM #pragma target 3.0 #pragma vertex vert_img #pragma fragment frag_position ENDCG } Pass { CGPROGRAM #pragma target 3.0 #pragma vertex vert_img #pragma fragment frag_normal1 ENDCG } Pass { CGPROGRAM #pragma target 3.0 #pragma vertex vert_img #pragma fragment frag_normal2 ENDCG } } } <|start_filename|>Assets/Furball/FurballRenderer.cs<|end_filename|> // // Geometric furball like thing // using UnityEngine; using UnityEngine.Rendering; using Emgen; [ExecuteInEditMode] public class FurballRenderer : MonoBehaviour { #region Public Properties // Subdivision level [SerializeField, Range(0, 4)] int _subdivision = 2; public int subdivision { get { return _subdivision; } set { _subdivision = Mathf.Clamp(value, 0, 4); } } // Noise amplitude [SerializeField, Header("Noise Parameters")] float _noiseAmplitude = 3; public float noiseAmplitude { get { return _noiseAmplitude; } set { _noiseAmplitude = value; } } // Exponent of noise amplitude [SerializeField] float _noiseExponent = 2.5f; public float noiseExponent { get { return _noiseExponent; } set { _noiseExponent = value; } } // Noise frequency [SerializeField] float _noiseFrequency = 2; public float noiseFrequency { get { return _noiseFrequency; } set { _noiseFrequency = value; } } // Noise speed [SerializeField] float _noiseSpeed = 3; public float noiseSpeed { get { return _noiseSpeed; } set { _noiseSpeed = value; } } // Rendering settings [SerializeField, Header("Rendering")] Material _material; bool _owningMaterial; // whether owning the material public Material sharedMaterial { get { return _material; } set { _material = value; } } public Material material { get { if (!_owningMaterial) { _material = Instantiate<Material>(_material); _owningMaterial = true; } return _material; } set { if (_owningMaterial) Destroy(_material, 0.1f); _material = value; _owningMaterial = false; } } [SerializeField] bool _receiveShadows; [SerializeField] ShadowCastingMode _shadowCastingMode; #endregion #region Private Members Mesh _mesh; int _subdivided = -1; Vector3 _noiseOffset; #endregion #region MonoBehaviour Functions void Update() { if (_subdivided != _subdivision) RebuildMesh(); var noiseDir = new Vector3(1, 0.3f, -0.5f).normalized; _noiseOffset += noiseDir * (Time.deltaTime * _noiseSpeed); var props = new MaterialPropertyBlock(); props.SetVector("_NoiseOffset", _noiseOffset); props.SetFloat("_NoiseFrequency", _noiseFrequency); props.SetFloat("_NoiseAmplitude", _noiseAmplitude); props.SetFloat("_NoiseExponent", _noiseExponent); Graphics.DrawMesh( _mesh, transform.localToWorldMatrix, _material, 0, null, 0, props, _shadowCastingMode, _receiveShadows); } #endregion #region Mesh Builder void RebuildMesh() { if (_mesh) DestroyImmediate(_mesh); // Make an icosphere. IcosphereBuilder ib = new IcosphereBuilder(); for (var i = 0; i < _subdivision; i++) ib.Subdivide(); // Vertex array. var vc = ib.vertexCache; var vertices = new Vector3[vc.triangles.Count * 12]; var colors = new Color[vc.triangles.Count * 12]; // Make a funnel shaped surface for each original triangle. var offs = 0; foreach (var t in vc.triangles) { // Vertices on the original triangle. var v1 = vc.vertices[t.i1]; var v2 = vc.vertices[t.i2]; var v3 = vc.vertices[t.i3]; // Get the center of mass and encode it to a color. var cc = (v1 + v2 + v3) * 0.3333333f; var c = new Color(cc.x, cc.y, cc.z, 1); // Fill the color. for (var i = 0; i < 12; i++) colors[offs + i] = c; // Make each face. vertices[offs++] = v1; vertices[offs++] = v2; vertices[offs++] = v3; vertices[offs++] = Vector3.zero; vertices[offs++] = v2; vertices[offs++] = v1; vertices[offs++] = Vector3.zero; vertices[offs++] = v3; vertices[offs++] = v2; vertices[offs++] = Vector3.zero; vertices[offs++] = v1; vertices[offs++] = v3; } // Index array. Simply enumerates the vertices. var indices = new int[vertices.Length]; for (var i = 0; i < indices.Length; i++) indices[i] = i; // Build a mesh. _mesh = new Mesh(); _mesh.hideFlags = HideFlags.DontSave; _mesh.bounds = new Bounds(Vector3.zero, Vector3.one * 10); _mesh.vertices = vertices; _mesh.colors = colors; _mesh.SetIndices(indices, MeshTopology.Triangles, 0); _mesh.RecalculateNormals(); _subdivided = _subdivision; } #endregion } <|start_filename|>Assets/VJ05/GlobalConfig.cs<|end_filename|> using UnityEngine; public class GlobalConfig : MonoBehaviour { void Start() { if (!Application.isEditor) Cursor.visible = false; } } <|start_filename|>Assets/DeferredAO/Shader/DeferredAO.shader<|end_filename|> // // Deferred AO - G-buffer based SSAO effect // // Copyright (C) 2015 <NAME> // // 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. // Shader "Hidden/DeferredAO" { Properties { _MainTex("-", 2D) = "" {} } CGINCLUDE #include "UnityCG.cginc" #pragma multi_compile _ _RANGE_CHECK #pragma multi_compile _SAMPLE_LOW _SAMPLE_MEDIUM _SAMPLE_HIGH _SAMPLE_OVERKILL sampler2D _MainTex; float2 _MainTex_TexelSize; sampler2D_float _CameraDepthTexture; sampler2D _CameraGBufferTexture2; float4x4 _WorldToCamera; float _Intensity; float _Radius; float _FallOff; #if _SAMPLE_LOW static const int SAMPLE_COUNT = 8; #elif _SAMPLE_MEDIUM static const int SAMPLE_COUNT = 16; #elif _SAMPLE_HIGH static const int SAMPLE_COUNT = 24; #else static const int SAMPLE_COUNT = 80; #endif float nrand(float2 uv, float dx, float dy) { uv += float2(dx, dy + _Time.x); return frac(sin(dot(uv, float2(12.9898, 78.233))) * 43758.5453); } float3 spherical_kernel(float2 uv, float index) { // Uniformaly distributed points // http://mathworld.wolfram.com/SpherePointPicking.html float u = nrand(uv, 0, index) * 2 - 1; float theta = nrand(uv, 1, index) * UNITY_PI * 2; float u2 = sqrt(1 - u * u); float3 v = float3(u2 * cos(theta), u2 * sin(theta), u); // Adjustment for distance distribution. float l = index / SAMPLE_COUNT; return v * lerp(0.1, 1.0, l * l); } half4 frag_ao(v2f_img i) : SV_Target { half4 src = tex2D(_MainTex, i.uv); // Sample a linear depth on the depth buffer. float depth_o = SAMPLE_DEPTH_TEXTURE(_CameraDepthTexture, i.uv); depth_o = LinearEyeDepth(depth_o); // This early-out flow control is not allowed in HLSL. // if (depth_o > _FallOff) return src; // Sample a view-space normal vector on the g-buffer. float3 norm_o = tex2D(_CameraGBufferTexture2, i.uv).xyz * 2 - 1; norm_o = mul((float3x3)_WorldToCamera, norm_o); // Reconstruct the view-space position. float2 p11_22 = float2(unity_CameraProjection._11, unity_CameraProjection._22); float3 pos_o = float3((i.uv * 2 - 1) / p11_22, 1) * depth_o; float3x3 proj = (float3x3)unity_CameraProjection; float occ = 0.0; for (int s = 0; s < SAMPLE_COUNT; s++) { float3 delta = spherical_kernel(i.uv, s); // Wants a sample in normal oriented hemisphere. delta *= (dot(norm_o, delta) >= 0) * 2 - 1; // Sampling point. float3 pos_s = pos_o + delta * _Radius; // Re-project the sampling point. float3 pos_sc = mul(proj, pos_s); float2 uv_s = (pos_sc.xy / pos_s.z + 1) * 0.5; // Sample a linear depth at the sampling point. float depth_s = LinearEyeDepth(SAMPLE_DEPTH_TEXTURE(_CameraDepthTexture, uv_s)); // Occlusion test. float dist = pos_s.z - depth_s; #if _RANGE_CHECK occ += (dist > 0.1) * (dist < _Radius); #else occ += (dist > 0.1); #endif } float falloff = 1.0 - depth_o / _FallOff; occ = saturate(occ * _Intensity * falloff / SAMPLE_COUNT); return half4(lerp(src.rgb, (half3)0.0, occ), src.a); } ENDCG SubShader { Pass { ZTest Always Cull Off ZWrite Off CGPROGRAM #pragma vertex vert_img #pragma fragment frag_ao #pragma target 3.0 ENDCG } } } <|start_filename|>Assets/Kvant/Tunnel/Editor/TunnelEditor.cs<|end_filename|> // // Custom editor for Tunnel // using UnityEngine; using UnityEditor; namespace Kvant { [CanEditMultipleObjects] [CustomEditor(typeof(Tunnel))] public class TunnelEditor : Editor { SerializedProperty _slices; SerializedProperty _stacks; SerializedProperty _radius; SerializedProperty _height; SerializedProperty _offset; SerializedProperty _noiseRepeat; SerializedProperty _noiseFrequency; SerializedProperty _noiseDepth; SerializedProperty _noiseClampMin; SerializedProperty _noiseClampMax; SerializedProperty _noiseElevation; SerializedProperty _noiseWarp; SerializedProperty _material; SerializedProperty _castShadows; SerializedProperty _receiveShadows; SerializedProperty _lineColor; SerializedProperty _debug; static GUIContent _textSlices = new GUIContent("Slices (on equator)"); static GUIContent _textStacks = new GUIContent("Stacks (along Z)"); static GUIContent _textRepeat = new GUIContent("Repeat (on equator)"); static GUIContent _textFrequency = new GUIContent("Frequency (along Z)"); static GUIContent _textDepth = new GUIContent("Depth"); static GUIContent _textClamp = new GUIContent("Clamp"); static GUIContent _textElevation = new GUIContent("Elevation"); static GUIContent _textWarp = new GUIContent("Warp"); void OnEnable() { _slices = serializedObject.FindProperty("_slices"); _stacks = serializedObject.FindProperty("_stacks"); _radius = serializedObject.FindProperty("_radius"); _height = serializedObject.FindProperty("_height"); _offset = serializedObject.FindProperty("_offset"); _noiseRepeat = serializedObject.FindProperty("_noiseRepeat"); _noiseFrequency = serializedObject.FindProperty("_noiseFrequency"); _noiseDepth = serializedObject.FindProperty("_noiseDepth"); _noiseClampMin = serializedObject.FindProperty("_noiseClampMin"); _noiseClampMax = serializedObject.FindProperty("_noiseClampMax"); _noiseElevation = serializedObject.FindProperty("_noiseElevation"); _noiseWarp = serializedObject.FindProperty("_noiseWarp"); _material = serializedObject.FindProperty("_material"); _castShadows = serializedObject.FindProperty("_castShadows"); _receiveShadows = serializedObject.FindProperty("_receiveShadows"); _lineColor = serializedObject.FindProperty("_lineColor"); _debug = serializedObject.FindProperty("_debug"); } public override void OnInspectorGUI() { var instance = target as Tunnel; serializedObject.Update(); EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(_slices, _textSlices); EditorGUILayout.PropertyField(_stacks, _textStacks); if (!_stacks.hasMultipleDifferentValues) { var note = "Allocated: " + instance.stacks; EditorGUILayout.LabelField(" ", note, EditorStyles.miniLabel); } if (EditorGUI.EndChangeCheck()) instance.NotifyConfigChange(); EditorGUILayout.PropertyField(_radius); EditorGUILayout.PropertyField(_height); EditorGUILayout.PropertyField(_offset); EditorGUILayout.Space(); EditorGUILayout.LabelField("Fractal Noise", EditorStyles.boldLabel); EditorGUILayout.PropertyField(_noiseRepeat, _textRepeat); EditorGUILayout.PropertyField(_noiseFrequency, _textFrequency); EditorGUILayout.PropertyField(_noiseDepth, _textDepth); MinMaxSlider(_textClamp, _noiseClampMin, _noiseClampMax, -1.0f, 1.0f); EditorGUILayout.PropertyField(_noiseElevation, _textElevation); EditorGUILayout.PropertyField(_noiseWarp, _textWarp); EditorGUILayout.Space(); EditorGUILayout.PropertyField(_material); EditorGUILayout.PropertyField(_castShadows); EditorGUILayout.PropertyField(_receiveShadows); EditorGUILayout.PropertyField(_lineColor); EditorGUILayout.Space(); EditorGUILayout.PropertyField(_debug); serializedObject.ApplyModifiedProperties(); } void MinMaxSlider( GUIContent label, SerializedProperty propMin, SerializedProperty propMax, float minLimit, float maxLimit) { var min = propMin.floatValue; var max = propMax.floatValue; EditorGUI.BeginChangeCheck(); // Min-max slider. EditorGUILayout.MinMaxSlider(label, ref min, ref max, minLimit, maxLimit); var prevIndent = EditorGUI.indentLevel; EditorGUI.indentLevel = 0; // Float value boxes. var rect = EditorGUILayout.GetControlRect(); rect.x += EditorGUIUtility.labelWidth; rect.width = (rect.width - EditorGUIUtility.labelWidth) / 2 - 2; if (EditorGUIUtility.wideMode) { EditorGUIUtility.labelWidth = 28; min = Mathf.Clamp(EditorGUI.FloatField(rect, "min", min), minLimit, max); rect.x += rect.width + 4; max = Mathf.Clamp(EditorGUI.FloatField(rect, "max", max), min, maxLimit); EditorGUIUtility.labelWidth = 0; } else { min = Mathf.Clamp(EditorGUI.FloatField(rect, min), minLimit, max); rect.x += rect.width + 4; max = Mathf.Clamp(EditorGUI.FloatField(rect, max), min, maxLimit); } EditorGUI.indentLevel = prevIndent; if (EditorGUI.EndChangeCheck()) { propMin.floatValue = min; propMax.floatValue = max; } } } } <|start_filename|>Assets/Kvant/Wall/Shaders/Kernel.shader<|end_filename|> // // GPGPU kernels for Wall // // Position kernel outputs: // .xyz = position // .w = random value (0-1) // // Rotation kernel outputs: // .xyzw = rotation (quaternion) // // Scale kernel outputs: // .xyz = scale factor // .w = random value (0-1) // Shader "Hidden/Kvant/Wall/Kernel" { Properties { _MainTex("-", 2D) = ""{} } CGINCLUDE #include "UnityCG.cginc" #include "ClassicNoise3D.cginc" #pragma multi_compile POSITION_Z POSITION_XYZ POSITION_RANDOM #pragma multi_compile ROTATION_AXIS ROTATION_RANDOM #pragma multi_compile SCALE_UNIFORM SCALE_XYZ sampler2D _MainTex; float2 _ColumnRow; float2 _Extent; float2 _UVOffset; float3 _BaseScale; float2 _RandomScale; // min, max float4 _PositionNoise; // x freq, y freq, amp, time float4 _RotationNoise; // x freq, y freq, amp, time float4 _ScaleNoise; // x freq, y freq, amp, time float3 _RotationAxis; // PRNG function. float nrand(float2 uv, float salt) { uv += float2(salt, 0); return frac(sin(dot(uv, float2(12.9898, 78.233))) * 43758.5453); } // Snap UV coordinate to column*row grid. float2 snap_uv(float2 uv) { return floor(uv * _ColumnRow) / _ColumnRow; } // Quaternion multiplication. // http://mathworld.wolfram.com/Quaternion.html float4 qmul(float4 q1, float4 q2) { return float4( q2.xyz * q1.w + q1.xyz * q2.w + cross(q1.xyz, q2.xyz), q1.w * q2.w - dot(q1.xyz, q2.xyz) ); } // Get a random rotation axis in a deterministic fashion. float3 get_rotation_axis(float2 uv) { // Uniformaly distributed points. // http://mathworld.wolfram.com/SpherePointPicking.html float u = nrand(uv, 0) * 2 - 1; float theta = nrand(uv, 1) * UNITY_PI * 2; float u2 = sqrt(1 - u * u); return float3(u2 * cos(theta), u2 * sin(theta), u); } // Pass 0: Position kernel float4 frag_position(v2f_img i) : SV_Target { // Offset UV float2 uv = snap_uv(i.uv + _UVOffset); // Base position float3 origin = float3((i.uv - 0.5) * _Extent, 0); // << Note: use original UV, not ofsetted UV.. // Noise coordinate float3 nc = float3(uv * _PositionNoise.xy, _PositionNoise.w); // Displacement #if POSITION_Z float3 disp = float3(0, 0, cnoise(nc)); #elif POSITION_XYZ float nx = cnoise(nc + float3(0, 0, 0)); float ny = cnoise(nc + float3(138.2, 0, 0)); float nz = cnoise(nc + float3(0, 138.2, 0)); float3 disp = float3(nx, ny, nz); #else // POSITION_RANDOM float3 disp = get_rotation_axis(uv) * cnoise(nc); #endif disp *= _PositionNoise.z; return float4(origin + disp, nrand(uv, 2)); } // Pass 1: Rotation kernel float4 frag_rotation(v2f_img i) : SV_Target { // Offset UV float2 uv = snap_uv(i.uv + _UVOffset); // Noise coordinate float3 nc = float3(uv * _RotationNoise.xy, _RotationNoise.w); // Angle float angle = cnoise(nc) * _RotationNoise.z; // Rotation axis #if ROTATION_AXIS float3 axis = _RotationAxis; #else // ROTATION_RANDOM float3 axis = get_rotation_axis(uv); #endif return float4(axis * sin(angle), cos(angle)); } // Pass 2: Scale kernel float4 frag_scale(v2f_img i) : SV_Target { // Offset UV float2 uv = snap_uv(i.uv + _UVOffset); // Random scale factor float vari = lerp(_RandomScale.x, _RandomScale.y, nrand(uv, 3)); // Noise coordinate float3 nc = float3(uv * _ScaleNoise.xy, _ScaleNoise.w); // Scale factors for each axis #if SCALE_UNIFORM float3 axes = (float3)cnoise(nc + float3(417.1, 471.2, 0)); #else // SCALE_XYZ float sx = cnoise(nc + float3(417.1, 471.2, 0)); float sy = cnoise(nc + float3(917.1, 471.2, 0)); float sz = cnoise(nc + float3(417.1, 971.2, 0)); float3 axes = float3(sx, sy, sz); #endif axes = 1.0 - _ScaleNoise.z * (axes + 0.7) / 1.4; return float4(_BaseScale * axes * vari, nrand(uv, 4)); } ENDCG SubShader { Pass { CGPROGRAM #pragma target 3.0 #pragma vertex vert_img #pragma fragment frag_position ENDCG } Pass { CGPROGRAM #pragma target 3.0 #pragma vertex vert_img #pragma fragment frag_rotation ENDCG } Pass { CGPROGRAM #pragma target 3.0 #pragma vertex vert_img #pragma fragment frag_scale ENDCG } } } <|start_filename|>Assets/Kino/Glitch/Shader/DigitalGlitch.shader<|end_filename|> // // KinoGlitch - Video glitch effect // // Copyright (C) 2015 <NAME> // // 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. // Shader "Hidden/Kino/Glitch/Digital" { Properties { _MainTex ("-", 2D) = "" {} _NoiseTex ("-", 2D) = "" {} _TrashTex ("-", 2D) = "" {} } CGINCLUDE #include "UnityCG.cginc" sampler2D _MainTex; sampler2D _NoiseTex; sampler2D _TrashTex; float _Intensity; float4 frag(v2f_img i) : SV_Target { float4 glitch = tex2D(_NoiseTex, i.uv); float thresh = 1.001 - _Intensity * 1.001; float w_d = step(thresh, pow(glitch.z, 2.5)); // displacement glitch float w_f = step(thresh, pow(glitch.w, 2.5)); // frame glitch float w_c = step(thresh, pow(glitch.z, 3.5)); // color glitch // Displacement. float2 uv = frac(i.uv + glitch.xy * w_d); float4 source = tex2D(_MainTex, uv); // Mix with trash frame. float3 color = lerp(source, tex2D(_TrashTex, uv), w_f).rgb; // Shuffle color components. float3 neg = saturate(color.grb + (1 - dot(color, 1)) * 0.5); color = lerp(color, neg, w_c); return float4(color, source.a); } ENDCG SubShader { Pass { ZTest Always Cull Off ZWrite Off CGPROGRAM #pragma vertex vert_img #pragma fragment frag #pragma target 3.0 ENDCG } } } <|start_filename|>Assets/Shaders/ImageEffects/Bloom_V2/VideoBloom.shader<|end_filename|> Shader "Hidden/VideoBloom" { Properties { _MainTex ("_MainTex (RGB)", 2D) = "black" _MediumBloom ("-", 2D) = "" {} _LargeBloom ("-", 2D) = "black" {} } CGINCLUDE #include "UnityCG.cginc" sampler2D _MainTex; sampler2D _MediumBloom; sampler2D _LargeBloom; uniform half4 _MainTex_TexelSize; uniform half4 _Param0; uniform half4 _Param1; uniform half _Param2; struct v_blurCoords { float4 pos : SV_POSITION; half2 uv0 : TEXCOORD0; half2 uv1 : TEXCOORD1; half2 uv2 : TEXCOORD2; half2 uv3 : TEXCOORD3; half2 uv4 : TEXCOORD4; }; struct v2f { float4 pos : SV_POSITION; float2 uv : TEXCOORD0; }; uniform float4 _MainTex_ST; v_blurCoords vertBlur(appdata_img v) { v_blurCoords o; o.pos = mul (UNITY_MATRIX_MVP, v.vertex); o.uv0 = v.texcoord; o.uv1 = v.texcoord + _MainTex_TexelSize.xy * _Param0.xy; o.uv2 = v.texcoord - _MainTex_TexelSize.xy * _Param0.xy; o.uv3 = v.texcoord + _MainTex_TexelSize.xy * _Param0.zw; o.uv4 = v.texcoord - _MainTex_TexelSize.xy * _Param0.zw; return o; } half4 fragBlurIter(v_blurCoords i) : COLOR { half4 color = half4(0.182h, 0.182h, 0.182h, 0.182h) * tex2D (_MainTex, i.uv0); color += half4(0.2045h, 0.2045h, 0.2045h, 0.2045h) * (tex2D (_MainTex, i.uv1) + tex2D (_MainTex, i.uv2) + tex2D (_MainTex, i.uv3) + tex2D (_MainTex, i.uv4)); return color; } half4 fragBlurLerpIter(v_blurCoords i) : COLOR { half4 src0 = tex2D (_MainTex, i.uv0); half4 color = half4(0.182h, 0.182h, 0.182h, 0.182h) * src0; color += half4(0.2045h, 0.2045h, 0.2045h, 0.2045h) * (tex2D (_MainTex, i.uv1) + tex2D (_MainTex, i.uv2) + tex2D (_MainTex, i.uv3) + tex2D (_MainTex, i.uv4)); return lerp(src0, color, _Param2); } v2f vert(appdata_img v) { v2f o; o.pos = mul(UNITY_MATRIX_MVP, v.vertex); o.uv = v.texcoord.xy; return o; } half4 fragThresh(v2f i) : SV_Target { half4 color = tex2D(_MainTex, i.uv); half luma = dot(color, half4(0.3h, 0.59h, 0.11h, 0.0h)); return luma < _Param2 ? half4(0.0h, 0.0h, 0.0h, 0.0h):color; } half4 fragAdd(v2f i) : SV_Target { half4 color = tex2D(_MainTex, i.uv); half4 bloom = tex2D(_MediumBloom, i.uv) * _Param1 * _Param0.x; bloom += tex2D(_LargeBloom, i.uv) * _Param1 * _Param0.y; return color + bloom; } half4 fragScreen(v2f i) : SV_Target { half4 color = tex2D(_MainTex, i.uv); half4 bloom = tex2D(_MediumBloom, i.uv) * _Param1 * _Param0.x; bloom += tex2D(_LargeBloom, i.uv) * _Param1 * _Param0.y; half4 mr = color + bloom - color * bloom; return max(color, mr); } ENDCG SubShader { ZTest Always Cull Off ZWrite Off Fog { Mode Off } Lighting Off Blend Off // 0 Pass { CGPROGRAM #pragma vertex vertBlur #pragma fragment fragBlurIter #pragma fragmentoption ARB_precision_hint_fastest ENDCG } // 1 Pass { CGPROGRAM #pragma vertex vertBlur #pragma fragment fragBlurLerpIter #pragma fragmentoption ARB_precision_hint_fastest ENDCG } // 2 Pass { CGPROGRAM #pragma vertex vert #pragma fragment fragThresh #pragma fragmentoption ARB_precision_hint_fastest ENDCG } // 3 Pass { CGPROGRAM #pragma vertex vert #pragma fragment fragAdd #pragma fragmentoption ARB_precision_hint_fastest ENDCG } // 4 Pass { CGPROGRAM #pragma vertex vert #pragma fragment fragScreen #pragma fragmentoption ARB_precision_hint_fastest ENDCG } } FallBack Off } <|start_filename|>Assets/Kvant/Wall/WallScroller.cs<|end_filename|> // // Scroller script for Wall // using UnityEngine; namespace Kvant { [RequireComponent(typeof(Wall))] [AddComponentMenu("Kvant/Wall Scroller")] public class WallScroller : MonoBehaviour { public float yawAngle; public float speed; public float Speed { get { return speed; } set { speed = value; } } void Update() { var r = yawAngle * Mathf.Deg2Rad; var dir = new Vector2(Mathf.Cos(r), Mathf.Sin(r)); GetComponent<Wall>().offset += dir * speed * Time.deltaTime; } } }
keijiro/Furball
<|start_filename|>docs/assets/css/no-scroll.css<|end_filename|> body { overflow-y:hidden; } @media (max-width: 992px) { body { overflow-y:auto; } } <|start_filename|>docs/assets/css/website.css<|end_filename|> .code { color: #86193F; } .nav-item { border-right: solid; border-right-color: #bbb; border-right-width: 1px; } .nav-subsubitem { border: solid; border-color: #bbb; border-width: 1px } .bottom-padding { padding-bottom: 50px; } .navbar-brand { max-height: 187px; } .navbar-brand-img { max-height: 187px; } .link-container h1{ font-weight: 500 !important; text-align: center; } .env-title h2{ font-size: 2em !important; font-weight: 500 !important; } .selection-table-container h2 { text-align: center; font-weight: 500 !important; font-size: 2em !important; } .selection-table-container .card-title { font-weight: 500 !important; font-size: 1em !important; } .api-nav-link { text-align: center; } .navbar-text { font-family:Ubuntu; } .nav-first-item { width: 19vw; min-width: 110px } .nav-link { font-family:Ubuntu; } .selection-container { box-sizing: border-box; display: flex; flex-direction: column; margin-right: 0; } .env-container { box-sizing: border-box; display: flex; flex-direction: column; margin-right: 0; } .docu-container { box-sizing: border-box; display: flex; margin-right: 0; } .doccontainer.container { width: 50vw; /* padding-right: 15px; padding-left: 15px; */ margin-right: auto; margin-left: auto } .home-img { display:block; margin-left: auto; margin-right: auto; border-style: none; margin-bottom: 5%; } .home-img-style { max-height: 465px; height: 40vh; } .nav-submenu { width: 75%; max-height: 287px; display: flex; overflow-y: visible; flex-direction: column; flex-wrap: wrap; padding-inline-start: 0; } .nav-subsubmenu { padding-inline-start: 0px; max-height: 287px; display: flex; overflow-y: visible; flex-direction: column; flex-wrap: wrap; } .api-navbar { padding: 0rem 2rem; overflow-y: auto; z-index: 0 !important; } @media (max-width: 860px) { .env-icon { margin-left: 10px; margin-right: 10px; } .env-title { display: none; } .home-container { margin-top: 10vh; } .api-navbar { padding: 0rem 2rem; visibility: hidden; } .navbar-nav { padding-left: 10px; } .navbar-brand { display: none !important; visibility: hidden; } .navbar-text { left: 40%; padding-left: 8px; } .doccontainer.container { margin-top: 25%; z-index: 0; width: 80vh; } .shorten { height: 100%; } .navbar-site-title { height: 100%; } .markdown-body { margin-top: 15vh; } .selection-content { float:none; box-sizing: border-box; padding: 10px; overflow-x: auto; } .selection-table-container { float: none; padding: 10px; overflow-x: auto; } .docu-info { overflow-y: auto; padding: 10px; overflow-x: auto; } .docu-content { box-sizing: border-box; overflow-y: auto; padding: 10px; overflow-x: auto; } .navbar-nav { position: fixed; left: 0; top: 10vh; margin-top: 0px; } .menu-btn { position: fixed; left: 0; top: 0; width: 10vw; height: 10vh; min-height: 52px; } .navbar-arrow { visibility: hidden; } .link-container { padding-left: 20px; } } .api-navbar-nav { margin-top: 0px!important; background-color: rgba(0, 0, 0, 0)!important; } .navbar-collapse li { list-style: none; position: relative; } .navbar-collapse li li { list-style: none; position: relative; background: #fff; width: 12vw; left: 19vw; } .nav-subitem-1 { top: -89.06px; border: solid; border-color: #bbb; border-width: 1px } .nav-subitem-2 { top: -133.59px; border: solid; border-color: #bbb; border-width: 1px } .nav-subitem-3 { top: -178.12px; border: solid; border-color: #bbb; border-width: 1px } .nav-subitem-4 { border-top: solid; border-bottom: solid; border-color: #bbb; border-width: 1px; top: -222.65px; } .navbar-collapse li li li{ list-style: none; position: relative; background: #fff; left: 100%; top: -45.522px; z-index: 10; } .navbar-collapse ul li:hover { background: #eee; } .navbar-collapse .api-navbar-nav li { background: #fff; } .navbar-collapse ul ul { position: absolute; visibility: hidden; } @media(min-width:860px) { .navbar-collapse ul li:hover ul { visibility: visible; } .navbar-nav { padding-left: 0; } .top-padding { padding-top: 25px; } .side-padding { padding-left: 20vw; padding-right: 20vw; } } .navbar-collapse ul ul ul { position: absolute; visibility: hidden; } .navbar-collapse li:hover ul ul { visibility: hidden; } .navbar-collapse li li:hover ul { visibility: visible; } .api-collapse { -ms-flex-preferred-size: 100%; flex-basis: 100%; -ms-flex-positive: 1; flex-grow: 1; -ms-flex-align: center; align-items: center } .api-collapse li { list-style: none; position: relative; } .navbar-arrow { position: absolute; top: 12px; height: 20px; right: 0; } .icon { float: left; position: absolute; top: 14px; max-width: 17px; max-height: 20px; padding-left: 4px; } .env-icon { float: left; height: 2rem; } .fixed-footer { position: fixed; right: 0; bottom: 0; left: 26px; z-index: 1030; color: white; } .fixed-left { position: fixed; left: 0; top: 0; width: 100%; min-height: 52px; height: 10%; z-index: 1030 } .fixed-right { position: fixed; right: 0; bottom: 0; top: 0; width: 19%; z-index: 1030 } .fixed-margin { left: 20%; } .purple_rectangle { background: #BA90F9; padding-bottom: .5em; } .menu-icon { display: flex; position: fixed; top: max(2.5vh, 13px); left: 1vw; height: max(5vh, 26px); } .menu-btn:hover .collapse { display: flex; } .usage { padding-top: 2%; } .divMenu ul { line-height: 25px; } .divMenu ul ul { position: absolute; visibility: hidden; top: 27px; } .divMenu ul li:hover ul { visibility: visible; } .divMenu a:hover { font-weight: bold; } @media (min-width: 860px) { .home-container { margin-left: 19vw; } .env-icon { padding-top: 5px; margin-right: 10px } .fixed-left { position: fixed; left: 0; bottom: 0; top: 0; width: 19vw; z-index: 1030; height: 100%; } .selection-container { margin-left: 20%; } .docu-container { margin-left: 19vw; } .menu-icon { display: none; } .navbar-nav { margin-top: 0; } .link-container { margin-left: 19vw; } .timeline-container { margin-left: 19vw; } } @media (min-width:1440px) { .nav-first-item { width: 267px; } .home-container { margin-left: 267px; } .fixed-left { position: fixed; left: 0; bottom: 0; top: 0; width: 267px; z-index: 1030 } .fixed-right { position: fixed; right: 0; bottom: 0; top: 0; width: 341px; z-index: 1030 } .fixed-margin { left: 281px; } .navbar-collapse li li { list-style: none; position: relative; background: #fff; left: 267px; width: 200.25px; } .navbar-collapse li li li{ list-style: none; position: relative; background: #fff; left: 200px; width: 200px; top: -45.522px; } .copyright { position: fixed; right: 0; bottom: 0; left: 26px; z-index: 1030; color: white; padding-bottom: 10px; } .selection-container { box-sizing: border-box; display: flex; margin-right: 0; margin-left: 300px; } .link-container { margin-left: 267px; } .timeline-container { margin-left: 189px; } .docu-content { height: 100vh; } .docu-info { height: 100vh; } .selection-content { height: 100vh; } .selection-table-container { height: 100vh; } } @media screen and (max-width: 1440px) and (min-width: 860px) { .docu-content { height: 125vh; } .docu-info { height: 125vh; } .selection-content { height: 125vh; } .selection-table-container { height: 125vh; } } @media screen and (max-height: 600px) and (min-width: 860px) { .copyright { visibility: hidden; } .navbar-nav { overflow-y: auto; overflow-x: hidden; } .navbar-arrow { visibility: hidden; } } @media (max-width: 1440px) { .navbar-collapse li li li{ left: 12vw; } .copyright { visibility: hidden; } .zoom { zoom: .8; } } @media (max-width: 992px) { .env-link { visibility: hidden; } .navbar-collapse li li li{ list-style: none; position: relative; background: #fff; top: -45.522px; width: 45.522px; height: 45.522px; z-index: 10; } .icon { left: 14px; } .icon-anchor { display: block; height: 100%; } .nav-subsubmenu { padding-inline-start: 0px; width: 225px; max-width: 225px; display: flex; overflow-y: visible; flex-direction: row; flex-wrap: wrap; } } @media (max-width: 1615px) and (min-width: 1440px) { .navbar-collapse li li li { left: 200px; } } @media (min-width: 860px) { .env-title-small { display: none; } .env-selector-title { display: none; } .spacer { height: calc(55vh - 425px); } .selection-table-container { width: 50%; overflow-y: auto; padding: 10px; overflow-x: auto; border-left: 3px solid black; } .selection-content { width: 50%; float: left; box-sizing: border-box; overflow-y: auto; padding: 10px; padding-top: 80px; overflow-x: auto; } .docu-info { width: 30%; overflow-y: auto; padding: 10px; padding-top: 40px; overflow-x: auto; float: left; } .docu-content { width:70%; float: left; box-sizing: border-box; overflow-y: auto; padding: 10px; padding-left: 5vw; padding-right: 5vw; overflow-x: auto; border-left: 3px solid black; } } <|start_filename|>docs/_includes/timeline.html<|end_filename|> <!-- About --> <section class="page-section" id="{{ site.data.sitetext.timeline.section | default: "about" }}"> <div class="container"> <div> <div class="row"> <div class="col-lg-12 text-center"> <h2 class="section-heading text-uppercase">{{ site.data.sitetext.timeline.title | markdownify | default: "About" }}</h2> <h3 class="section-subheading text-muted">{{ site.data.sitetext.timeline.text | default: ""}}</h3> </div> </div> <div class="env_table"> {%- for row in site.data.sitetext.timeline.rows -%} <div class="env_row"> {%- for event in row -%} <div class="img_entry gallery_entry env_entry"> <a href="{{ event.link }}"> <img src="{{ event.image }}" alt="Card image"> </a> </div> {% endfor %} </div> <div class="env_row"> {%- for event in row -%} <div class="descrip_entry gallery_entry"> <div><h4 class="card-title horizontal_center"> {{ event.title }} </h4></div> <p class="card-title horizontal_center"> {{ event.desc }} </p> {% if event.url %}<a href="{{event.url}}">{{event.url}}</a>{% endif %} </div> {% endfor %} </div> {% endfor %} </div> </div> </div> </section> <!-- End About -->
RedTachyon/PettingZoo
<|start_filename|>haxelib.json<|end_filename|> { "name": "ase", "url": "https://github.com/miriti/ase", "license": "MIT", "tags": ["aseprite", "ase", "format", "pixelart", "gamedev"], "description": "Aseprite file format reader/writer", "version": "2.1.0", "classPath": "src", "releasenote": "Bugfixes and minor updates", "contributors": ["miriti", "AustinEast"], "dependencies": {} } <|start_filename|>documentation/index.js<|end_filename|> function createCookie(name, value) { localStorage.setItem(name, value); } function readCookie(name) { return localStorage.getItem(name); } function isDarkTheme() { return document.querySelector("html").classList.contains("dark-theme"); } function toggleTheme() { const htmlTag = document.querySelector("html"); let isDark = isDarkTheme(); if (isDark) { htmlTag.classList.remove("dark-theme"); } else { htmlTag.classList.add("dark-theme"); } isDark = isDarkTheme(); localStorage.theme = isDark ? "dark" : "light"; } function toggleInherited(el) { var toggle = $(el).closest(".toggle"); toggle.toggleClass("toggle-on"); if (toggle.hasClass("toggle-on")) { $("i", toggle).removeClass("fa-folder").addClass("fa-folder-open"); } else { $("i", toggle).addClass("fa-folder").removeClass("fa-folder-open"); } return false; } function toggleCollapsed(el) { var toggle = $(el).closest(".expando"); toggle.toggleClass("expanded"); if (toggle.hasClass("expanded")) { $(toggle).find("i").first().removeClass("fa-folder").addClass("fa-folder-open"); } else { $(toggle).find("i").first().addClass("fa-folder").removeClass("fa-folder-open"); } updateTreeState(); return false; } function updateTreeState() { var states = []; $("#nav .expando").each(function (i, e) { states.push($(e).hasClass("expanded") ? 1 : 0); }); var treeState = JSON.stringify(states); createCookie("treeState", treeState); } function setPlatform(platform) { createCookie("platform", platform); $("#select-platform").val(platform); var styles = ".platform { display:none }"; var platforms = dox.platforms; if (platform == "flash" || platform == "js") { styles += ".package-sys { display:none; } "; } for (var i = 0; i < platforms.length; i++) { var p = platforms[i]; if (platform == "sys") { if (p != "flash" && p != "js") { styles += ".platform-" + p + " { display:inherit } "; } } else { if (platform == "all" || p == platform) { styles += ".platform-" + p + " { display:inherit } "; } } } if (platform != "flash" && platform != "js") { styles += ".platform-sys { display:inherit } "; } $("#dynamicStylesheet").text(styles); } $(document).ready(function () { $("#nav").html(navContent); var treeState = readCookie("treeState"); $("#nav .expando").each(function (i, e) { $("i", e).first().addClass("fa-folder").removeClass("fa-folder-open"); }); $(".treeLink").each(function () { this.href = this.href.replace("::rootPath::", dox.rootPath); }); if (treeState != null) { var states = JSON.parse(treeState); $("#nav .expando").each(function (i, e) { if (states[i]) { $(e).addClass("expanded"); $("i", e).first().removeClass("fa-folder").addClass("fa-folder-open"); } }); } $("head").append("<style id='dynamicStylesheet'></style>"); setPlatform(readCookie("platform") == null ? "all" : readCookie("platform")); $("#search").on("input", function (e) { searchQuery(e.target.value); }); $(document).bind("keyup keydown", function (e) { if (e.ctrlKey && e.keyCode == 80) { // ctrl + p $("#search").focus(); return false; } return true; }); function getItems() { return $("#search-results-list a").toArray(); } $("#search").bind("keyup", function (e) { switch (e.keyCode) { case 27: // escape searchQuery(""); $("#search").val("") $("#search").blur(); return false; case 13: // enter var items = getItems(); for (i = 0; i < items.length; i++) { var item = $(items[i]); if (item.hasClass("selected")) { window.location = items[i].href; break; } } return false; } }); $("#search").bind("keydown", function (e) { function mod(a, b) { var r = a % b; return r < 0 ? r + b : r; } function changeSelection(amount) { var previousSelection = null; var items = getItems(); for (i = 0; i < items.length; i++) { var item = $(items[i]); if (item.hasClass("selected")) { item.removeClass("selected"); previousSelection = i; break; } } var newSelection = mod(previousSelection + amount, items.length); $(items[newSelection]).addClass("selected"); items[newSelection].scrollIntoView(false); } switch (e.keyCode) { case 38: // up changeSelection(-1); return false; case 40: // down changeSelection(1); return false; case 13: // enter return false; } }); $("#select-platform").selectpicker().on("change", function (e) { var value = $(":selected", this).val(); setPlatform(value); }); $("#nav a").each(function () { if (this.href == location.href) { $(this.parentElement).addClass("active"); } }); $("a.expand-button").click(function (e) { var container = $(this).parent().next(); container.toggle(); $("i", this).removeClass("fa-folder-open") .removeClass("fa-folder") .addClass(container.is(":visible") ? "fa-folder-open" : "fa-folder"); return false; }); // Because there is no CSS parent selector $("code.prettyprint").parents("pre").addClass("example"); }); function searchQuery(query) { $("#searchForm").removeAttr("action"); query = query.replace(/[&<>"']/g, ""); if (!query || query.length < 2) { $("#nav").removeClass("searching"); $("#nav li").each(function (index, element) { var e = $(element); e.css("display", ""); }); $("#nav ul:first-child").css("display", "block"); $("#search-results-list").css("display", "none"); return; } var queryParts = query.toLowerCase().split(" "); var listItems = []; var bestMatch = 200; $("#nav").addClass("searching"); $("#nav ul:first-child").css("display", "none"); $("#nav li").each(function (index, element) { var e = $(element); if (!e.hasClass("expando")) { var content = e.attr("data_path"); var score = searchMatch(content, queryParts); if (score >= 0) { if (score < bestMatch) { var url = dox.rootPath + e.attr("data_path").split(".").join("/") + ".html"; $("#searchForm").attr("action", url); // best match will be form action bestMatch = score; } var elLink = $("a", element); // highlight matched parts var elLinkContent = elLink.text().replace(new RegExp("(" + queryParts.join("|").split(".").join("|") + ")", "ig"), "<strong>$1</strong>"); var liStyle = (score == 0) ? ("font-weight:bold") : ""; listItems.push({ score: score, item: "<li style='" + liStyle + "'><a href='" + elLink.attr("href") + "'>" + elLinkContent + "</a></li>" }); } } }); if ($("#search-results-list").length == 0) { // append to nav $("#nav").parent().append("<ul id='search-results-list' class='nav nav-list'></ul>"); } listItems.sort(function (x, y) { return x.score - y.score; }); // put in order $("#search-results-list").css("display", "block").html(listItems.map(function (x) { return x.item; }).join("")); // pre-select the first item $("#search-results-list a").removeClass("selected"); $("#search-results-list a:first").addClass("selected"); } function match(textParts, query) { var queryParts = query.split("."); if (queryParts.length == 1) { var queryPart = queryParts[0]; for (var i = 0; i < textParts.length; ++i) { var textPart = textParts[i]; if (textPart.indexOf(queryPart) > -1) { // We don't want to match the same part twice, so let's remove it textParts[i] = textParts[i].split(queryPart).join(""); return textPart.length - queryPart.length; } } } else { var offset = -1; outer: while (true) { ++offset; if (queryParts.length + offset > textParts.length) { return -1; } var scoreSum = 0; for (var i = 0; i < queryParts.length; ++i) { var queryPart = queryParts[i]; var textPart = textParts[i + offset]; var index = textPart.indexOf(queryPart); if (index != 0) { continue outer; } scoreSum += textPart.length - queryPart.length; } return scoreSum; } } } function searchMatch(text, queryParts) { text = text.toLowerCase(); var textParts = text.split("."); var scoreSum = 0; for (var i = 0; i < queryParts.length; ++i) { var score = match(textParts, queryParts[i]); if (score == -1) { return -1; } scoreSum += score + text.length; } return scoreSum; } function errorSearch() { var errorURL = ""; if (!!window.location.pathname) { errorURL = window.location.pathname; } else if (!!window.location.href) { errorURL = window.location.href; } if (!!errorURL) { var searchTerm = errorURL.split("/").pop(); if (searchTerm.indexOf(".html") > -1) { searchTerm = searchTerm.split(".html").join(""); } if (!!searchTerm) { // update filter with search term $("#search").val(searchTerm); searchQuery(searchTerm); } } } <|start_filename|>documentation/dark-mode.css<|end_filename|> #theme-toggle:focus { outline: none; } .dark-theme { background-color: #111 !important; color: #ccc; color-scheme: dark; } .dark-theme body { background-color: #111 !important; color: #ccc; } .dark-theme .navbar-inner { background-color: #222 !important; } .dark-theme .brand { color: #CCC !important; } .dark-theme .well { background-color: #222; border: 1px solid #222; } .dark-theme .input-append .add-on, .dark-theme .input-prepend .add-on { background-color: #333; border: 1px solid #333; padding: 3px 5px; text-shadow: 0 0 0 #000; } .dark-theme h1 { color: #ccc; } .dark-theme a { color: #0087ff; } .dark-theme a:hover, .dark-theme a:focus { color: #00b7ff; } .dark-theme input, .dark-theme textarea { background-color: #151515; border: 1px solid #333; transition: none; } .dark-theme .btn-group.open .btn.dropdown-toggle { background-color: #202020; } .dark-theme .dropdown-menu { background-color: #111; } .dark-theme .dropdown-menu>li>a { color: #EEE; } .dark-theme .dropdown-menu>li>a:hover, .dark-theme .dropdown-menu>li>a:focus, .dark-theme .dropdown-submenu:hover>a, .dark-theme .dropdown-submenu:focus>a { color: #EEE; background-color: #2f2f2f; background-image: linear-gradient(to bottom, #262626, #2f2f2f); } .dark-theme .btn:focus, .dark-theme .btn:hover { background-position: 0 0; } .dark-theme .nav>li>a:hover, .dark-theme .nav>li>a:focus { background-color: #333; } .dark-theme .nav-list>.active>a { background-color: #444; } .dark-theme .nav-list>.active>a.treeLink, .dark-theme .nav-list>.active>a.treeLink:hover, .dark-theme .nav-list>.active>a.treeLink:focus { background: #269; } .dark-theme .btn { color: #d5d5d5; text-shadow: 0 1px 1px rgba(0, 0, 0, 0.75); background-color: #313131; background-image: linear-gradient(to bottom, #313131, #282828); border: 1px solid #424141; border-bottom-color: #393939; box-shadow: none; } .dark-theme .btn { color: #d5d5d5; text-shadow: 0 1px 1px rgba(0, 0, 0, 0.75); background-color: #313131; background-image: linear-gradient(to bottom, #313131, #282828); border: 1px solid #424141; border-bottom-color: rgb(66, 65, 65); border-bottom-color: #393939; box-shadow: none; } .dark-theme .btn:focus, .dark-theme .btn:hover { color: #fff; text-decoration: none; } .dark-theme .btn.active, .dark-theme .btn:active { background-image: none; box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125); } .dark-theme .btn.disabled, .dark-theme .btn[disabled] { cursor: not-allowed; opacity: 0.65; box-shadow: none; border-color: #393939; } .dark-theme .btn:focus { color: #d5d5d5; background-color: #313131; border-color: #424141; } .dark-theme .btn:active:hover, .dark-theme .btn:focus:hover { color: #fff; background-color: #313131; border-color: #393939; } .dark-theme a.btn.disabled { pointer-events: none; } .dark-theme .section.site-footer { background: #111 !important; } .dark-theme .copyright>p { color: #CCC !important; } .dark-theme .table th, .dark-theme .table td { border-bottom: 1px solid #222; } .dark-theme .table .fa { color: #222; margin-right: 5px; } .dark-theme .alert, .dark-theme .alert h4 { color: #ffc96c; } .dark-theme .availability { color: #69b; } .dark-theme .section-availability { color: #69b; } .dark-theme .alert { text-shadow: 0 1px 0 rgba(0, 0, 0, 0.5); } .dark-theme .alert { text-shadow: 0 1px 0 rgba(0, 0, 0, 0.5); background-color: #332b00; border: none; } .dark-theme hr { border-top: none; border-bottom: 1px solid #222; } .dark-theme .page-header { border-bottom: 1px solid #222; } .dark-theme .section { border-bottom: 1px solid #222; } .dark-theme .field+.field { border-top: 1px solid #222; } .dark-theme code { color: #ddd; background-color: #111; border: 1px solid #222; } .dark-theme pre { background-color: #222; border: 1px solid #333; } .dark-theme .example code { color: #ddd; background-color: transparent; border: none; } .dark-theme pre code { background-color: transparent; } .dark-theme pre.example::before { color: #DDD; background: #191919; } .dark-theme h3 code { box-shadow: 0 0 15px rgb(20, 20, 20); } .dark-theme .label, .dark-theme .badge { color: #DDD; background-color: #404040; } .dark-theme .label.label-meta { background: #333379; } .dark-theme code .identifier { color: #eff; } .dark-theme table.params { border-left: 5px solid #222; margin-left: 20px; } .dark-theme .table-bordered { border: 1px solid #222; } .dark-theme table.params th { background: #111; } .dark-theme .table-bordered th, .dark-theme .table-bordered td { border-left: 1px solid #222; } .dark-theme .indent { border-left: 5px solid #222; } /* Types without links */ .dark-theme code .type { color: #29e; } /* dark code examples (from try-haxe) */ .dark-theme code, .dark-theme pre { color: #DDD; } .dark-theme code a { color: #29e } .dark-theme pre .type { color: #DECB6B } .dark-theme pre .kwd { color: #C792EA } .dark-theme pre .val { color: #FF5370 } .dark-theme div.pre .str, .dark-theme pre .str, .dark-theme pre .str .kwd, .dark-theme pre .str .type, .dark-theme pre .str .val { color: #C3E88D } .dark-theme pre .cmt, .dark-theme pre .cmt .kwd, .dark-theme pre .cmt .str, .dark-theme pre .cmt .type, .dark-theme pre .cmt .val { color: #545454 } .dark-theme .last-modified { color: #666 }
miriti/ase
<|start_filename|>fido.js<|end_filename|> const base64url = require('base64url'); const cbor = require('cbor'); const uuid = require('uuid-parse'); const jwkToPem = require('jwk-to-pem'); const jwt = require('jsonwebtoken'); const crypto = require('crypto'); const url = require('url'); const storage = require('./storage.js'); const hostname = process.env.HOSTNAME || "localhost"; const jwt_secret = process.env.JWT_SECRET || "defaultsecret"; const fido = {}; /** * Gets an opaque challenge for the client. * Internally, this challenge is a JWT with a timeout. * @returns {string} challenge */ fido.getChallenge = () => { return jwt.sign({}, jwt_secret, { expiresIn: 120 * 1000 }); }; /** * Creates a FIDO credential and stores it * @param {any} attestation AuthenticatorAttestationResponse received from client */ fido.makeCredential = async (attestation) => { //https://w3c.github.io/webauthn/#registering-a-new-credential if (!attestation.id) throw new Error("id is missing"); if (!attestation.attestationObject) throw new Error("attestationObject is missing") if (!attestation.clientDataJSON) throw new Error("clientDataJSON is missing"); //Step 1-2: Let C be the parsed the client data claimed as collected during //the credential creation let C; try { C = JSON.parse(attestation.clientDataJSON); } catch (e) { throw new Error("clientDataJSON could not be parsed"); } //Step 3-6: Verify client data validateClientData(C, "webauthn.create"); //Step 7: Compute the hash of response.clientDataJSON using SHA-256. const clientDataHash = sha256(attestation.clientDataJSON); //Step 8: Perform CBOR decoding on the attestationObject let attestationObject; try { attestationObject = cbor.decodeFirstSync(Buffer.from(attestation.attestationObject, 'base64')); } catch (e) { throw new Error("attestationObject could not be decoded"); } //Step 8.1: Parse authData data inside the attestationObject const authenticatorData = parseAuthenticatorData(attestationObject.authData); //Step 8.2: authenticatorData should contain attestedCredentialData if (!authenticatorData.attestedCredentialData) throw new Exception("Did not see AD flag in authenticatorData"); //Step 9: Verify that the RP ID hash in authData is indeed the SHA-256 hash //of the RP ID expected by the RP. if (!authenticatorData.rpIdHash.equals(sha256(hostname))) { throw new Error("RPID hash does not match expected value: sha256(" + rpId + ")"); } //Step 10: Verify that the User Present bit of the flags in authData is set if ((authenticatorData.flags & 0b00000001) == 0) { throw new Error("User Present bit was not set."); } //Step 11: Verify that the User Verified bit of the flags in authData is set if ((authenticatorData.flags & 0b00000100) == 0) { throw new Error("User Verified bit was not set."); } //Steps 12-19 are skipped because this is a sample app. //Store the credential const credential = await storage.Credentials.create({ id: authenticatorData.attestedCredentialData.credentialId.toString('base64'), publicKeyJwk: authenticatorData.attestedCredentialData.publicKeyJwk, signCount: authenticatorData.signCount }); return credential; }; /** * Verifies a FIDO assertion * @param {any} assertion AuthenticatorAssertionResponse received from client * @return {any} credential object */ fido.verifyAssertion = async (assertion) => { // https://w3c.github.io/webauthn/#verifying-assertion // Step 1 and 2 are skipped because this is a sample app // Step 3: Using credential’s id attribute look up the corresponding // credential public key. let credential = await storage.Credentials.findOne({ id: assertion.id }); if (!credential) { throw new Error("Could not find credential with that ID"); } const publicKey = credential.publicKeyJwk; if (!publicKey) throw new Error("Could not read stored credential public key"); // Step 4: Let cData, authData and sig denote the value of credential’s // response's clientDataJSON, authenticatorData, and signature respectively const cData = assertion.clientDataJSON; const authData = Buffer.from(assertion.authenticatorData, 'base64'); const sig = Buffer.from(assertion.signature, 'base64'); // Step 5 and 6: Let C be the decoded client data claimed by the signature. let C; try { C = JSON.parse(cData); } catch (e) { throw new Error("clientDataJSON could not be parsed"); } //Step 7-10: Verify client data validateClientData(C, "webauthn.get"); //Parse authenticator data used for the next few steps const authenticatorData = parseAuthenticatorData(authData); //Step 11: Verify that the rpIdHash in authData is the SHA-256 hash of the //RP ID expected by the Relying Party. if (!authenticatorData.rpIdHash.equals(sha256(hostname))) { throw new Error("RPID hash does not match expected value: sha256(" + rpId + ")"); } //Step 12: Verify that the User Present bit of the flags in authData is set if ((authenticatorData.flags & 0b00000001) == 0) { throw new Error("User Present bit was not set."); } //Step 13: Verify that the User Verified bit of the flags in authData is set if ((authenticatorData.flags & 0b00000100) == 0) { throw new Error("User Verified bit was not set."); } //Step 14: Verify that the values of the client extension outputs in //clientExtensionResults and the authenticator extension outputs in the //extensions in authData are as expected if (authenticatorData.extensionData) { //We didn't request any extensions. If extensionData is defined, fail. throw new Error("Received unexpected extension data"); } //Step 15: Let hash be the result of computing a hash over the cData using //SHA-256. const hash = sha256(cData); //Step 16: Using the credential public key looked up in step 3, verify //that sig is a valid signature over the binary concatenation of authData //and hash. const verify = (publicKey.kty === "RSA") ? crypto.createVerify('RSA-SHA256') : crypto.createVerify('sha256'); verify.update(authData); verify.update(hash); if (!verify.verify(jwkToPem(publicKey), sig)) throw new Error("Could not verify signature"); //Step 17: verify signCount if (authenticatorData.signCount != 0 && authenticatorData.signCount < credential.signCount) { throw new Error("Received signCount of " + authenticatorData.signCount + " expected signCount > " + credential.signCount); } //Update signCount credential = await storage.Credentials.findOneAndUpdate({ id: credential.id }, { signCount: authenticatorData.signCount }, { new: true }); //Return credential object that was verified return credential; }; /** * Parses authData buffer and returns an authenticator data object * @param {Buffer} authData * @returns {AuthenticatorData} Parsed AuthenticatorData object * @typedef {Object} AuthenticatorData * @property {Buffer} rpIdHash * @property {number} flags * @property {number} signCount * @property {AttestedCredentialData} attestedCredentialData * @property {string} extensionData * @typedef {Object} AttestedCredentialData * @property {string} aaguid * @property {any} publicKeyJwk * @property {string} credentialId * @property {number} credentialIdLength */ const parseAuthenticatorData = authData => { try { const authenticatorData = {}; authenticatorData.rpIdHash = authData.slice(0, 32); authenticatorData.flags = authData[32]; authenticatorData.signCount = (authData[33] << 24) | (authData[34] << 16) | (authData[35] << 8) | (authData[36]); if (authenticatorData.flags & 64) { const attestedCredentialData = {}; attestedCredentialData.aaguid = uuid.unparse(authData.slice(37, 53)).toUpperCase(); attestedCredentialData.credentialIdLength = (authData[53] << 8) | authData[54]; attestedCredentialData.credentialId = authData.slice(55, 55 + attestedCredentialData.credentialIdLength); //Public key is the first CBOR element of the remaining buffer const publicKeyCoseBuffer = authData.slice(55 + attestedCredentialData.credentialIdLength, authData.length); //convert public key to JWK for storage attestedCredentialData.publicKeyJwk = coseToJwk(publicKeyCoseBuffer); authenticatorData.attestedCredentialData = attestedCredentialData; } if (authenticatorData.flags & 128) { //has extension data let extensionDataCbor; if (authenticatorData.attestedCredentialData) { //if we have attesttestedCredentialData, then extension data is //the second element extensionDataCbor = cbor.decodeAllSync(authData.slice(55 + authenticatorData.attestedCredentialData.credentialIdLength, authData.length)); extensionDataCbor = extensionDataCbor[1]; } else { //Else it's the first element extensionDataCbor = cbor.decodeFirstSync(authData.slice(37, authData.length)); } authenticatorData.extensionData = cbor.encode(extensionDataCbor).toString('base64'); } return authenticatorData; } catch (e) { throw new Error("Authenticator Data could not be parsed") } } /** * Validates CollectedClientData * @param {any} clientData JSON parsed client data object received from client * @param {string} type Operation type: webauthn.create or webauthn.get */ const validateClientData = (clientData, type) => { if (clientData.type !== type) throw new Error("collectedClientData type was expected to be " + type); let origin; try { origin = url.parse(clientData.origin); } catch (e) { throw new Error("Invalid origin in collectedClientData"); } if (origin.hostname !== hostname) throw new Error("Invalid origin in collectedClientData. Expected hostname " + hostname); if (hostname !== "localhost" && origin.protocol !== "https:") throw new Error("Invalid origin in collectedClientData. Expected HTTPS protocol."); let decodedChallenge; try { decodedChallenge = jwt.verify(base64url.decode(clientData.challenge), jwt_secret); } catch (err) { throw new Error("Invalid challenge in collectedClientData"); } }; /** * Converts a COSE key to a JWK * @param {Buffer} cose Buffer containing COSE key data * @returns {any} JWK object */ const coseToJwk = cose => { try { let publicKeyJwk = {}; const publicKeyCbor = cbor.decodeFirstSync(cose); if (publicKeyCbor.get(3) == -7) { publicKeyJwk = { kty: "EC", crv: "P-256", x: publicKeyCbor.get(-2).toString('base64'), y: publicKeyCbor.get(-3).toString('base64') } } else if (publicKeyCbor.get(3) == -257) { publicKeyJwk = { kty: "RSA", n: publicKeyCbor.get(-1).toString('base64'), e: publicKeyCbor.get(-2).toString('base64') } } else { throw new Error("Unknown public key algorithm"); } return publicKeyJwk; } catch (e) { throw new Error("Could not decode COSE Key"); } } /** * Evaluates the sha256 hash of a buffer * @param {Buffer} data * @returns sha256 of the input data */ const sha256 = data => { const hash = crypto.createHash('sha256'); hash.update(data); return hash.digest(); } module.exports = fido; <|start_filename|>app.js<|end_filename|> const express = require("express"); const app = express(); const fido = require('./fido.js'); const bodyParser = require('body-parser'); const enforce = require('express-sslify'); if (process.env.ENFORCE_SSL_HEROKU === "true") { app.use(enforce.HTTPS({ trustProtoHeader: true })); } else if (process.env.ENFORCE_SSL_AZURE === "true") { app.use(enforce.HTTPS({ trustAzureHeader: true })); } app.use(express.static('public')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.get('/challenge', async (req, res) => { try { const challenge = await fido.getChallenge(); res.json({ result: challenge }); } catch (e) { res.json({ error: e.message }); }; }); app.put('/credentials', async (req, res) => { try { const credential = await fido.makeCredential(req.body); res.json({ result: credential }); } catch (e) { res.json({ error: e.message }); } }); app.put('/assertion', async (req, res) => { try { const credential = await fido.verifyAssertion(req.body); res.json({ result: credential }); } catch (e) { res.json({ error: e.message }); } }); app.listen(process.env.PORT || 3000, () => console.log('App launched.'));
mkkhedawat/webauthnsample
<|start_filename|>generators/handlebars/templates/gulpfile.js<|end_filename|> // definition of Handlebars loader const loaderConfig = { test: /\.hbs/, loader: 'handlebars-loader' }; // Merge custom loader to web pack configuration build.configureWebpack.mergeConfig({ additionalConfiguration: (generatedConfiguration) => { generatedConfiguration.module.rules.push(loaderConfig); return generatedConfiguration; } }); // register custom watch for hbbs.JS files // copy of '.hba' files will be handled by 'copy-static-assets.json' gulp.watch('./src/**/*.hbs', event => { // copy empty index.ts onto itself to launch build procees gulp.src('./src/index.ts') .pipe(gulp.dest('./src/')); }); <|start_filename|>generators/reactjs.plus/index.js<|end_filename|> "use strict"; // Base Yeoman generator const Generator = require('yeoman-generator'); // filesystem const fs = require('fs'); // importing utilities const util = require('../../lib/util.js'); // Information injected in the readme file const readmeInfo = { libraryName: '', // Placeholder for project name techStack: 'This project uses [React](https://reactjs.org).' }; module.exports = class extends Generator { constructor(args, opts) { super(args, opts); } // Initialisation geenerator initializing() { } // Prompt for user input for Custom Generator prompting() { } // adds additonal editor support in this case CSS Comb configuring() { } writing() {} install() { // include JEST testing if requestd if (this.options.testFramework !== undefined && this.options.testFramework.indexOf('jest') !== -1) { let reactVersion = util.detectReactVersion(this); // add all package depenedencies configured in addonConfig.json. this._addPackageDependencies(reactVersion); } // inject custom tasks to gulpfile this._injectToGulpFile(); // Updated Readme info util.updateReadmeFile(this, readmeInfo); // run installation util.runInstall(this); } // Run installer normally time to say goodbye // If yarn is installed yarn will be used end() { } _deployFiles() { } _addExternals() { } _addPackageDependencies(reactVersion) { if (fs.existsSync(this.destinationPath('package.json'))) { // request the default package file let config; try { config = JSON.parse(fs.readFileSync( this.destinationPath('package.json') )); } catch (error) { throw error; } // request current addon configuration let addonConfig; try { addonConfig = JSON.parse( fs.readFileSync( this.templatePath('addonConfig.json') ) ) } catch (err) { throw err; } // select the requested libraried let requestedLibraries = [reactVersion]; // declare new package config file let newPkgConfig; try { newPkgConfig = util.mergeAddons(addonConfig, requestedLibraries, config); } catch (error) { throw error } // if content could be added to the new package.json write it if (newPkgConfig !== undefined && newPkgConfig !== null) { fs.writeFileSync( this.destinationPath('package.json'), JSON.stringify(newPkgConfig, null, 2) ); } else { throw 'Updated package.json file is invalid.'; } } } _injectToGulpFile() { let targetGulpFile = this.destinationPath('gulpfile.js'); if (fs.existsSync(targetGulpFile)) { let coreGulpTemplate = this.templatePath('../../../app/templates/gulpfile.js'); let customGulpTemplate = this.templatePath('./gulpfile.js'); try { util.composeGulpFile(coreGulpTemplate, customGulpTemplate, targetGulpFile, this.options); } catch (error) { this.log(error); } } } }
Laul0/generator-spfx
<|start_filename|>lib/convert.js<|end_filename|> var _ = require('lodash'), Helpers = require('./helpers.js'), Swagger2OpenAPI = require('swagger2openapi'), OpenAPI2Postman = require('openapi-to-postmanv2'), Converter = null, fs = require('fs'); Converter = { // Static Props: collection: null, // will hold the V2 collection object // takes in a swagger2 JSON object // returns a V2 collection JSON object convert: function (input, options, callback) { options = _.assign({}, options); let definedOptions = _.keyBy(Converter.getOptions(), 'id'); // set default options for (let id in definedOptions) { if (definedOptions.hasOwnProperty(id)) { // set the default value to that option if the user has not defined if (options[id] === undefined) { options[id] = definedOptions[id].default; continue; } // set the default value if the type is unknown switch (definedOptions[id].type) { case 'boolean': if (typeof options[id] !== definedOptions[id].type) { options[id] = definedOptions[id].default; } break; case 'enum': if (!definedOptions[id].availableOptions.includes(options[id])) { options[id] = definedOptions[id].default; } break; default: options[id] = definedOptions[id].default; } } } // We can't expose this option to the user options.schemaFaker = true; var parseResult = Helpers.parse(input); if (!parseResult.result) { return callback(new Error(parseResult.reason || 'Invalid input')); } try { return Swagger2OpenAPI.convertObj(parseResult.swagger, { fatal: false, patch: true, anchors: true, warnOnly: true }, function(err, oas3Wrapper) { if (err) { return callback(err); } return OpenAPI2Postman.convert({ type: 'json', data: oas3Wrapper.openapi }, options, (error, result) => { if (error) { return callback('Error importing Swagger 2.0 spec'); } return callback(null, result); }); }); } catch (e) { return callback(e); } }, getOptions: function() { return [ { name: 'Naming requests', id: 'requestNameSource', type: 'enum', default: 'Fallback', availableOptions: ['URL', 'Fallback'], description: 'Determines how the requests inside the generated collection will be named.' + ' If “Fallback” is selected, the request will be named after one of the following schema' + ' values: `description`, `operationid`, `url`.', external: true }, { name: 'Set indent character', id: 'indentCharacter', type: 'enum', default: 'Space', availableOptions: ['Space', 'Tab'], description: 'Option for setting indentation character', external: true }, { name: 'Collapse redundant folders', id: 'collapseFolders', type: 'boolean', default: true, description: 'Importing will collapse all folders that have only one child element and lack ' + 'persistent folder-level data.', external: true }, { name: 'Optimize conversion', id: 'optimizeConversion', type: 'boolean', default: true, description: 'Optimizes conversion for large specification, disabling this option might affect' + ' the performance of conversion.', external: true }, { name: 'Request parameter generation', id: 'requestParametersResolution', type: 'enum', default: 'Schema', availableOptions: ['Example', 'Schema'], description: 'Select whether to generate the request parameters based on the' + ' [schema](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#schemaObject) or the' + ' [example](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#exampleObject)' + ' in the schema.', external: true }, { name: 'Response parameter generation', id: 'exampleParametersResolution', type: 'enum', default: 'Example', availableOptions: ['Example', 'Schema'], description: 'Select whether to generate the response parameters based on the' + ' [schema](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#schemaObject) or the' + ' [example](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#exampleObject)' + ' in the schema.', external: true }, { name: 'Folder organization', id: 'folderStrategy', type: 'enum', default: 'Paths', availableOptions: ['Paths', 'Tags'], description: 'Select whether to create folders according to the spec’s paths or tags.', external: true }, { name: 'Include auth info in example requests', id: 'includeAuthInfoInExample', type: 'boolean', default: true, description: 'Select whether to include authentication parameters in the example request', external: true } ]; }, getMetaData: function (input, cb) { var parseResult = Helpers.parse(input); if (!parseResult.result) { return cb(new Error(parseResult.reason || 'Invalid input')); } return cb(null, { result: true, name: parseResult.swagger.info.title, output: [{ type: 'collection', name: parseResult.swagger.info.title }] }); } }; // Exports the convert function for the plugin module.exports = { convert: function(input, options, cb) { if (input.type === 'string') { return Converter.convert(input.data, options, cb); } else if (input.type === 'json') { return Converter.convert(JSON.stringify(input.data), options, cb); } else if (input.type === 'file') { return fs.readFile(input.data, 'utf8', function(err, data) { if (err) { return cb(err); } return Converter.convert(data, options, cb); }); } return cb(null, { result: false, reason: 'Input type is not valid.' }); }, getMetaData: function (input, cb) { if (input.type === 'string') { return Converter.getMetaData(input.data, cb); } else if (input.type === 'json') { return Converter.getMetaData(JSON.stringify(input.data), cb); } else if (input.type === 'file') { return fs.readFile(input.data, 'utf8', function(err, data) { if (err) { return cb(err); } return Converter.getMetaData(data, cb); }); } return cb(null, { result: false, reason: 'Input Type is not valid.' }); }, getOptions: Converter.getOptions }; <|start_filename|>test/unit/structure.test.js<|end_filename|> let expect = require('chai').expect, getOptions = require('../../index').getOptions; const optionIds = [ 'collapseFolders', 'requestParametersResolution', 'exampleParametersResolution', 'indentCharacter', 'requestNameSource', 'folderStrategy', 'optimizeConversion', 'includeAuthInfoInExample' ], expectedOptions = { collapseFolders: { name: 'Collapse redundant folders', type: 'boolean', default: true, description: 'Importing will collapse all folders that have only one child element and lack ' + 'persistent folder-level data.' }, requestParametersResolution: { name: 'Request parameter generation', type: 'enum', default: 'Schema', availableOptions: ['Example', 'Schema'], description: 'Select whether to generate the request parameters based on the' + ' [schema](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#schemaObject) or the' + ' [example](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#exampleObject)' + ' in the schema.' }, exampleParametersResolution: { name: 'Response parameter generation', type: 'enum', default: 'Example', availableOptions: ['Example', 'Schema'], description: 'Select whether to generate the response parameters based on the' + ' [schema](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#schemaObject) or the' + ' [example](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#exampleObject)' + ' in the schema.' }, indentCharacter: { name: 'Set indent character', type: 'enum', default: 'Space', availableOptions: ['Space', 'Tab'], description: 'Option for setting indentation character' }, requestNameSource: { name: 'Naming requests', type: 'enum', default: 'Fallback', availableOptions: ['Url', 'Fallback'], description: 'Determines how the requests inside the generated collection will be named.' + ' If “Fallback” is selected, the request will be named after one of the following schema' + ' values: `description`, `operationid`, `url`.' }, folderStrategy: { name: 'Folder organization', type: 'enum', default: 'Paths', availableOptions: ['Paths', 'Tags'], description: 'Select whether to create folders according to the spec’s paths or tags.' }, optimizeConversion: { name: 'Optimize conversion', id: 'optimizeConversion', type: 'boolean', default: true, description: 'Optimizes conversion for large specification, disabling this option might affect' + ' the performance of conversion.' }, includeAuthInfoInExample: { name: 'Include auth info in example requests', type: 'boolean', default: true, description: 'Select whether to include authentication parameters in the example request' } }; describe('getOptions', function() { let options = getOptions(); it('must be a valid id and should be present in the whitelist of options id', function () { options.forEach((option) => { expect(option.id).to.be.oneOf(optionIds); }); }); it('must have a valid structure', function () { options.forEach((option) => { expect(option).to.have.property('name'); expect(option).to.have.property('id'); expect(option).to.have.property('type'); expect(option).to.have.property('default'); expect(option).to.have.property('description'); }); }); it('must have consistent type, description and name', function () { options.forEach((option) => { if (expectedOptions[option.id]) { expect(option).to.have.property('description'); expect(option.name).to.be.eql(expectedOptions[option.id].name); expect(option.type).to.be.eql(expectedOptions[option.id].type); expect(option.description).to.be.eql(expectedOptions[option.id].description); } else { console.warn(`Option ${option.name} not present in the list of expected options.`); } }); }); }); <|start_filename|>index.js<|end_filename|> // Exports the interface for the plugin module.exports = { validate: require('./lib/validate'), convert: require('./lib/convert').convert, getOptions: require('./lib/convert').getOptions, getMetaData: require('./lib/convert').getMetaData };
postmanlabs/swagger2-postman2
<|start_filename|>src/styles/font/font.css<|end_filename|> @font-face { font-family: "CustomFont"; src: url("b.ttf") format("truetype"); } *:not(i):not(.fa):not(.glyphicon) { font-family: CustomFont !important; } <|start_filename|>src/styles/general/dark_3.css<|end_filename|> :root { --main-bg-color: #000a14; --main-txt-color: #b8b8b8; --main-link-color: #bfc209; --main-border-color: #01070f; --main-bg-color-light: #01070f; } *:first-child > tr:first-child > td, *:first-child > tr:first-child > td > * { color: var(--main-link-color) !important; background: var(--main-bg-color) !important; border-color: var(--main-bg-color) !important; } .customTable-level1 tr.tableContent-level1 td { border-color: var(--main-border-color) !important; } html { background: var(--main-bg-color) !important; } html *:not(a) { color: var(--main-txt-color) !important; border-color: #00000000 !important; background: var(--main-bg-color) !important; } a { color: var(--main-link-color) !important; border: 0px !important; background: var(--main-bg-color) !important; } .box { background: var(--main-link-color) !important; } .box-body, .box-footer { border-bottom-left-radius: 0px !important; border-bottom-right-radius: 0px !important; } .btn.btn-link { color: var(--main-link-color) !important; } .btn.btn-primary, .btn.btn-primary > * { color: var(--main-bg-color) !important; background-color: var(--main-link-color) !important; } a > span { color: var(--main-link-color) !important; } img[src]:hover, input[type="image"]:hover { opacity: 1; } input, select, button, textarea { background: var(--main-bg-color-light) !important; } a:visited, a:visited *, a:active, a:active * { color: #5f5f5f !important; } input[type="radio"] { border-width: 0 !important; background: none !important; } <|start_filename|>src/coursepage.js<|end_filename|> /** * @module CoursePage */ let regNo; /** * @function triggerDownloads * @param {Object} downloads * @param {Object} downloads.linkData * @param {Object} downloads.course * @param {Object} downloads.facultySlotName * Sends message with download information to the background script */ const triggerDownloads = (downloads) => { chrome.extension.sendMessage({ message: downloads, }); }; /** * @function getDownloadLink * @param {String} hrefContent href present in the checkboxes * @param {String} regNo Registration Number of the User */ const getDownloadLink = (hrefContent, regNo) => { const url = hrefContent.substring( hrefContent.indexOf("'") + 1, hrefContent.lastIndexOf("'") ); const now = new Date(); const params = "authorizedID=" + regNo + "&x=" + encodeURIComponent(now.toUTCString()); return "https://vtop.vit.ac.in/vtop/" + url.trim() + "?" + params; }; /** * @function selectAllLinks * Selects all the valid links in the course page */ const selectAllLinks = () => { const checkedValue = document.getElementById("selectAll").checked; let checkbox = Array.from(document.querySelectorAll(".sexy-input")); checkbox.forEach((boxes) => { boxes.checked = checkedValue; }); }; /** * @function getLinkInfo * @param {DOMElement} linkElement * @param {Number} index * retreives link information, and the title */ const getLinkInfo = (linkElement, index) => { if (linkElement.outerText.indexOf("_") === -1) { const description = linkElement.parentNode.parentNode.previousElementSibling.innerText.trim(); const date = linkElement.parentNode.parentNode.previousElementSibling.previousElementSibling.previousElementSibling.innerText.trim(); let title = ( (index + 1).toString() + "-" + description + "-" + date ).replace(/[/:*?"<>|]/g, "_"); return { url: getDownloadLink(linkElement.href, regNo), title: title }; } return { url: getDownloadLink(linkElement.href, regNo), title: (index + 1).toString() + "-", }; }; /** * @function getCourseInfo * Returns the coursename and faculty details */ function getCourseInfo() { const detailsTable = document .querySelectorAll(".table")[0] .querySelectorAll("td"); const course = detailsTable[8].innerText.trim() + "-" + detailsTable[9].innerText.trim(); const facultySlotName = ( detailsTable[12].innerText.trim() + "-" + detailsTable[13].innerText.trim() ).replace(/[/:*?"<>|]/g, "-"); return { course, facultySlotName }; } const siblings = function (el) { if (el.parentNode === null) return []; return [...el.parentNode.children].filter(function (child) { return child !== el; }); }; /** * @function downloadFiles * @param {String} type * accepted type: ["all", "selected"] * Aggregates download data and pulls the trigger */ const downloadFiles = (type) => { const syllabusButton = document.querySelectorAll(".btn-primary")[0]; const syllabusLink = syllabusButton.innerText.trim() === "Download" ? syllabusButton.href : false; let allLinks = Array.from(document.querySelectorAll(".sexy-input")); allLinks = allLinks .filter((link) => type === "all" || link["checked"]) .map((link, index) => getLinkInfo(siblings(link)[0], index)); if (syllabusLink && type === "all") { allLinks.push({ title: "Syllabus", url: syllabusLink }); } const { course, facultySlotName } = getCourseInfo(); return triggerDownloads({ linkData: allLinks, course: course, facultySlotName: facultySlotName, }); }; /** * @function modifyCoursePage * Called when the course page is loaded, adds the checkboxes and buttons */ const modifyCoursePage = () => { // add selectAll checkbox const { course, facultySlotName } = getCourseInfo(); const selectAllElem = document.createElement("input"); selectAllElem.setAttribute("type", "checkbox"); selectAllElem.setAttribute("id", "selectAll"); document.querySelectorAll(".table-responsive")[0].appendChild(selectAllElem); const selectAllElemText = document.createElement("label"); selectAllElemText.innerHTML = "<em>&nbsp;Select All</em>"; document .querySelectorAll(".table-responsive")[0] .appendChild(selectAllElemText); selectAllElem.addEventListener("click", selectAllLinks); // add checkboxes let arr_check = Array.from(document.querySelectorAll(".btn-link")); let array_checkbox = []; arr_check.forEach((checks) => { const check = Array.from(checks.querySelectorAll("span")); check.forEach((checkElem) => { if (!checkElem.innerHTML.includes("Web Material")) { array_checkbox.push(checks); } }); }); array_checkbox.forEach((elem, index) => { elem.addEventListener( "click", (event) => { event.preventDefault(); return triggerDownloads({ linkData: [getLinkInfo(elem, index)], course, facultySlotName, }); }, false ); const inputElem = document.createElement("input"); inputElem.setAttribute("type", "checkbox"); inputElem.setAttribute("class", "sexy-input"); elem.parentNode.insertBefore(inputElem, elem.parentNode.firstChild); }); // projects page modification if (document.querySelectorAll(".btn-primary").length != 2) { const btnLen = document.querySelectorAll(".btn-primary").length; const btnToRemove = document.querySelectorAll(".btn-primary")[btnLen - 1]; btnToRemove.parentNode.removeChild(btnToRemove); } // add new buttons const downloadAllFilesBtn = document.createElement("input"); downloadAllFilesBtn.setAttribute("type", "button"); downloadAllFilesBtn.setAttribute("class", "btn btn-primary"); downloadAllFilesBtn.setAttribute( "style", "margin:4px;padding:3px 16px;font-size:13px;background-color:black;" ); downloadAllFilesBtn.setAttribute("value", "Download All Files"); downloadAllFilesBtn.setAttribute("id", "downloadAll"); downloadAllFilesBtn.onclick = () => downloadFiles("all"); const btnLen = document.querySelectorAll(".btn-primary").length; document .querySelectorAll(".btn-primary") [btnLen - 1].insertAdjacentElement("afterend", downloadAllFilesBtn); const downloadSelectedFilesBtn = document.createElement("input"); downloadSelectedFilesBtn.setAttribute("type", "button"); downloadSelectedFilesBtn.setAttribute("class", "btn btn-primary"); downloadSelectedFilesBtn.setAttribute( "style", "margin:4px;padding:3px 16px;font-size:13px;background-color:black;" ); downloadSelectedFilesBtn.setAttribute("value", "Download Selected Files"); downloadSelectedFilesBtn.setAttribute("id", "downloadSelected"); downloadSelectedFilesBtn.onclick = () => downloadFiles("selected"); downloadAllFilesBtn.insertAdjacentElement( "afterend", downloadSelectedFilesBtn ); // add credits const mainSection = document.getElementById("main-section"); const creditsElem = document.createElement("p"); creditsElem.innerHTML = '<center>CoursePage Download Manager - Made with ♥, <a href="https://www.github.com/Presto412" target="_blank">IEEE-CS</a></center>'; mainSection.appendChild(creditsElem); }; // Listener for messages from background chrome.runtime.onMessage.addListener((request) => { if (request.message === "ReloadFacultyPage") { try { chrome.storage.local.get(["facultyHTML"], function (result) { if (!result) { throw new Error("Invalid"); } document.querySelectorAll("#main-section").innerHTML = result.facultyHTML; }); } catch (error) { console.log(error); } } else if (request.message === "StoreFacultyPage") { try { let html = document.querySelectorAll("#main-section")[0].outerHTML; chrome.storage.local.set({ facultyHTML: html }); } catch (error) { console.log(error); } } else if (request.message === "CoursePageLoaded") { try { const loader = setInterval(function () { if (document.readyState !== "complete") return; clearInterval(loader); // gets the registration number regNo = document .querySelectorAll(".VTopHeaderStyle")[0] .innerText.replace("(STUDENT)", "") .trim() || ""; modifyCoursePage(); }, 100); } catch (error) { console.log(error); } } }); <|start_filename|>src/internalmarkspage.js<|end_filename|> /** * @function modifyInternalMarksPage * Called when the Internal Page is loaded, shows averages and totals */ const modifyInternalMarksPage = () => { let addClassAvg = document.querySelectorAll(".tableHeader-level1"); addClassAvg.forEach((addClassAvgs) => { let newTableHeader = addClassAvgs.innerHTML.split("\n"); newTableHeader.splice(9, 0, "<td>Class Average Weightage</td>"); addClassAvgs.innerHTML = newTableHeader.join(""); }); let addClassWeightage = document.querySelectorAll(".tableContent-level1"); addClassWeightage.forEach((addClassWeightages) => { let newTableContent = addClassWeightages.innerHTML.split("\n"); let maxMark = newTableContent[3].replace(/[^\d.]/g, ""); let weightage = newTableContent[4].replace(/[^\d.]/g, ""); let classAverage = newTableContent[8].replace(/[^\d.]/g, ""); let classAverageWeightage = (classAverage * weightage) / maxMark; newTableContent.splice( 9, 0, "<td><output>" + classAverageWeightage.toFixed(2) + "</output></td>" ); addClassWeightages.innerHTML = newTableContent.join(""); return; }); let tables = document.querySelectorAll(".customTable-level1 > tbody"); tables.forEach((table) => { let totalClassWeightage = 0, totalUserWeightage = 0, totalMaxMark = 0, totalWeightage = 0, totalScoredMark = 0, totalClassAverage = 0; let tableData = table.querySelectorAll(".tableContent-level1"); tableData = Array.from(tableData); tableData.map(function (row) { let tableContent = row.innerHTML.split("<td>"); let maxMark = tableContent[3].replace(/[^\d.]/g, ""); let weightage = tableContent[4].replace(/[^\d.]/g, ""); let scoredMark = tableContent[6].replace(/[^\d.]/g, ""); let userWeightage = tableContent[7].replace(/[^\d.]/g, ""); let classAverage = tableContent[8].replace(/[^\d.]/g, ""); let classWeightage = tableContent[9].replace(/[^\d.]/g, ""); totalMaxMark += parseFloat(maxMark); totalWeightage += parseFloat(weightage); totalScoredMark += parseFloat(scoredMark); totalClassAverage += parseFloat(classAverage); totalUserWeightage += parseFloat(userWeightage); totalClassWeightage += parseFloat(classWeightage); }); // Adds the row to display row table.innerHTML += ` <tr class='tableContent-level1' style='background: #efd2a5;' > <td></td> <td><b>Total:</b></td> <td> ${totalMaxMark.toFixed(2)} </td> <td> ${totalWeightage.toFixed(2)} </td> <td></td> <td> ${totalScoredMark.toFixed(2)} </td> <td style='font-weight: 700' > ${totalUserWeightage.toFixed( 2 )} </td> <td> ${totalClassAverage.toFixed(2)} </td> <td style='font-weight: 700' > ${totalClassWeightage.toFixed( 2 )} </td> <td></td> <td></td> </tr>`; }); }; chrome.runtime.onMessage.addListener((request) => { if (request.message === "MarkViewPage") { try { modifyInternalMarksPage(); } catch (error) { console.log(error); } } });
Thunder0104/Enhancer-for-VIT-Vellore-Academics
<|start_filename|>src/app/panels/filtering/module.js<|end_filename|> /* ## filtering */ define([ 'angular', 'app', 'underscore' ], function (angular, app, _) { 'use strict'; var module = angular.module('kibana.panels.filtering', []); app.useModule(module); module.controller('filtering', function($scope, datasourceSrv, $rootScope, $timeout, $q) { $scope.panelMeta = { status : "Stable", description : "graphite target filters" }; // Set and populate defaults var _d = { }; _.defaults($scope.panel,_d); $scope.init = function() { // empty. Don't know if I need the function then. }; $scope.remove = function(templateParameter) { $scope.filter.removeTemplateParameter(templateParameter); }; $scope.filterOptionSelected = function(templateParameter, option, recursive) { templateParameter.current = option; $scope.filter.updateTemplateData(); return $scope.applyFilterToOtherFilters(templateParameter) .then(function() { // only refresh in the outermost call if (!recursive) { $scope.dashboard.refresh(); } }); }; $scope.applyFilterToOtherFilters = function(updatedTemplatedParam) { var promises = _.map($scope.filter.templateParameters, function(templateParam) { if (templateParam === updatedTemplatedParam) { return; } if (templateParam.query.indexOf(updatedTemplatedParam.name) !== -1) { return $scope.applyFilter(templateParam); } }); return $q.all(promises); }; $scope.applyFilter = function(templateParam) { return datasourceSrv.default.metricFindQuery($scope.filter, templateParam.query) .then(function (results) { templateParam.editing = undefined; templateParam.options = _.map(results, function(node) { return { text: node.text, value: node.text }; }); if (templateParam.includeAll) { var allExpr = '{'; _.each(templateParam.options, function(option) { allExpr += option.text + ','; }); allExpr = allExpr.substring(0, allExpr.length - 1) + '}'; templateParam.options.unshift({text: 'All', value: allExpr}); } // if parameter has current value // if it exists in options array keep value if (templateParam.current) { var currentExists = _.findWhere(templateParam.options, { value: templateParam.current.value }); if (currentExists) { return $scope.filterOptionSelected(templateParam, templateParam.current, true); } } return $scope.filterOptionSelected(templateParam, templateParam.options[0], true); }); }; $scope.add = function() { $scope.filter.addTemplateParameter({ type : 'filter', name : 'filter name', editing : true, query : 'metric.path.query.*', }); }; }); }); <|start_filename|>src/test/specs/graphiteTargetCtrl-specs.js<|end_filename|> define([ ], function() { 'use strict'; describe('graphiteTargetCtrl', function() { var _targetCtrl; beforeEach(module('kibana.services')); beforeEach(module(function($provide){ $provide.value('filterSrv',{}); })); beforeEach(inject(function($controller, $rootScope) { _targetCtrl = $controller({ $scope: $rootScope.$new() }); })); describe('init', function() { beforeEach(function() { }); }); }); }); <|start_filename|>src/test/specs/graph-panel-controller-specs.js<|end_filename|> /*define([ 'panels/graphite/module' ], function() { 'use strict'; describe('Graph panel controller', function() { var _graphPanelCtrl; beforeEach(module('kibana.panels.graphite')); beforeEach(module(function($provide){ $provide.value('filterSrv',{}); })); beforeEach(inject(function($controller, $rootScope) { _graphPanelCtrl = $controller('graphite', { $scope: $rootScope.$new() }); })); describe('init', function() { beforeEach(function() { }); it('asd', function() { }); }); }); }); */ <|start_filename|>tasks/options/connect.js<|end_filename|> module.exports = function(config) { return { dev: { options: { port: 5601, hostname: '*', base: config.srcDir, keepalive: true } }, } }; <|start_filename|>src/app/controllers/playlistCtrl.js<|end_filename|> define([ 'angular', 'underscore', 'config' ], function (angular, _, config) { 'use strict'; var module = angular.module('kibana.controllers'); module.controller('PlaylistCtrl', function($scope, playlistSrv) { $scope.init = function() { $scope.timespan = config.playlist_timespan; $scope.loadFavorites(); $scope.$on('modal-opened', $scope.loadFavorites); }; $scope.loadFavorites = function() { $scope.favDashboards = playlistSrv.getFavorites().dashboards; _.each($scope.favDashboards, function(dashboard) { dashboard.include = true; }); }; $scope.removeAsFavorite = function(dashboard) { playlistSrv.removeAsFavorite(dashboard); $scope.loadFavorites(); }; $scope.start = function() { var included = _.where($scope.favDashboards, { include: true }); playlistSrv.start(included, $scope.timespan); }; }); }); <|start_filename|>src/test/mocks/dashboard-mock.js<|end_filename|> define([], function() { 'use strict'; return { create: function() { return { refresh: function() {}, set_interval: function(value) { this.current.refresh = value; }, current: { title: "", tags: [], style: "dark", timezone: 'browser', editable: true, failover: false, panel_hints: true, rows: [], pulldowns: [ { type: 'templating' }, { type: 'annotations' } ], nav: [ { type: 'timepicker' } ], services: {}, loader: { save_gist: false, save_elasticsearch: true, save_local: true, save_default: true, save_temp: true, save_temp_ttl_enable: true, save_temp_ttl: '30d', load_gist: false, load_elasticsearch: true, load_elasticsearch_size: 20, load_local: false, hide: false }, refresh: true } }; } }; }); <|start_filename|>src/app/services/dashboard/all.js<|end_filename|> define([ './dashboardKeyBindings', ], function () {});
gema-arta/grafana
<|start_filename|>Makefile<|end_filename|> BUILD_DIR?=./build CC=clang all: segment_dumper segment_dumper: $(BUILD_DIR) $(CC) main.c -o $(BUILD_DIR)/segment_dumper $(BUILD_DIR): mkdir -p $(BUILD_DIR) <|start_filename|>main.c<|end_filename|> /* -*- C -*- main.c */ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <mach-o/loader.h> #include <mach-o/swap.h> #include <mach-o/fat.h> /* hack until arm64 headers are worked out */ #ifndef CPU_TYPE_ARM64 # define CPU_TYPE_ARM64 (CPU_TYPE_ARM | CPU_ARCH_ABI64) #endif /* !CPU_TYPE_ARM64 */ extern void dump_segments(FILE *obj_file); int main(int argc, char *argv[]) { if (argc < 2 || strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-h") == 0) { printf("Usage: %s <path to mach-o binary>\n", argv[0]); return 1; } const char *filename = argv[1]; FILE *obj_file = fopen(filename, "rb"); if (obj_file == NULL) { printf("'%s' could not be opened.\n", argv[1]); return 1; } dump_segments(obj_file); fclose(obj_file); (void)argc; return 0; } static uint32_t read_magic(FILE *obj_file, off_t offset) { uint32_t magic; fseek(obj_file, offset, SEEK_SET); fread(&magic, sizeof(uint32_t), 1, obj_file); return magic; } static int is_magic_64(uint32_t magic) { return magic == MH_MAGIC_64 || magic == MH_CIGAM_64; } static int should_swap_bytes(uint32_t magic) { return magic == MH_CIGAM || magic == MH_CIGAM_64 || magic == FAT_CIGAM; } static int is_fat(uint32_t magic) { return magic == FAT_MAGIC || magic == FAT_CIGAM; } struct _cpu_type_names { cpu_type_t cputype; const char *cpu_name; /* FIXME: -Wpadded from clang */ }; static struct _cpu_type_names cpu_type_names[] = { { CPU_TYPE_I386, "i386" }, { CPU_TYPE_X86_64, "x86_64" }, { CPU_TYPE_ARM, "arm" }, { CPU_TYPE_ARM64, "arm64" } }; static const char *cpu_type_name(cpu_type_t cpu_type) { static int cpu_type_names_size = sizeof(cpu_type_names) / sizeof(struct _cpu_type_names); for (int i = 0; i < cpu_type_names_size; i++ ) { if (cpu_type == cpu_type_names[i].cputype) { return cpu_type_names[i].cpu_name; } } return "unknown"; } static void *load_bytes(FILE *obj_file, off_t offset, size_t size) { void *buf = calloc(1, size); fseek(obj_file, offset, SEEK_SET); fread(buf, size, 1, obj_file); return buf; } static void dump_segment_commands(FILE *obj_file, off_t offset, bool is_swap, uint32_t ncmds) { off_t actual_offset = offset; for (uint32_t i = 0U; i < ncmds; i++) { struct load_command *cmd = load_bytes(obj_file, actual_offset, sizeof(struct load_command)); if (is_swap) { swap_load_command(cmd, 0); } if (cmd->cmd == LC_SEGMENT_64) { struct segment_command_64 *segment = load_bytes(obj_file, actual_offset, sizeof(struct segment_command_64)); if (is_swap) { swap_segment_command_64(segment, 0); } printf("segname: %s\n", segment->segname); free(segment); } else if (cmd->cmd == LC_SEGMENT) { struct segment_command *segment = load_bytes(obj_file, actual_offset, sizeof(struct segment_command)); if (is_swap) { swap_segment_command(segment, 0); } printf("segname: %s\n", segment->segname); free(segment); } actual_offset += cmd->cmdsize; free(cmd); } } static void dump_mach_header(FILE *obj_file, off_t offset, bool is_64, bool is_swap) { uint32_t ncmds; off_t load_commands_offset = offset; if (is_64) { size_t header_size = sizeof(struct mach_header_64); struct mach_header_64 *header = load_bytes(obj_file, offset, header_size); if (is_swap) { swap_mach_header_64(header, 0); } ncmds = header->ncmds; load_commands_offset += header_size; printf("%s\n", cpu_type_name(header->cputype)); free(header); } else { size_t header_size = sizeof(struct mach_header); struct mach_header *header = load_bytes(obj_file, offset, header_size); if (is_swap) { swap_mach_header(header, 0); } ncmds = header->ncmds; load_commands_offset += header_size; printf("%s\n", cpu_type_name(header->cputype)); free(header); } dump_segment_commands(obj_file, load_commands_offset, is_swap, ncmds); } static void dump_fat_header(FILE *obj_file, int is_swap) { size_t header_size = sizeof(struct fat_header); size_t arch_size = sizeof(struct fat_arch); struct fat_header *header = load_bytes(obj_file, 0, header_size); if (is_swap) { swap_fat_header(header, 0); } off_t arch_offset = (off_t)header_size; for (uint32_t i = 0U; i < header->nfat_arch; i++) { struct fat_arch *arch = load_bytes(obj_file, arch_offset, arch_size); if (is_swap) { swap_fat_arch(arch, 1, 0); } off_t mach_header_offset = (off_t)arch->offset; free(arch); arch_offset += arch_size; uint32_t magic = read_magic(obj_file, mach_header_offset); int is_64 = is_magic_64(magic); int is_swap_mach = should_swap_bytes(magic); dump_mach_header(obj_file, mach_header_offset, is_64, is_swap_mach); } free(header); } void dump_segments(FILE *obj_file) { uint32_t magic = read_magic(obj_file, 0); int is_64 = is_magic_64(magic); int is_swap = should_swap_bytes(magic); int fat = is_fat(magic); if (fat) { dump_fat_header(obj_file, is_swap); } else { dump_mach_header(obj_file, 0, is_64, is_swap); } } /* EOF */
kunnan/KNsegment_dumper
<|start_filename|>samples/twilio/ip-messaging/src/app.js<|end_filename|> 'use strict'; const express = require('express'); const TwilioBot = require('./twiliobot'); const TwilioBotConfig = require('./twiliobotconfig'); const REST_PORT = (process.env.PORT || 5000); const DEV_CONFIG = process.env.DEVELOPMENT_CONFIG == 'true'; const APIAI_ACCESS_TOKEN = process.env.APIAI_ACCESS_TOKEN; const APIAI_LANG = process.env.APIAI_LANG; const ACCOUNT_SID = process.env.ACCOUNT_SID; const SERVICE_SID = process.env.SERVICE_SID; const SIGNING_KEY_SID = process.env.SIGNING_KEY_SID; const SIGNING_KEY_SECRET = process.env.SIGNING_KEY_SECRET; // console timestamps require('console-stamp')(console, 'yyyy.mm.dd HH:MM:ss.l'); const botConfig = new TwilioBotConfig(APIAI_ACCESS_TOKEN, APIAI_LANG, ACCOUNT_SID, SERVICE_SID, SIGNING_KEY_SID, SIGNING_KEY_SECRET); const bot = new TwilioBot(botConfig); bot.start(); const app = express(); app.listen(REST_PORT, function () { console.log('Rest service ready on port ' + REST_PORT); }); <|start_filename|>samples/twilio/ip-messaging/src/twiliobotconfig.js<|end_filename|> 'use strict'; module.exports = class TwilioBotConfig { get botIdentity() { return this._botIdentity; } set botIdentity(value) { this._botIdentity = value; } get apiaiAccessToken() { return this._apiaiAccessToken; } set apiaiAccessToken(value) { this._apiaiAccessToken = value; } get apiaiLang() { return this._apiaiLang; } set apiaiLang(value) { this._apiaiLang = value; } get accountSid() { return this._accountSid; } set accountSid(value) { this._accountSid = value; } get serviceSid() { return this._serviceSid; } set serviceSid(value) { this._serviceSid = value; } get signingKeySid() { return this._signingKeySid; } set signingKeySid(value) { this._signingKeySid = value; } get signingKeySecret() { return this._signingKeySecret; } set signingKeySecret(value) { this._signingKeySecret = value; } get devConfig() { return this._devConfig; } set devConfig(value) { this._devConfig = value; } constructor(apiaiAccessToken, apiaiLang, accountSid, serviceSid, signingKeySid, signingKeySecret) { this.botIdentity = "bot"; this._apiaiAccessToken = apiaiAccessToken; this._apiaiLang = apiaiLang; this._accountSid = accountSid; this._serviceSid = serviceSid; this._signingKeySid = signingKeySid; this._signingKeySecret = signingKeySecret; } }; <|start_filename|>samples/twitter/src/twitterbotconfig.js<|end_filename|> 'use strict'; module.exports = class TwitterBotConfig { get botName() { return this._botName; } set botName(value) { this._botName = value; } get apiaiAccessToken() { return this._apiaiAccessToken; } set apiaiAccessToken(value) { this._apiaiAccessToken = value; } get apiaiLang() { return this._apiaiLang; } set apiaiLang(value) { this._apiaiLang = value; } get consumerKey() { return this._consumerKey; } set consumerKey(value) { this._consumerKey = value; } get consumerSecret() { return this._consumerSecret; } set consumerSecret(value) { this._consumerSecret = value; } get accessToken() { return this._accessToken; } set accessToken(value) { this._accessToken = value; } get accessTokenSecret() { return this._accessTokenSecret; } set accessTokenSecret(value) { this._accessTokenSecret = value; } get devConfig() { return this._devConfig; } set devConfig(value) { this._devConfig = value; } constructor(apiaiAccessToken, apiaiLang, botName, consumerKey, consumerSecret, accessToken, accessTokenSecret) { this.apiaiAccessToken = apiaiAccessToken; this.apiaiLang = apiaiLang; this.botName = botName; this.consumerKey = consumerKey; this.consumerSecret = consumerSecret; this.accessToken = accessToken; this.accessTokenSecret = accessTokenSecret; } }; <|start_filename|>module/query_dev_request.js<|end_filename|> /*! * apiai * Copyright(c) 2015 http://api.ai/ * Apache 2.0 Licensed */ 'use strict'; var JSONApiDeveloperRequest = require('./json_api_dev_request').JSONApiDeveloperRequest; var util = require('util'); exports.QueryDeveloperRequest = module.exports.QueryDeveloperRequest = QueryDeveloperRequest; util.inherits(QueryDeveloperRequest, JSONApiDeveloperRequest); function QueryDeveloperRequest(application, options) { var self = this; if (!('method' in options)) { throw new Error('Must specify method (POST/GET).'); } if (!('path' in options)) { throw new Error('Must specify path.'); } if ('version' in options) { self.version = options.version; } self.method = options.method; self.path = options.path; QueryDeveloperRequest.super_.apply(this, arguments); } QueryDeveloperRequest.prototype._requestOptions = function() { var self = this; var path = self.path; if (self.hasOwnProperty("version")) { path += '?v=' + self.version; } var request_options = QueryDeveloperRequest.super_.prototype._requestOptions.apply(this, arguments); request_options.path = self.endpoint + path; request_options.method = self.method; return request_options; }; QueryDeveloperRequest.prototype._jsonRequestParameters = function() { var self = this; var json = { }; return json; }; <|start_filename|>samples/tropo/src/app.js<|end_filename|> 'use strict'; const express = require('express'); const bodyParser = require('body-parser'); const TropoBot = require('./tropobot'); const TropoBotConfig = require('./tropobotconfig'); const REST_PORT = (process.env.PORT || 5000); const DEV_CONFIG = process.env.DEVELOPMENT_CONFIG == 'true'; const APIAI_ACCESS_TOKEN = process.env.APIAI_ACCESS_TOKEN; const APIAI_LANG = process.env.APIAI_LANG; // console timestamps require('console-stamp')(console, 'yyyy.mm.dd HH:MM:ss.l'); const botConfig = new TropoBotConfig(APIAI_ACCESS_TOKEN, APIAI_LANG); const bot = new TropoBot(botConfig); const app = express(); app.use(bodyParser.json()); app.post('/sms', (req, res) => { console.log('POST sms received'); try { bot.processMessage(req, res); } catch (err) { return res.status(400).send('Error while processing ' + err.message); } }); app.listen(REST_PORT, function () { console.log('Rest service ready on port ' + REST_PORT); }); <|start_filename|>samples/line/app.json<|end_filename|> { "name": "API.AI Line integration", "description": "Api.ai Line integration allows you to create Line bots with natural language understanding based on Api.ai technology.", "repository": "https://github.com/api-ai/apiai-line-bot", "logo": "http://xvir.github.io/img/apiai.png", "keywords": ["api.ai", "line", "natural language"], "env": { "APIAI_ACCESS_TOKEN": { "description": "Client access token for Api.ai", "value": "" }, "APIAI_LANG": { "description": "Agent language", "value": "en", "required": false }, "LINE_CHANNEL_ID": { "description": "Channel ID from Line dashboard", "value": "" }, "LINE_CHANNEL_SECRET": { "description": "Channel Secret from Line dashboard", "value": "" }, "LINE_MID": { "description": "MID from Line dashboard", "value": "" } }, "engines": { "node": "5.10.1" } } <|start_filename|>module/developer_request.js<|end_filename|> /*! * apiai * Copyright(c) 2015 http://api.ai/ * Apache 2.0 Licensed */ 'use strict'; var Request = require('./request').Request; var util = require('util'); exports.DeveloperRequest = module.exports.DeveloperRequest = DeveloperRequest; util.inherits(DeveloperRequest, Request); function DeveloperRequest(application, options) { this.developerAccessToken = application.developerAccessToken; DeveloperRequest.super_.apply(this, arguments); } DeveloperRequest.prototype._headers = function() { var self = this; return { 'Accept': 'application/json', 'Authorization': 'Bearer ' + self.developerAccessToken, 'api-request-source': self.requestSource }; }; <|start_filename|>module/intent_request.js<|end_filename|> /*! * apiai * Copyright(c) 2015 http://api.ai/ * Apache 2.0 Licensed */ 'use strict'; var QueryDeveloperRequest = require('./query_dev_request').QueryDeveloperRequest; var util = require('util'); exports.IntentRequest = module.exports.IntentRequest = IntentRequest; util.inherits(IntentRequest, QueryDeveloperRequest); function IntentRequest(application, options, intent) { IntentRequest.super_.apply(this, [application, options]); var self = this; self.intent = intent; } IntentRequest.prototype._headers = function() { var headers = IntentRequest.super_.prototype._headers.apply(this, arguments); headers['Content-Type'] = 'application/json; charset=utf-8'; return headers; }; IntentRequest.prototype._jsonRequestParameters = function() { var self = this; var json = IntentRequest.super_.prototype._jsonRequestParameters.apply(this, arguments); if(self.intent != undefined) json.intent = self.intent; return json; }; IntentRequest.prototype.end = function() { var self = this; self.write(JSON.stringify(self._jsonRequestParameters())); IntentRequest.super_.prototype.end.apply(this, arguments); }; <|start_filename|>samples/text_request_no_ssl.js<|end_filename|> /*! * apiai * Copyright(c) 2015 http://api.ai/ * Apache 2.0 Licensed */ 'use strict'; // var apiai = require("../module/apiai"); var apiai = require("apiai"); var options = { secure: false, hostname: 'openapi-dev', endpoint: '/api/' }; var app = apiai("YOUR_ACCESS_TOKEN", options); var options = { sessionId: '<UNIQE SESSION ID>' }; var request = app.textRequest('Hello', options); request.on('response', function(response) { console.log(response); }); request.on('error', function(error) { console.log(error); }); request.end(); <|start_filename|>samples/twilio/bot/src/twiliobotconfig.js<|end_filename|> 'use strict'; module.exports = class TwilioBotConfig { get apiaiAccessToken() { return this._apiaiAccessToken; } set apiaiAccessToken(value) { this._apiaiAccessToken = value; } get apiaiLang() { return this._apiaiLang; } set apiaiLang(value) { this._apiaiLang = value; } get devConfig() { return this._devConfig; } set devConfig(value) { this._devConfig = value; } constructor(apiaiAccessToken, apiaiLang) { this._apiaiAccessToken = apiaiAccessToken; this._apiaiLang = apiaiLang; } toPlainDoc() { return { apiaiAccessToken: this._apiaiAccessToken, apiaiLang: this._apiaiLang } } static fromPlainDoc(doc){ return new TwilioBotConfig( doc.apiaiAccessToken, doc.apiaiLang); } }; <|start_filename|>samples/tropo/src/tropobot.js<|end_filename|> 'use strict'; const apiai = require('apiai'); const uuid = require('node-uuid'); const request = require('request'); module.exports = class TropoBot { get apiaiService() { return this._apiaiService; } set apiaiService(value) { this._apiaiService = value; } get botConfig() { return this._botConfig; } set botConfig(value) { this._botConfig = value; } get sessionIds() { return this._sessionIds; } set sessionIds(value) { this._sessionIds = value; } constructor(botConfig) { this._botConfig = botConfig; var apiaiOptions = { language: botConfig.apiaiLang, requestSource: "tropo" }; this._apiaiService = apiai(botConfig.apiaiAccessToken, apiaiOptions); this._sessionIds = new Map(); } processMessage(req, res) { if (this._botConfig.devConfig) { console.log("body", req.body); } if (req.body && req.body.session && req.body.session.from && req.body.session.initialText) { let chatId = req.body.session.from.id; let messageText = req.body.session.initialText; console.log(chatId, messageText); if (messageText) { if (!this._sessionIds.has(chatId)) { this._sessionIds.set(chatId, uuid.v1()); } let apiaiRequest = this._apiaiService.textRequest(messageText, { sessionId: this._sessionIds.get(chatId) }); apiaiRequest.on('response', (response) => { if (TropoBot.isDefined(response.result)) { let responseText = response.result.fulfillment.speech; if (TropoBot.isDefined(responseText)) { console.log('Response as text message'); res.status(200).json({ tropo: [{say: {value: responseText}}] }); } else { console.log('Received empty speech'); return res.status(400).end('Received empty speech'); } } else { console.log('Received empty result'); return res.status(400).end('Received empty result'); } }); apiaiRequest.on('error', (error) => console.error(error)); apiaiRequest.end(); } else { console.log('Empty message'); return res.status(400).end('Empty message'); } } else { console.log('Empty message'); return res.status(400).end('Empty message'); } } static isDefined(obj) { if (typeof obj == 'undefined') { return false; } if (!obj) { return false; } return obj != null; } } <|start_filename|>samples/line/src/app.js<|end_filename|> 'use strict'; const express = require('express'); const bodyParser = require('body-parser'); const crypto = require('crypto'); const LineBot = require('./linebot'); const LineBotConfig = require('./linebotconfig'); const REST_PORT = (process.env.PORT || 5000); const DEV_CONFIG = process.env.DEVELOPMENT_CONFIG == 'true'; const APIAI_ACCESS_TOKEN = process.env.APIAI_ACCESS_TOKEN; const APIAI_LANG = process.env.APIAI_LANG; const LINE_CHANNEL_ID = process.env.LINE_CHANNEL_ID; const LINE_CHANNEL_SECRET = process.env.LINE_CHANNEL_SECRET; const LINE_MID = process.env.LINE_MID; // console timestamps require('console-stamp')(console, 'yyyy.mm.dd HH:MM:ss.l'); const botConfig = new LineBotConfig(APIAI_ACCESS_TOKEN, APIAI_LANG, LINE_CHANNEL_ID, LINE_CHANNEL_SECRET, LINE_MID); const bot = new LineBot(botConfig); const app = express(); app.use(bodyParser.json({ verify: function(req, res, buf, encoding) { // raw body for signature check req.rawBody = buf.toString(); } })); app.post('/webhook', (req, res) => { console.log('POST received'); let signature = req.get('X-LINE-ChannelSignature'); let rawBody = req.rawBody; let hash = crypto.createHmac('sha256', LINE_CHANNEL_SECRET).update(rawBody).digest('base64'); if (hash != signature) { console.log("Unauthorized request"); return res.status(401).send('Wrong request signature'); } try { if (req.body.result) { req.body.result.forEach(function (item) { bot.processMessage(item, res); }); } } catch (err) { return res.status(400).send('Error while processing ' + err.message); } }); app.listen(REST_PORT, function () { console.log('Rest service ready on port ' + REST_PORT); }); <|start_filename|>samples/line/src/linebot.js<|end_filename|> 'use strict'; const apiai = require('apiai'); const uuid = require('node-uuid'); const request = require('request'); module.exports = class LineBot { get apiaiService() { return this._apiaiService; } set apiaiService(value) { this._apiaiService = value; } get botConfig() { return this._botConfig; } set botConfig(value) { this._botConfig = value; } get sessionIds() { return this._sessionIds; } set sessionIds(value) { this._sessionIds = value; } constructor(botConfig) { this._botConfig = botConfig; var apiaiOptions = { language: botConfig.apiaiLang, requestSource: "line" }; this._apiaiService = apiai(botConfig.apiaiAccessToken, apiaiOptions); this._sessionIds = new Map(); } processMessage(message, res) { if (this._botConfig.devConfig) { console.log("message", message); } if (message.content && message.content.from && message.content.text) { let chatId = message.content.from; let messageText = message.content.text; console.log(chatId, messageText); if (messageText) { if (!this._sessionIds.has(chatId)) { this._sessionIds.set(chatId, uuid.v1()); } let apiaiRequest = this._apiaiService.textRequest(messageText, { sessionId: this._sessionIds.get(chatId) }); apiaiRequest.on('response', (response) => { if (LineBot.isDefined(response.result)) { let responseText = response.result.fulfillment.speech; if (LineBot.isDefined(responseText)) { console.log('Response as text message'); this.postLineMessage(chatId, responseText); } else { console.log('Received empty speech'); } } else { console.log('Received empty result') } }); apiaiRequest.on('error', (error) => console.error(error)); apiaiRequest.end(); } else { console.log('Empty message'); } } else { console.log('Empty message'); } } postLineMessage(to, text) { request.post("https://trialbot-api.line.me/v1/events", { headers: { 'X-Line-ChannelID': this._botConfig.channelId, 'X-Line-ChannelSecret': this._botConfig.channelSecret, 'X-Line-Trusted-User-With-ACL': this._botConfig.MID }, json: { to: [to], toChannel: 1383378250, eventType: "138311608800106203", content: { contentType: 1, toType: 1, text: text } } }, function (error, response, body) { if (error) { console.error('Error while sending message', error); return; } if (response.statusCode != 200) { console.error('Error status code while sending message', body); return; } console.log('Send message succeeded'); }); } static isDefined(obj) { if (typeof obj == 'undefined') { return false; } if (!obj) { return false; } return obj != null; } } <|start_filename|>samples/twilio/bot/src/app.js<|end_filename|> 'use strict'; const express = require('express'); const bodyParser = require('body-parser'); const TwilioBot = require('./twiliobot'); const TwilioBotConfig = require('./twiliobotconfig'); const REST_PORT = (process.env.PORT || 5000); const DEV_CONFIG = process.env.DEVELOPMENT_CONFIG == 'true'; const APIAI_ACCESS_TOKEN = process.env.APIAI_ACCESS_TOKEN; const APIAI_LANG = process.env.APIAI_LANG; // console timestamps require('console-stamp')(console, 'yyyy.mm.dd HH:MM:ss.l'); const botConfig = new TwilioBotConfig(APIAI_ACCESS_TOKEN, APIAI_LANG); const bot = new TwilioBot(botConfig); const app = express(); app.use(bodyParser.urlencoded({extended: true})); app.post('/sms', (req, res) => { console.log('POST sms received'); try { bot.processMessage(req, res); } catch (err) { return res.status(400).send('Error while processing ' + err.message); } }); app.listen(REST_PORT, function () { console.log('Rest service ready on port ' + REST_PORT); }); <|start_filename|>samples/twitter/src/app.js<|end_filename|> 'use strict'; const express = require('express'); const TwitterBot = require('./twitterbot'); const TwitterBotConfig = require('./twitterbotconfig'); const REST_PORT = (process.env.PORT || 5000); const DEV_CONFIG = process.env.DEVELOPMENT_CONFIG == 'true'; // console timestamps require('console-stamp')(console, 'yyyy.mm.dd HH:MM:ss.l'); const botConfig = new TwitterBotConfig( process.env.APIAI_ACCESS_TOKEN, process.env.APIAI_LANG, process.env.BOT_NAME, process.env.CONSUMER_KEY, process.env.CONSUMER_SECRET, process.env.ACCESS_TOKEN, process.env.ACCESS_TOKEN_SECRET ); botConfig.devConfig = DEV_CONFIG; const bot = new TwitterBot(botConfig); bot.start(); const app = express(); app.listen(REST_PORT, function () { console.log('Rest service ready on port ' + REST_PORT); });
akiraindia86/node-chatbox
<|start_filename|>cli.js<|end_filename|> #!/usr/bin/env node import meow from 'meow'; import {moveFileSync} from 'move-file'; const cli = meow(` Usage $ move-file <source-path> <destination-path> Options --no-overwrite Don't overwrite an existing destination file Example $ move-file source/unicorn.png destination/unicorn.png `, { importMeta: import.meta, flags: { overwrite: { type: 'boolean', default: true, }, }, }); const [source, destination] = cli.input; moveFileSync(source, destination, cli.flags);
sindresorhus/move-file-cli
<|start_filename|>typedoc.json<|end_filename|> { "inputFiles": [ "./types.d.ts" ], "out": "docs", "mode": "file", "name": "Solidity AST", "disableSources": true, "includeDeclarations": true, "excludeExternals": true } <|start_filename|>test/helpers/solc-compile-helper.js<|end_filename|> if (process.send === undefined) { throw new Error('Must run via child_process.fork'); } const events = require('events'); process.once('message', async ({ version, sources }) => { const solc = require(`solc-${version}`); const output = JSON.parse( solc.compile( JSON.stringify({ sources, language: 'Solidity', settings: { outputSelection: { '*': { '': ['ast'] } }, }, }) ) ); process.send(output); }); <|start_filename|>test/helpers/solc-versions.js<|end_filename|> const semver = require('semver'); const versions = Object.keys(require('../../package.json').devDependencies) .filter(s => s.startsWith('solc-')) .map(s => s.replace('solc-', '')) .sort(semver.compare); const latest = versions[versions.length - 1]; module.exports = { versions, latest }; <|start_filename|>scripts/build-types.js<|end_filename|> #!/usr/bin/env node const json2ts = require('json-schema-to-typescript'); const fs = require('fs'); const schema = require('../schema.json'); json2ts.compile(schema, schema.title, { strictIndexSignatures: true, bannerComment: '/* tslint:disable */', }).then(result => { fs.writeFileSync('types.d.ts', result); }).catch(err => { console.error(err.stack); process.exit(1); }); <|start_filename|>test/openzeppelin-contracts.js<|end_filename|> const { assertValid } = require('./helpers/assert-valid'); const { sources } = require('./openzeppelin-contracts.json'); describe('openzeppelin contracts', function () { for (const [ path, { ast } ] of Object.entries(sources)) { it(path, function () { assertValid(ast); }); } }); <|start_filename|>test/solidity-submodule.js<|end_filename|> const fs = require('promisified/fs'); const path = require('path'); const { assertValid } = require('./helpers/assert-valid'); const dir = path.join(__dirname, 'solidity/test/libsolidity/ASTJSON'); describe('solidity submodule', function () { // we read all jsons except those marked legacy or parseOnly const inputs = fs.readdirSync(dir) .filter(e => /^.*(?<!_legacy|_parseOnly)\.json$/.test(e)); before('read inputs', async function () { const contents = await Promise.all(inputs.map(f => fs.readFile(path.resolve(dir, f), 'utf8'))); this.inputContents = {}; for (const [i, content] of contents.entries()) { this.inputContents[inputs[i]] = content; } }); for (const f of inputs) { it(f, function () { const text = this.inputContents[f]; if (text.length === 0) return; const doc = JSON.parse(text.replace(/%EVMVERSION%/g, JSON.stringify('berlin'))); // Some of these files are arrays so we use concat to treat them uniformly. const asts = [].concat(doc); for (const ast of asts) { assertValid(ast); } }); } }); <|start_filename|>test/helpers/assert-valid.js<|end_filename|> const Ajv = require('ajv'); const lodash = require('lodash'); const chalk = require('chalk'); const util = require('util'); const ajv = new Ajv({ verbose: true }); ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-06.json')); const validate = ajv.compile(require('../../scripts/build-schema')); function assertValid(ast, file) { if (!validate(ast)) { const longest = lodash.maxBy(validate.errors, e => e.instancePath.split('/').length); throw new Error(formatError(longest, ast, file)); } } function formatError(error, doc, file) { const pathComponents = error.instancePath.split('/'); const nodeTree = pathComponents.map((c, i) => { const subPath = pathComponents.slice(1, i + 1).concat('nodeType').join('.'); const nodeType = lodash.get(doc, subPath) || ''; const indent = i === 0 ? '' : ' '.repeat(i - 1) + '└─'; if (nodeType === 'SourceUnit') c = file; return lodash.compact([indent, nodeType, c && chalk.dim(c)]).join(' '); }).join('\n'); const params = Object.values(error.params).join(', '); const dataString = util.inspect(error.data, { compact: false, depth: 1 }); return `${error.message} (${params})\n\n${nodeTree}\n\n${dataString}`; } module.exports = { assertValid }; <|start_filename|>scripts/build-finder.js<|end_filename|> #!/usr/bin/env node // @ts-check 'use strict'; const fs = require('fs'); const _ = require('lodash'); const reachable = {}; const schema = require('../schema.json'); for (const def of [...Object.values(schema.definitions), schema]) { if ('properties' in def && 'nodeType' in def.properties) { const parentType = def.properties.nodeType.enum[0]; _.defaults(reachable, { [parentType]: {} }); for (const prop in def.properties) { for (const containedType of getReachableNodeTypes(def.properties[prop])) { _.set(reachable, [containedType, parentType, prop], true); } } } } const finder = _.mapValues(reachable, f => _.mapValues(f, Object.keys)); fs.writeFileSync('finder.json', JSON.stringify(finder, null, 2)); function* getReachableNodeTypes(nodeSchema, visited = new Set()) { yield* _.get(nodeSchema, ['properties', 'nodeType', 'enum'], []); if ('$ref' in nodeSchema) { const [ ref ] = nodeSchema['$ref'].match(/[^\/]+$/); if (!visited.has(ref)) { visited.add(ref); yield* getReachableNodeTypes(schema.definitions[ref], visited); } } if ('anyOf' in nodeSchema) { for (const subSchema of nodeSchema['anyOf']) { yield* getReachableNodeTypes(subSchema, visited); } } if ('properties' in nodeSchema) { for (const prop of Object.values(nodeSchema.properties)) { yield* getReachableNodeTypes(prop, visited); } } if ('items' in nodeSchema) { yield* getReachableNodeTypes(nodeSchema.items, visited); } } <|start_filename|>test/helpers/solc-compile.js<|end_filename|> const proc = require('child_process'); const events = require('events'); const lodash = require('lodash'); async function compile(version, sources) { const child = proc.fork(require.resolve('./solc-compile-helper')); child.send({ version, sources }); const [output] = await events.once(child, 'message'); // allows tests to exit as soon as they finish // otherwise solc module delays exit child.disconnect(); child.unref(); if (output.errors && output.errors.some(e => e.severity !== 'warning')) { throw new Error(lodash.map(output.errors, 'formattedMessage').join('\n')); } return output; } module.exports = { compile }; <|start_filename|>test/solc.js<|end_filename|> const fs = require('promisified/fs'); const path = require('path'); const semver = require('semver'); const lodash = require('lodash'); const { assertValid } = require('./helpers/assert-valid'); const { versions } = require('./helpers/solc-versions'); const { compile } = require('./helpers/solc-compile'); describe('solc', function () { this.timeout(10 * 60 * 1000); before('reading solidity sources', async function () { const files = await fs.readdir(path.join(__dirname, 'sources')); this.sources = {}; this.sourceVersions = {}; for (const file of files) { const content = await fs.readFile( path.join(__dirname, 'sources', file), 'utf8', ); this.sources[file] = { content }; this.sourceVersions[file] = content.match(/pragma solidity (.*);/)[1]; } }); for (const version of versions) { it(version, async function () { const sources = lodash.pickBy(this.sources, (_, f) => semver.satisfies(version, this.sourceVersions[f]), ); const output = await compile(version, sources); for (const source of Object.keys(sources)) { assertValid(output.sources[source].ast, source); } }); } });
Amxx/solidity-ast
<|start_filename|>lua/configs/global/filetypes/filetypes/yaml.lua<|end_filename|> vim.bo.shiftwidth = 2 vim.bo.tabstop = 2
essn/lvim
<|start_filename|>src/apis/controllers/task.controller.js<|end_filename|> const httpStatus = require('http-status') const catchAsync = require('../../utils/catch-async') const { taskService } = require('../services') const CreateTask = catchAsync(async (req, res) => { const task = await taskService.createTask(req.body) res.status(httpStatus.CREATED).send({ task }) }) const DeleteTask = catchAsync(async (req, res) => { await taskService.deleteTask(req.params.id) res.status(httpStatus.NO_CONTENT).send() }) const GetTasks = catchAsync(async (req, res) => { const tasks = await taskService.getTasks() res.status(httpStatus.OK).send({ tasks }) }) const UpdateTask = catchAsync(async (req, res) => { const task = await taskService.updateTask(req.params.id, req.body) res.status(httpStatus.OK).send({ task }) }) module.exports = { CreateTask, DeleteTask, GetTasks, UpdateTask, } <|start_filename|>src/apis/services/task.service.js<|end_filename|> const { Task } = require('../models') /** * Create a task * @param {Object} taskBody * @returns {Promise<Task>} */ const createTask = async (taskBody) => { return Task.create(taskBody) } const deleteTask = async (taskId) => { return Task.deleteOne({ _id: taskId }) } /** * Get a task * @param {Object} taskBody * @returns {Promise<Task>} */ const getTasks = async () => { return Task.find({}).sort({ dueDate: -1 }).lean() } const updateTask = async (id, taskBody) => { const task = await Task.findOne({ _id: id }) Object.keys(taskBody).forEach((key) => { task[key] = taskBody[key] }) console.log('taskkkk: ', task) await task.save() return task } module.exports = { createTask, deleteTask, getTasks, updateTask, } <|start_filename|>src/apis/routes/index.js<|end_filename|> const express = require('express') const authRoute = require('./v1/auth.route') const taskRoute = require('./v1/task.route') const userRoute = require('./v1/user.route') const router = express.Router() const defaultRoutes = [ { path: '/v1/auth', route: authRoute, }, { path: '/v1/tasks', route: taskRoute, }, { path: '/v1/users', route: userRoute, }, ] defaultRoutes.forEach((route) => { router.use(route.path, route.route) }) module.exports = router <|start_filename|>src/apis/models/task.model.js<|end_filename|> const mongoose = require('mongoose') const { toJSON } = require('./plugins') const taskSchema = mongoose.Schema( { title: { type: String, required: true, }, description: { type: String, required: false, }, dueDate: { type: Number, required: false, }, priority: { type: String, required: false, }, completed: { type: Boolean, required: true, default: false, }, }, { timestamps: true, } ) taskSchema.plugin(toJSON) /** * @typedef Token */ const Task = mongoose.model('Task', taskSchema) module.exports = Task <|start_filename|>src/apis/routes/v1/task.route.js<|end_filename|> const express = require('express') const { taskController } = require('../../controllers') const router = express.Router() router.delete('/:id', taskController.DeleteTask) router.patch('/:id', taskController.UpdateTask) router.get('/list', taskController.GetTasks) router.post('/new', taskController.CreateTask) module.exports = router /** * @swagger * tags: * name: Tasks * description: Task management and retrieval */ <|start_filename|>src/apis/controllers/index.js<|end_filename|> module.exports.authController = require('./auth.controller') module.exports.taskController = require('./task.controller')
Honghm/booking
<|start_filename|>js/sliders.js<|end_filename|> /* * Copyright (c) 2012 The Chromium Authors. 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. */ function updateSingleGain( event ) { var t = event.target; var value = t.value; t.audioNode.gain.value = value; //update the numeric display t.parentNode.childNodes[2].textContent = value; } function updateSingleFrequency( event ) { var t = event.target; var value = t.value; t.audioNode.frequency.value = value; //update the numeric display t.parentNode.childNodes[2].textContent = value; } function updateSingleDetune( event ) { var t = event.target; var value = t.value; t.audioNode.detune.value = value; //update the numeric display t.parentNode.childNodes[2].textContent = value; } function updateSingleQ( event ) { var t = event.target; var value = t.value; t.audioNode.Q.value = value; // if this is one of our chained filters, update the chained filter too if (t.audioNode.chainedFilter) t.audioNode.chainedFilter.Q.value = value; //update the numeric display t.parentNode.childNodes[2].textContent = value; } function updateGains( event ) { var t = event.target; var value = t.value; for (var i=0; i<numVocoderBands; i++) t.audioNodes[i].gain.value = value; //update the numeric display t.parentNode.childNodes[2].textContent = value; } function updateQs( event ) { var t = event.target; var value = t.value; for (var i=0; i<numVocoderBands; i++) t.audioNodes[i].Q.value = value; //update the numeric display t.parentNode.childNodes[2].textContent = value; } function updateFrequencies( event ) { var t = event.target; var value = t.value; for (var i=0; i<numVocoderBands; i++) t.audioNodes[i].frequency.value = value; //update the numeric display t.parentNode.childNodes[2].textContent = value; } function scaleCarrierFilterFrequencies( scalingFactor ) { for (var i=0; i<numVocoderBands; i++) { var filter = carrierBands[i]; var newFrequency = vocoderBands[i].frequency * scalingFactor; filter.frequency.value = newFrequency; if (filter.chainedFilter) filter.chainedFilter.frequency.value = newFrequency; } } function clearSliders() { var sliders = document.getElementById("sliders"); var child; for (child=sliders.firstChild; child; child=sliders.firstChild) sliders.removeChild( child ); } function addColumnSlider( label, defaultValue, minValue, maxValue, nodeArray, onChange ) { // insert a range control // <input type="range" id="rangeEl" value="0.5" oninput="alert(this.value);" min="0.0" max="1.0" step="0.01"> var div = document.createElement("div"); div.appendChild(document.createTextNode(label)); var ctl = document.createElement("input"); ctl.type = "range"; ctl.min = minValue; ctl.max = maxValue; ctl.step = (maxValue - minValue) / 1000.0; ctl.value = defaultValue; ctl.oninput = onChange; ctl.audioNodes = nodeArray; ctl.label = label; div.appendChild(ctl); div.appendChild(document.createTextNode(defaultValue)); document.getElementById("sliders").appendChild(div); } function addSingleValueSlider( label, defaultValue, minValue, maxValue, node, onChange ) { // insert a range control // <input type="range" id="rangeEl" value="0.5" oninput="alert(this.value);" min="0.0" max="1.0" step="0.01"> var div = document.createElement("div"); div.appendChild(document.createTextNode(label)); var ctl = document.createElement("input"); ctl.type = "range"; ctl.min = minValue; ctl.max = maxValue; ctl.step = (maxValue - minValue) / 1000.0; ctl.value = defaultValue; ctl.oninput = onChange; ctl.audioNode = node; ctl.label = label; div.appendChild(ctl); div.appendChild(document.createTextNode(defaultValue)); document.getElementById("sliders").appendChild(div); } <|start_filename|>js/app.js<|end_filename|> chrome.app.runtime.onLaunched.addListener(function() { chrome.app.window.create('index.html', { width: 980, height: 550 }) }) <|start_filename|>js/vocoder.js<|end_filename|> /* * Copyright (c) 2012 The Chromium Authors. 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. */ var CANVAS_WIDTH = 582; var CANVAS_HEIGHT = 150; var GAINS_CANVAS_HEIGHT = 100; var FILTER_QUALITY = 6; // The Q value for the carrier and modulator filters var animationRunning = false; // These are "placeholder" gain nodes - because the modulator and carrier will get swapped in // as they are loaded, it's easier to connect these nodes to all the bands, and the "real" // modulator & carrier AudioBufferSourceNodes connect to these. var modulatorInput = null; var carrierInput = null; var modulatorGain = null; var modulatorGainValue = 1.0; // noise node added to the carrier signal var noiseBuffer = null; var noiseNode = null; var noiseGain = null; var noiseGainValue = 0.2; // Carrier sample gain var carrierSampleNode = null; var carrierSampleGain = null; var carrierSampleGainValue = 0.0; // Carrier Synth oscillator stuff var oscillatorNode = null; var oscillatorType = 4; // CUSTOM var oscillatorGain = null; var oscillatorGainValue = 1.0; var oscillatorDetuneValue = 0; var FOURIER_SIZE = 2048; var wavetable = null; var wavetableSignalGain = null; var WAVETABLEBOOST = 40.0; var SAWTOOTHBOOST = 0.40; // These are the arrays of nodes - the "columns" across the frequency band "rows" var modFilterBands = null; // tuned bandpass filters var modFilterPostGains = null; // post-filter gains. var heterodynes = null; // gain nodes used to multiply bandpass X sine var powers = null; // gain nodes used to multiply prev out by itself var lpFilters = null; // tuned LP filters to remove doubled copy of product var lpFilterPostGains = null; // gain nodes for tuning input to waveshapers var bandAnalysers = null; // these are just used to drive the visual vocoder band drawing var carrierBands = null; // tuned bandpass filters, same as modFilterBands but in carrier chain var carrierFilterPostGains = null; // post-bandpass gain adjustment var carrierBandGains = null; // these are the "control gains" driven by the lpFilters var modulatorCanvas = null; var carrierCanvas = null; var outputCanvas = null; var DEBUG_BAND = 5; // current debug band - used to display a filtered signal var vocoderBands; var numVocoderBands; var hpFilterGain = null; // this function will algorithmically re-calculate vocoder bands, distributing evenly // from startFreq to endFreq, splitting evenly (logarhythmically) into a given numBands. // The function places this info into the global vocoderBands and numVocoderBands variables. function generateVocoderBands( startFreq, endFreq, numBands ) { // Remember: 1200 cents in octave, 100 cents per semitone var totalRangeInCents = 1200 * Math.log( endFreq / startFreq ) / Math.LN2; var centsPerBand = totalRangeInCents / numBands; var scale = Math.pow( 2, centsPerBand / 1200 ); // This is the scaling for successive bands vocoderBands = new Array(); var currentFreq = startFreq; for (var i=0; i<numBands; i++) { vocoderBands[i] = new Object(); vocoderBands[i].frequency = currentFreq; // console.log( "Band " + i + " centered at " + currentFreq + "Hz" ); currentFreq = currentFreq * scale; } numVocoderBands = numBands; } function loadNoiseBuffer() { // create a 5-second buffer of noise var lengthInSamples = 5 * audioContext.sampleRate; noiseBuffer = audioContext.createBuffer(1, lengthInSamples, audioContext.sampleRate); var bufferData = noiseBuffer.getChannelData(0); for (var i = 0; i < lengthInSamples; ++i) { bufferData[i] = (2*Math.random() - 1); // -1 to +1 } } function initBandpassFilters() { // When this function is called, the carrierNode and modulatorAnalyser // may not already be created. Create placeholder nodes for them. modulatorInput = audioContext.createGain(); carrierInput = audioContext.createGain(); if (modFilterBands == null) modFilterBands = new Array(); if (modFilterPostGains == null) modFilterPostGains = new Array(); if (heterodynes == null) heterodynes = new Array(); if (powers == null) powers = new Array(); if (lpFilters == null) lpFilters = new Array(); if (lpFilterPostGains == null) lpFilterPostGains = new Array(); if (bandAnalysers == null) bandAnalysers = new Array(); if (carrierBands == null) carrierBands = new Array(); if (carrierFilterPostGains == null) carrierFilterPostGains = new Array(); if (carrierBandGains == null) carrierBandGains = new Array(); var waveShaperCurve = new Float32Array(65536); // Populate with a "curve" that does an abs() var n = 65536; var n2 = n / 2; for (var i = 0; i < n2; ++i) { x = i / n2; waveShaperCurve[n2 + i] = x; waveShaperCurve[n2 - i - 1] = x; } // Set up a high-pass filter to add back in the fricatives, etc. // (this isn't used by default in the "production" version, as I hid the slider) var hpFilter = audioContext.createBiquadFilter(); hpFilter.type = "highpass"; hpFilter.frequency.value = 8000; // or use vocoderBands[numVocoderBands-1].frequency; hpFilter.Q.value = 1; // no peaking modulatorInput.connect( hpFilter); hpFilterGain = audioContext.createGain(); hpFilterGain.gain.value = 0.0; hpFilter.connect( hpFilterGain ); hpFilterGain.connect( audioContext.destination ); //clear the arrays modFilterBands.length = 0; modFilterPostGains.length = 0; heterodynes.length = 0; powers.length = 0; lpFilters.length = 0; lpFilterPostGains.length = 0; carrierBands.length = 0; carrierFilterPostGains.length = 0; carrierBandGains.length = 0; bandAnalysers.length = 0; var outputGain = audioContext.createGain(); outputGain.connect(audioContext.destination); var rectifierCurve = new Float32Array(65536); for (var i=-32768; i<32768; i++) rectifierCurve[i+32768] = ((i>0)?i:-i)/32768; for (var i=0; i<numVocoderBands; i++) { // CREATE THE MODULATOR CHAIN // create the bandpass filter in the modulator chain var modulatorFilter = audioContext.createBiquadFilter(); modulatorFilter.type = "bandpass"; // Bandpass filter modulatorFilter.frequency.value = vocoderBands[i].frequency; modulatorFilter.Q.value = FILTER_QUALITY; // initial quality modulatorInput.connect( modulatorFilter ); modFilterBands.push( modulatorFilter ); // Now, create a second bandpass filter tuned to the same frequency - // this turns our second-order filter into a 4th-order filter, // which has a steeper rolloff/octave var secondModulatorFilter = audioContext.createBiquadFilter(); secondModulatorFilter.type = "bandpass"; // Bandpass filter secondModulatorFilter.frequency.value = vocoderBands[i].frequency; secondModulatorFilter.Q.value = FILTER_QUALITY; // initial quality modulatorFilter.chainedFilter = secondModulatorFilter; modulatorFilter.connect( secondModulatorFilter ); // create a post-filtering gain to bump the levels up. var modulatorFilterPostGain = audioContext.createGain(); modulatorFilterPostGain.gain.value = 6; secondModulatorFilter.connect( modulatorFilterPostGain ); modFilterPostGains.push( modulatorFilterPostGain ); // Create the sine oscillator for the heterodyne var heterodyneOscillator = audioContext.createOscillator(); heterodyneOscillator.frequency.value = vocoderBands[i].frequency; heterodyneOscillator.start(0); // Create the node to multiply the sine by the modulator var heterodyne = audioContext.createGain(); modulatorFilterPostGain.connect( heterodyne ); heterodyne.gain.value = 0.0; // audio-rate inputs are summed with initial intrinsic value heterodyneOscillator.connect( heterodyne.gain ); var heterodynePostGain = audioContext.createGain(); heterodynePostGain.gain.value = 2.0; // GUESS: boost heterodyne.connect( heterodynePostGain ); heterodynes.push( heterodynePostGain ); // Create the rectifier node var rectifier = audioContext.createWaveShaper(); rectifier.curve = rectifierCurve; heterodynePostGain.connect( rectifier ); // Create the lowpass filter to mask off the difference (near zero) var lpFilter = audioContext.createBiquadFilter(); lpFilter.type = "lowpass"; // Lowpass filter lpFilter.frequency.value = 5.0; // Guesstimate! Mask off 20Hz and above. lpFilter.Q.value = 1; // don't need a peak lpFilters.push( lpFilter ); rectifier.connect( lpFilter ); var lpFilterPostGain = audioContext.createGain(); lpFilterPostGain.gain.value = 1.0; lpFilter.connect( lpFilterPostGain ); lpFilterPostGains.push( lpFilterPostGain ); var waveshaper = audioContext.createWaveShaper(); waveshaper.curve = waveShaperCurve; lpFilterPostGain.connect( waveshaper ); // create an analyser to drive the vocoder band drawing var analyser = audioContext.createAnalyser(); analyser.fftSize = 128; //small, shouldn't matter waveshaper.connect(analyser); bandAnalysers.push( analyser ); // Create the bandpass filter in the carrier chain var carrierFilter = audioContext.createBiquadFilter(); carrierFilter.type = "bandpass"; carrierFilter.frequency.value = vocoderBands[i].frequency; carrierFilter.Q.value = FILTER_QUALITY; carrierBands.push( carrierFilter ); carrierInput.connect( carrierFilter ); // We want our carrier filters to be 4th-order filter too. var secondCarrierFilter = audioContext.createBiquadFilter(); secondCarrierFilter.type = "bandpass"; // Bandpass filter secondCarrierFilter.frequency.value = vocoderBands[i].frequency; secondCarrierFilter.Q.value = FILTER_QUALITY; // initial quality carrierFilter.chainedFilter = secondCarrierFilter; carrierFilter.connect( secondCarrierFilter ); var carrierFilterPostGain = audioContext.createGain(); carrierFilterPostGain.gain.value = 10.0; secondCarrierFilter.connect( carrierFilterPostGain ); carrierFilterPostGains.push( carrierFilterPostGain ); // Create the carrier band gain node var bandGain = audioContext.createGain(); carrierBandGains.push( bandGain ); carrierFilterPostGain.connect( bandGain ); bandGain.gain.value = 0.0; // audio-rate inputs are summed with initial intrinsic value waveshaper.connect( bandGain.gain ); // connect the lp controller bandGain.connect( outputGain ); } addSingleValueSlider( "hi-pass gain", hpFilterGain.gain.value, 0.0, 1.0, hpFilterGain, updateSingleGain ); addSingleValueSlider( "hi-pass freq", hpFilter.frequency.value, 4000, 10000.0, hpFilter, updateSingleFrequency ); addSingleValueSlider( "hi-pass Q", hpFilter.Q.value, 1, 50.0, hpFilter, updateSingleQ ); addColumnSlider( "mod filter Q", modFilterBands[0].Q.value, 1.0, 20.0, modFilterBands, updateQs ); addColumnSlider( "mod filter post gain", modFilterPostGains[0].gain.value, 1.0, 20.0, modFilterPostGains, updateGains ); addColumnSlider( "heterodyne post gain", heterodynes[0].gain.value, 1.0, 8.0, heterodynes, updateGains ); addColumnSlider( "lp filter Q", lpFilters[0].Q.value, 1.0, 100.0, lpFilters, updateQs ); addColumnSlider( "lp filter frequency", lpFilters[0].frequency.value, 1.0, 100.0, lpFilters, updateFrequencies ); addColumnSlider( "lp filter post gain", lpFilterPostGains[0].gain.value, 1.0, 10.0, lpFilterPostGains, updateGains ); addSingleValueSlider( "carrier input gain", carrierInput.gain.value, 0.0, 10.0, carrierInput, updateSingleGain ); addColumnSlider( "carrier filter Q", carrierBands[0].Q.value, 1.0, 20.0, carrierBands, updateQs ); addColumnSlider( "carrier filter post gain", carrierFilterPostGains[0].gain.value, 1.0, 20.0, carrierFilterPostGains, updateGains ); addSingleValueSlider( "output gain", outputGain.gain.value, 0.0, 10.0, outputGain, updateSingleGain ); modulatorInput.connect( analyser1 ); outputGain.connect( analyser2 ); // Now set up our wavetable stuff. var real = new Float32Array(FOURIER_SIZE); var imag = new Float32Array(FOURIER_SIZE); real[0] = 0.0; imag[0] = 0.0; for (var i=1; i<FOURIER_SIZE; i++) { real[i]=1.0; imag[i]=1.0; } wavetable = (audioContext.createPeriodicWave) ? audioContext.createPeriodicWave(real, imag) : audioContext.createWaveTable(real, imag); loadNoiseBuffer(); } function setupVocoderGraph() { initBandpassFilters(); } function drawVocoderGains() { vocoderCanvas.clearRect(0, 0, CANVAS_WIDTH, GAINS_CANVAS_HEIGHT); vocoderCanvas.fillStyle = '#F6D565'; vocoderCanvas.lineCap = 'round'; var binWidth = (CANVAS_WIDTH / numVocoderBands); var value; var sample = new Uint8Array(1); // should only need one sample // Draw rectangle for each vocoder bin. for (var i = 0; i < numVocoderBands; i++) { vocoderCanvas.fillStyle = "hsl( " + Math.round((i*360)/numVocoderBands) + ", 100%, 50%)"; bandAnalysers[i].getByteTimeDomainData(sample); value = ((1.0 * sample[0]) - 128.0) / 64; vocoderCanvas.fillRect(i * binWidth, GAINS_CANVAS_HEIGHT, binWidth, -value * GAINS_CANVAS_HEIGHT ); } } function drawFreqAnalysis( analyser, canvas ) { canvas.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT); var numBins = analyser.frequencyBinCount; numBins = numBins /4; // this is JUST to drop the top half of the frequencies - they're not interesting. var binWidth = (CANVAS_WIDTH / numBins); var bins = new Uint8Array(numBins); var SCALAR = CANVAS_HEIGHT/256; analyser.getByteFrequencyData(bins); // Draw rectangle for each vocoder bin. for (var i = 0; i < numBins; i++) { canvas.fillStyle = "hsl( " + Math.round((i*360)/numBins) + ", 100%, 50%)"; canvas.fillRect(i * binWidth, CANVAS_HEIGHT, binWidth, -bins[i]*SCALAR ); } } var rafID = null; function cancelVocoderUpdates() { window.cancelAnimationFrame( rafID ); rafID = null; } function updateAnalysers(time) { if (cheapAnalysis) { drawFreqAnalysis( analyser1, analyserView1 ); drawFreqAnalysis( analyser2, analyserView2 ); } else { analyserView1.doFrequencyAnalysis( analyser1 ); analyserView2.doFrequencyAnalysis( analyser2 ); } drawVocoderGains(); rafID = window.requestAnimationFrame( updateAnalysers ); } function createCarriersAndPlay( output ) { carrierSampleNode = audioContext.createBufferSource(); carrierSampleNode.buffer = carrierBuffer; carrierSampleNode.loop = true; carrierSampleGain = audioContext.createGain(); carrierSampleGain.gain.value = carrierSampleGainValue; carrierSampleNode.connect( carrierSampleGain ); carrierSampleGain.connect( output ); // The wavetable signal needs a boost. wavetableSignalGain = audioContext.createGain(); oscillatorNode = audioContext.createOscillator(); if (oscillatorType = 4) { // wavetable oscillatorNode.setPeriodicWave ? oscillatorNode.setPeriodicWave(wavetable) : oscillatorNode.setWaveTable(wavetable); wavetableSignalGain.gain.value = WAVETABLEBOOST; } else { oscillatorNode.type = oscillatorType; wavetableSignalGain.gain.value = SAWTOOTHBOOST; } oscillatorNode.frequency.value = 110; oscillatorNode.detune.value = oscillatorDetuneValue; oscillatorNode.connect(wavetableSignalGain); oscillatorGain = audioContext.createGain(); oscillatorGain.gain.value = oscillatorGainValue; wavetableSignalGain.connect(oscillatorGain); oscillatorGain.connect(output); noiseNode = audioContext.createBufferSource(); noiseNode.buffer = noiseBuffer; noiseNode.loop = true; noiseGain = audioContext.createGain(); noiseGain.gain.value = noiseGainValue; noiseNode.connect(noiseGain); noiseGain.connect(output); oscillatorNode.start(0); noiseNode.start(0); carrierSampleNode.start(0); } function vocode() { if (this.event) this.event.preventDefault(); if (vocoding) { if (modulatorNode) modulatorNode.stop(0); shutOffCarrier(); vocoding = false; liveInput = false; cancelVocoderUpdates(); if (endOfModulatorTimer) window.clearTimeout(endOfModulatorTimer); endOfModulatorTimer = 0; return; } else if (document.getElementById("carrierpreview").classList.contains("playing") ) finishPreviewingCarrier(); else if (document.getElementById("modulatorpreview").classList.contains("playing") ) finishPreviewingModulator(); createCarriersAndPlay( carrierInput ); vocoding = true; modulatorNode = audioContext.createBufferSource(); modulatorNode.buffer = modulatorBuffer; modulatorGain = audioContext.createGain(); modulatorGain.gain.value = modulatorGainValue; modulatorNode.connect( modulatorGain ); modulatorGain.connect( modulatorInput ); modulatorNode.start(0); window.requestAnimationFrame( updateAnalysers ); endOfModulatorTimer = window.setTimeout( vocode, modulatorNode.buffer.duration * 1000 + 20 ); } function error() { alert('Stream generation failed.'); } function getUserMedia(dictionary, callback) { try { if (!navigator.getUserMedia) navigator.getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia; navigator.getUserMedia(dictionary, callback, error); } catch (e) { alert('getUserMedia threw exception :' + e); } } function convertToMono( input ) { var splitter = audioContext.createChannelSplitter(2); var merger = audioContext.createChannelMerger(2); input.connect( splitter ); splitter.connect( merger, 0, 0 ); splitter.connect( merger, 0, 1 ); return merger; } function generateNoiseFloorCurve( floor ) { // "floor" is 0...1 var curve = new Float32Array(65536); var mappedFloor = floor * 32768; for (var i=0; i<32768; i++) { var value = (i<mappedFloor) ? 0 : 1; curve[32768-i] = -value; curve[32768+i] = value; } curve[0] = curve[1]; // fixing up the end. return curve; } function createNoiseGate( connectTo ) { var inputNode = audioContext.createGain(); var rectifier = audioContext.createWaveShaper(); var ngFollower = audioContext.createBiquadFilter(); ngFollower.type = ngFollower.LOWPASS; ngFollower.frequency.value = 10.0; var curve = new Float32Array(65536); for (var i=-32768; i<32768; i++) curve[i+32768] = ((i>0)?i:-i)/32768; rectifier.curve = curve; rectifier.connect(ngFollower); var ngGate = audioContext.createWaveShaper(); ngGate.curve = generateNoiseFloorCurve(0.01); ngFollower.connect(ngGate); var gateGain = audioContext.createGain(); gateGain.gain.value = 0.0; ngGate.connect( gateGain.gain ); gateGain.connect( connectTo ); inputNode.connect(rectifier); inputNode.connect(gateGain); return inputNode; } var lpInputFilter=null; // this is ONLY because we have massive feedback without filtering out // the top end in live speaker scenarios. function createLPInputFilter(output) { lpInputFilter = audioContext.createBiquadFilter(); lpInputFilter.connect(output); lpInputFilter.frequency.value = 2048; return lpInputFilter; } var liveInput = false; function gotStream(stream) { // Create an AudioNode from the stream. var mediaStreamSource = audioContext.createMediaStreamSource(stream); modulatorGain = audioContext.createGain(); modulatorGain.gain.value = modulatorGainValue; modulatorGain.connect( modulatorInput ); // make sure the source is mono - some sources will be left-side only var monoSource = convertToMono( mediaStreamSource ); //create a noise gate monoSource.connect( createLPInputFilter( createNoiseGate( modulatorGain ) ) ); createCarriersAndPlay( carrierInput ); vocoding = true; liveInput = true; window.requestAnimationFrame( updateAnalysers ); } function useLiveInput() { if (vocoding) { if (modulatorNode) modulatorNode.stop(0); shutOffCarrier(); vocoding = false; cancelVocoderUpdates(); if (endOfModulatorTimer) window.clearTimeout(endOfModulatorTimer); endOfModulatorTimer = 0; } else if (document.getElementById("carrierpreview").classList.contains("playing") ) finishPreviewingCarrier(); else if (document.getElementById("modulatorpreview").classList.contains("playing") ) finishPreviewingModulator(); getUserMedia( { "audio": { "mandatory": { "googEchoCancellation": "false", "googAutoGainControl": "false", "googNoiseSuppression": "false", "googHighpassFilter": "false" }, "optional": [] }, }, gotStream); } window.addEventListener('keydown', function(ev) { var centOffset; switch (ev.keyCode) { case 'A'.charCodeAt(0): centOffset = -700; break; case 'W'.charCodeAt(0): centOffset = -600; break; case 'S'.charCodeAt(0): centOffset = -500; break; case 'E'.charCodeAt(0): centOffset = -400; break; case 'D'.charCodeAt(0): centOffset = -300; break; case 'R'.charCodeAt(0): centOffset = -200; break; case 'F'.charCodeAt(0): centOffset = -100; break; case 'G'.charCodeAt(0): centOffset = 0; break; case 'Y'.charCodeAt(0): centOffset = 100; break; case 'H'.charCodeAt(0): centOffset = 200; break; case 'U'.charCodeAt(0): centOffset = 300; break; case 'J'.charCodeAt(0): centOffset = 400; break; case 'K'.charCodeAt(0): centOffset = 500; break; case 'O'.charCodeAt(0): centOffset = 600; break; case 'L'.charCodeAt(0): centOffset = 700; break; case 'P'.charCodeAt(0): centOffset = 800; break; case 186: // ; centOffset = 900; break; case 219: // [ centOffset = 1000; break; case 222: // ' centOffset = 1100; break; default: return; } var detunegroup = document.getElementById("detunegroup"); $( detunegroup.children[1] ).slider( "value", centOffset ); updateSlider( detunegroup, centOffset, " cents" ); if (oscillatorNode) oscillatorNode.detune.value = centOffset; }, false); <|start_filename|>css/main.css<|end_filename|> /* main.css */ /* --------------------------------------------------------------------------- * :: Type * * - Fonts * - Base * - Links * -------------------------------------------------------------------------*/ .notready h6 { background: red; } div.link { font-style: italic; color: lightgrey; margin-left: 780px; margin-top: 5px; } #mobile { display: none; margin-left: 1em; color: lightgrey;} div.link a { color: white; font: inherit; text-decoration: underline; } /* Fonts */ @font-face { font-family: 'ProximaNovaRgRegular'; src: url('../fonts/proxima_nova_reg-webfont.eot'); src: url('../fonts/proxima_nova_reg-webfont.eot?#iefix') format('embedded-opentype'), url('../fonts/proxima_nova_reg-webfont.woff') format('woff'), url('../fonts/proxima_nova_reg-webfont.ttf') format('truetype'), url('../fonts/proxima_nova_reg-webfont.svg#ProximaNovaRgRegular') format('svg'); font-weight: normal; font-style: normal; } /* Base */ html, button, input, select, textarea { font-family: 'ProximaNovaRgRegular', 'Helvetica Neue', Helvetica, Arial, sans-serif; color: #4c4c4c; } body { font-size: 1em; line-height: 1.4; } /* Links */ a, a:visited { color: #4c4c4c; font-size: .6875em; /* 11 / 16 */ text-decoration: none; } a:hover { color: #000; text-decoration: none; } /* --------------------------------------------------------------------------- * :: Raw elements * -------------------------------------------------------------------------*/ body { background: url('../img/body-bkg.gif'); } /* --------------------------------------------------------------------------- * :: Main * * - Header * -------------------------------------------------------------------------*/ #main { position: relative; z-index: 1; } /* Header */ #header { margin: 0; padding: 1em 0 0 1em; } #footer { margin: 0; padding: 0;} /* --------------------------------------------------------------------------- * :: Modules * * - Controls * - Dropdown * - Dropdown arrow * - Modules * -------------------------------------------------------------------------*/ #modules { display: inline; float: left; margin: 0 0 0 18px; padding: 20px 0 0; width: 200px; } /* Module */ .module { border-radius: 5px; box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); display: inline-block; position: relative; } .module .content { background: #fff; border-radius: 5px; min-width: 10em; overflow: hidden; padding: 1.25em; position: relative; } .module.has-footer .content { border-bottom: 1px solid #dbdbdb; border-radius: 5px 5px 0 0; } .module h6 { font-size: 1.375em; font-weight: normal; margin: 0 0 .2em; text-align: center; text-transform: uppercase; } .module.audio-buffer-source .ico-play, .module.audio-buffer-source .ico-stop { display: none; } .module.audio-buffer-source.play .ico-play { display: block; } .module.audio-buffer-source.stop .ico-stop { display: block; } /* Module footer */ .module footer { background-color: #fff; background-image: -webkit-linear-gradient(top, rgb(255, 255, 255), rgb(219, 219, 219)); background-image: linear-gradient(top, rgb(255, 255, 255), rgb(219, 219, 219)); border-radius: 0 0 5px 5px; overflow: hidden; padding: 0; } .module footer a { display: inline; float: left; padding: .75em 0; text-align: center; text-transform: uppercase; width: 100px; } .module footer a:hover, .module footer a.active { background: #d4d4d4; box-shadow: inset 1px 1px 1px rgba(0,0,0,.2); } .module footer a.left { border-right: 1px solid #dbdbdb; width: 99px; } .module footer a.top { border-bottom: 1px solid #dbdbdb; } /* Control group */ .control-group { margin: 0 0 1em; } .control-group.last { margin: 0; } /* Slider */ .slider-info { font-size: .625em; /* 10 / 16 */ margin-bottom: 0 0 1em; overflow: hidden; padding-bottom: .4em; position: relative; } .slider-info .label { display: inline; float: left; text-transform: uppercase; width: 49%; } .slider-info .value { display: inline; float: right; font-weight: bold; text-align: right; text-transform: uppercase; width: 49%; } .module .slider-info:last-child { margin-bottom: 0; } .ui-slider { background: url('../img/slider-bkg.gif') 0 0 repeat-x; border: 0 none; color: #fff; height: 11px; position: relative; text-align: left; } .ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default { border: 1px solid #cccccc; background: #f6f6f6; font-weight: bold; color: #1c94c4; } .ui-slider .ui-slider-handle { background: url('../img/slider-handle.png') 0 1px no-repeat; border: 0 none; cursor: default; height: 18px; margin-left: -.6em; position: absolute; top: -.3em; width: 16px; z-index: 2; } .ui-slider .ui-slider-range { background-position: 0 0; border: 0; display: block; font-size: .7em; height: 100%; position: absolute; top: 0; z-index: 1; } .ui-slider .ui-slider-range-min { left: 0; } .ui-slider .ui-slider-range-max { right: 0; } /* Preview link */ .preview-link { color: #c2c2c2; display: block; padding: 2em 0 0; text-align: center; text-transform: uppercase; } .preview-link img { display: inline-block; width: 9px; height: 11px; line-height: 11px; margin-right: 3px; vertical-align: text-top; } /* Module close */ .module .preview { height: 11px; position: absolute; right: 8px; top: 8px; width: 11px; } .module .preview:hover { opacity: .8 } /* Specific modules */ .module.modulator { margin-bottom: 1.875em; } /* --------------------------------------------------------------------------- * :: Connection * -------------------------------------------------------------------------*/ #connection { display: inline; float: left; padding-top: 87px; width: 152px; } #play { background: url('../img/play.png') 0 0 no-repeat; display: block; height: 299px; text-indent: -999em; width: 152px; } #play:hover { background-position: -152px 0; } #record { width: 64px; height: 64px; margin: 20px auto 10px; display: block; } #record.recording { abackground: red; background: -webkit-radial-gradient(center, ellipse cover, #ff0000 0%,transparent 75%,transparent 100%,transparent 100%); background: -moz-radial-gradient(center, ellipse cover, #ff0000 0%,transparent 75%,transparent 100%,transparent 100%); background: radial-gradient(center, ellipse cover, #ff0000 0%,transparent 75%,transparent 100%,transparent 100%); } #recfile { color: lightblue; display: block; text-align: center; } /* --------------------------------------------------------------------------- * :: Results * -------------------------------------------------------------------------*/ #results { display: inline; float: left; width: 590px; position: relative; margin-top:15px; } #results h2 { color: #fff; font-size: 1.375em; font-weight: normal; margin: 0; text-align: center; text-transform: uppercase; position: absolute; right: 10px; } #result-top, #result-middle { margin: 0 0 1.875em; } #result-top, #result-middle, #result-bottom { box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); background-image: url('../img/analyser-bg.png'); border-radius: 8px; overflow: hidden; } #result-top canvas, #result-middle canvas, #result-bottom canvas { width:582px; margin-left: 4px; margin-top: 4px; margin-bottom: -2px; } #modulator.droptarget, #carrier.droptarget { outline: 1px solid red; opacity: 0.5;} /* --------------------------------------------------------------------------- * :: Global classes and styles * * - Clearfix * -------------------------------------------------------------------------*/ /* Clearfix */ .container:before, .container:after { content: ""; display: table; } .container:after { clear: both; } .container { *zoom: 1; } <|start_filename|>js/midi.js<|end_filename|> /* * Copyright (c) 2012 The Chromium Authors. 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. */ function midiMessageReceived( e ) { var cmd = e.data[0] >> 4; var channel = e.data[0] & 0xf; var b = e.data[1]; var c = e.data[2]; if ( cmd==8 || ((cmd==9)&&(c==0)) ) { // with MIDI, note on with velocity zero is the same as note off // if (b == lastNote) { // this keeps from shutting off if we're overlapping notes // we don't currently need note off // lastNote = -1; // } } else if (cmd == 9) { // note on message if (channel == 0 ) { // Change oscillator detune. var noteNumber = b - 60; var detuneValue = noteNumber * 100; var detunegroup = document.getElementById("detunegroup"); $( detunegroup.children[1] ).slider( "value", detuneValue ); updateSlider( detunegroup, detuneValue, " cents" ); if (oscillatorNode) oscillatorNode.detune.value = detuneValue; } else if (channel == 1) { //pads - play previews if (b==48) previewModulator(); // is a toggle. else if (b==49) previewCarrier(); // is a toggle. else if (b==44) vocode(); // is a toggle. } } else if (cmd == 11) { // continuous controller switch (b) { case 1: // CC2: "Gender" - tuning frequencies scaleCarrierFilterFrequencies((Math.floor( (100 * c) / 63.5) / 100) + 0.5) // ideally would be 0.5 - 2.0, centered on 1. break; case 71: case 2: // CC1: Modulator gain level var value = Math.floor( (100 * c) / 63.5) / 50; // 0.0-4.0 var modgaingroup = document.getElementById("modgaingroup"); $( modgaingroup.children[1] ).slider( "value", value ); updateSlider( modgaingroup, value, "" ); modulatorGainValue = value; if (modulatorGain) modulatorGain.gain.value = value; break; case 74: case 5: // CC5: Carrier sample level var sampleValue = Math.floor( (100 * c) / 63.5) / 100; // 0.0-2.0 var samplegroup = document.getElementById("samplegroup"); $( samplegroup.children[1] ).slider( "value", sampleValue ); updateSlider( samplegroup, sampleValue, "" ); if (carrierSampleGain) carrierSampleGain.gain.value = sampleValue; break; case 10: case 6: // CC6: Carrier synth level var synthValue = Math.floor( (100 * c) / 63.5) / 100; // 0.0-2.0 var synthgroup = document.getElementById("synthgroup"); $( synthgroup.children[1] ).slider( "value", synthValue ); updateSlider( synthgroup, synthValue, "" ); if (oscillatorGain) oscillatorGain.gain.value = synthValue; break; case 7: // CC7: Carrier noise level var noiseValue = Math.floor( (100 * c) / 63.5) / 100; // 0.0-2.0 var noisegroup = document.getElementById("noisegroup"); $( noisegroup.children[1] ).slider( "value", noiseValue ); updateSlider( noisegroup, noiseValue, "" ); if (noiseGain) noiseGain.gain.value = noiseValue; break; case 73: case 8: // CC8: HP filter gain hpFilterGain.gain.value = c / 63.5; // 0.0-1.0 break; default: console.log("Controller " + b + " received: " + c ); } } } //init: create plugin window.addEventListener('load', function() { navigator.requestMIDIAccess().then( gotMIDI, didntGetMIDI ); } ); var midi = null; var midiIn = null; function gotMIDI( midiAccess ) { midi = midiAccess; if ((typeof(midiAccess.inputs) == "function")) { //Old Skool MIDI inputs() code var ins = midiAccess.inputs(); for (var i=0; i<ins.length; i++) ins[i].onmidimessage = midiMessageReceived; } else { var inputs=midiAccess.inputs.values(); for ( var input = inputs.next(); input && !input.done; input = inputs.next()) input.value.onmidimessage = midiMessageReceived; } } function didntGetMIDI( error ) { console.log("No MIDI access: " + error.code ); } <|start_filename|>js/ui.js<|end_filename|> /* ui.js */ (function($, w) { 'use strict'; // Ready $(function() { $('.slider').slider(); }); })(jQuery, window);
elliotfiske/Vocoder
<|start_filename|>screens/Components.js<|end_filename|> import React from 'react'; import { ScrollView, StyleSheet, TouchableOpacity, Image, ImageBackground, Dimensions } from 'react-native'; import { Button, Block, Text, Input, theme } from 'galio-framework'; import { materialTheme, products, Images } from '../constants/'; import { Select, Icon, Header, Product, Switch } from '../components/'; const { width } = Dimensions.get('screen'); const thumbMeasure = (width - 48 - 32) / 3; export default class Components extends React.Component { state = { 'switch-1': true, 'switch-2': false, }; toggleSwitch = switchId => this.setState({ [switchId]: !this.state[switchId] }); renderButtons = () => { return ( <Block flex> <Text bold size={16} style={styles.title}>Buttons</Text> <Block style={{ paddingHorizontal: theme.SIZES.BASE }}> <Block center> <Button shadowless color={materialTheme.COLORS.DEFAULT} style={[styles.button, styles.shadow]}> DEFAULT </Button> </Block> <Block center> <Button shadowless style={[styles.button, styles.shadow]}> PRIMARY </Button> </Block> <Block center> <Button shadowless color="info" style={[styles.button, styles.shadow]}> INFO </Button> </Block> <Block center> <Button shadowless color="success" style={[styles.button, styles.shadow]}> SUCCESS </Button> </Block> <Block center> <Button shadowless color="warning" style={[styles.button, styles.shadow]}> WARNING </Button> </Block> <Block center> <Button shadowless color="danger" style={[styles.button, styles.shadow]}> ERROR </Button> </Block> <Block row space="evenly"> <Block flex left style={{marginTop: 8}}> <Select defaultIndex={1} options={[1, 2, 3, 4, 5]} style={styles.shadow} /> </Block> <Block flex center> <Button center shadowless color={materialTheme.COLORS.DEFAULT} textStyle={styles.optionsText} style={[styles.optionsButton, styles.shadow]}> DELETE </Button> </Block> <Block flex={1.25} right> <Button center shadowless color={materialTheme.COLORS.DEFAULT} textStyle={styles.optionsText} style={[styles.optionsButton, styles.shadow]}> SAVE FOR LATER </Button> </Block> </Block> </Block> </Block> ) } renderText = () => { return ( <Block flex style={styles.group}> <Text bold size={16} style={styles.title}>Typography</Text> <Block style={{ paddingHorizontal: theme.SIZES.BASE }}> <Text h1 style={{marginBottom: theme.SIZES.BASE / 2}}>Heading 1</Text> <Text h2 style={{marginBottom: theme.SIZES.BASE / 2}}>Heading 2</Text> <Text h3 style={{marginBottom: theme.SIZES.BASE / 2}}>Heading 3</Text> <Text h4 style={{marginBottom: theme.SIZES.BASE / 2}}>Heading 4</Text> <Text h5 style={{marginBottom: theme.SIZES.BASE / 2}}>Heading 5</Text> <Text p style={{marginBottom: theme.SIZES.BASE / 2}}>Paragraph</Text> <Text muted>This is a muted paragraph.</Text> </Block> </Block> ) } renderInputs = () => { return ( <Block flex style={styles.group}> <Text bold size={16} style={styles.title}>Inputs</Text> <Block style={{ paddingHorizontal: theme.SIZES.BASE }}> <Input right placeholder="icon right" placeholderTextColor={materialTheme.COLORS.DEFAULT} style={{ borderRadius: 3, borderColor: materialTheme.COLORS.INPUT }} iconContent={<Icon size={16} color={theme.COLORS.ICON} name="camera-18" family="GalioExtra" />} /> </Block> </Block> ) } renderSwitches = () => { return ( <Block flex style={styles.group}> <Text bold size={16} style={styles.title}>Switches</Text> <Block style={{ paddingHorizontal: theme.SIZES.BASE }}> <Block row middle space="between" style={{ marginBottom: theme.SIZES.BASE }}> <Text size={14}>Switch is ON</Text> <Switch value={this.state['switch-1']} onValueChange={() => this.toggleSwitch('switch-1')} /> </Block> <Block row middle space="between"> <Text size={14}>Switch is OFF</Text> <Switch value={this.state['switch-2']} onValueChange={() => this.toggleSwitch('switch-2')} /> </Block> </Block> </Block> ) } renderTableCell = () => { const { navigation } = this.props; return ( <Block flex style={styles.group}> <Text bold size={16} style={styles.title}>Table Cell</Text> <Block style={{ paddingHorizontal: theme.SIZES.BASE }}> <Block style={styles.rows}> <TouchableOpacity onPress={() => navigation.navigate('Pro')}> <Block row middle space="between" style={{ paddingTop: 7 }}> <Text size={14}>Manage Options</Text> <Icon name="angle-right" family="font-awesome" style={{ paddingRight: 5 }} /> </Block> </TouchableOpacity> </Block> </Block> </Block> ) } renderNavigation = () => { return ( <Block flex style={styles.group}> <Text bold size={16} style={styles.title}>Navigation</Text> <Block> <Block style={{ marginBottom: theme.SIZES.BASE }}> <Header back title="Title" navigation={this.props.navigation} /> </Block> <Block style={{ marginBottom: theme.SIZES.BASE }}> <Header search title="Title" navigation={this.props.navigation} /> </Block> <Block style={{ marginBottom: theme.SIZES.BASE }}> <Header tabs search title="Title" tabTitleLeft="Option 1" tabTitleRight="Option 2" navigation={this.props.navigation} /> </Block> </Block> </Block> ) } renderSocial = () => { return ( <Block flex style={styles.group}> <Text bold size={16} style={styles.title}>Social</Text> <Block style={{ paddingHorizontal: theme.SIZES.BASE }}> <Block row center space="between"> <Block flex middle right> <Button round onlyIcon shadowless icon="facebook" iconFamily="font-awesome" iconColor={theme.COLORS.WHITE} iconSize={theme.SIZES.BASE * 1.625} color={theme.COLORS.FACEBOOK} style={[styles.social, styles.shadow]} /> </Block> <Block flex middle center> <Button round onlyIcon shadowless icon="twitter" iconFamily="font-awesome" iconColor={theme.COLORS.WHITE} iconSize={theme.SIZES.BASE * 1.625} color={theme.COLORS.TWITTER} style={[styles.social, styles.shadow]} /> </Block> <Block flex middle left> <Button round onlyIcon shadowless icon="dribbble" iconFamily="font-awesome" iconColor={theme.COLORS.WHITE} iconSize={theme.SIZES.BASE * 1.625} color={theme.COLORS.DRIBBBLE} style={[styles.social, styles.shadow]} /> </Block> </Block> </Block> </Block> ) } renderCards = () => { return ( <Block flex style={styles.group}> <Text bold size={16} style={styles.title}>Cards</Text> <Block flex> <Block style={{ paddingHorizontal: theme.SIZES.BASE }}> <Product product={products[0]} horizontal /> <Block flex row> <Product product={products[1]} style={{ marginRight: theme.SIZES.BASE }} /> <Product product={products[2]} /> </Block> <Product product={products[3]} horizontal /> <Product product={products[4]} full /> <Block flex card shadow style={styles.category}> <ImageBackground source={{ uri: Images.Products['Accessories'] }} style={[styles.imageBlock, { width: width - (theme.SIZES.BASE * 2), height: 252 }]} imageStyle={{ width: width - (theme.SIZES.BASE * 2), height: 252 }}> <Block style={styles.categoryTitle}> <Text size={18} bold color={theme.COLORS.WHITE}>Accessories</Text> </Block> </ImageBackground> </Block> </Block> </Block> </Block> ) } renderAlbum = () => { const { navigation } = this.props; return ( <Block flex style={[styles.group, { paddingBottom: theme.SIZES.BASE * 5 }]}> <Text bold size={16} style={styles.title}>Album</Text> <Block style={{ marginHorizontal: theme.SIZES.BASE * 2 }}> <Block flex right> <Text size={12} color={theme.COLORS.PRIMARY} onPress={() => navigation.navigate('Home')}> View All </Text> </Block> <Block row space="between" style={{ marginTop: theme.SIZES.BASE, flexWrap: 'wrap' }} > {Images.Viewed.map((img, index) => ( <Block key={`viewed-${img}`} style={styles.shadow}> <Image resizeMode="cover" source={{ uri: img }} style={styles.albumThumb} /> </Block> ))} </Block> </Block> </Block> ) } render() { return ( <Block flex center> <ScrollView style={styles.components} showsVerticalScrollIndicator={false}> {this.renderButtons()} {this.renderText()} {this.renderInputs()} {this.renderSwitches()} {this.renderTableCell()} {this.renderNavigation()} {this.renderSocial()} {this.renderCards()} {this.renderAlbum()} </ScrollView> </Block> ); } } const styles = StyleSheet.create({ components: { width: width }, title: { paddingVertical: theme.SIZES.BASE, paddingHorizontal: theme.SIZES.BASE * 2, }, group: { paddingTop: theme.SIZES.BASE * 3.75, }, shadow: { shadowColor: 'black', shadowOffset: { width: 0, height: 2 }, shadowRadius: 4, shadowOpacity: 0.2, elevation: 2, }, button: { marginBottom: theme.SIZES.BASE, width: width - (theme.SIZES.BASE * 2), }, optionsText: { fontSize: theme.SIZES.BASE * 0.75, color: '#4A4A4A', fontWeight: "normal", fontStyle: "normal", letterSpacing: -0.29, }, optionsButton: { width: 'auto', height: 34, paddingHorizontal: theme.SIZES.BASE, paddingVertical: 10, }, imageBlock: { overflow: 'hidden', borderRadius: 4, }, rows: { height: theme.SIZES.BASE * 2, }, social: { width: theme.SIZES.BASE * 3.5, height: theme.SIZES.BASE * 3.5, borderRadius: theme.SIZES.BASE * 1.75, justifyContent: 'center', }, category: { backgroundColor: theme.COLORS.WHITE, marginVertical: theme.SIZES.BASE / 2, borderWidth: 0, }, categoryTitle: { height: '100%', paddingHorizontal: theme.SIZES.BASE, backgroundColor: 'rgba(0, 0, 0, 0.5)', justifyContent: 'center', alignItems: 'center', }, albumThumb: { borderRadius: 4, marginVertical: 4, alignSelf: 'center', width: thumbMeasure, height: thumbMeasure }, });
Nicca42/NewsBuff-v2.0
<|start_filename|>jsonrpc.go<|end_filename|> package jsonrpc import "encoding/json" const ( SupportedVersion = "2.0" InvalidRequest = -32600 MethodNotFound = -32601 InvalidParams = -32602 InternalError = -32603 ParseError = -32700 ) var ( InternalErrorTemplate = `{"jsonrpc":"2.0","error":{"code":-32603,"message":"%s"},"id": null}` DefaultInternalError = []byte(`{"jsonrpc":"2.0","error":{"code":-32603,"message":"Internal Error"},"id": null}`) ) type ( Proxy interface { Encode(Response) } // Method for JSONRPC requests Method interface { Process(json.RawMessage) (json.Marshaler, *Error) } // Handler for JSONRPC notifications Handler interface { Process(json.RawMessage) } // Callback for JSONRPC response callback Callback interface { Process(Response) } ) // Dispatcher holds RPC call routing implementation type Dispatcher interface { DispatchResponse(Response) DispatchNotification(Request) DispatchRequest(Request, Responder) }
gopaws/go.jsonrpc
<|start_filename|>service/service_account.go<|end_filename|> package service import ( "context" "fmt" "github.com/coinbase/rosetta-sdk-go/server" "github.com/coinbase/rosetta-sdk-go/types" ethcommon "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" "github.com/ava-labs/avalanche-rosetta/client" "github.com/ava-labs/avalanche-rosetta/mapper" "github.com/ava-labs/coreth/interfaces" ) // AccountService implements the /account/* endpoints type AccountService struct { config *Config client client.Client } // NewAccountService returns a new network servicer func NewAccountService(config *Config, client client.Client) server.AccountAPIServicer { return &AccountService{ config: config, client: client, } } // AccountBalance implements the /account/balance endpoint func (s AccountService) AccountBalance( ctx context.Context, req *types.AccountBalanceRequest, ) (*types.AccountBalanceResponse, *types.Error) { if s.config.IsOfflineMode() { return nil, errUnavailableOffline } if req.AccountIdentifier == nil { return nil, wrapError(errInvalidInput, "account identifier is not provided") } header, err := blockHeaderFromInput(s.client, req.BlockIdentifier) if err != nil { return nil, wrapError(errInternalError, err) } address := ethcommon.HexToAddress(req.AccountIdentifier.Address) nonce, nonceErr := s.client.NonceAt(ctx, address, header.Number) if nonceErr != nil { return nil, wrapError(errClientError, nonceErr) } metadata := &accountMetadata{ Nonce: nonce, } metadataMap, metadataErr := marshalJSONMap(metadata) if err != nil { return nil, wrapError(errInternalError, metadataErr) } avaxBalance, balanceErr := s.client.BalanceAt(context.Background(), address, header.Number) if balanceErr != nil { return nil, wrapError(errInternalError, balanceErr) } var balances []*types.Amount if len(req.Currencies) == 0 { balances = append(balances, mapper.AvaxAmount(avaxBalance)) } for _, currency := range req.Currencies { value, ok := currency.Metadata[mapper.ContractAddressMetadata] if !ok { if types.Hash(currency) == types.Hash(mapper.AvaxCurrency) { balances = append(balances, mapper.AvaxAmount(avaxBalance)) continue } return nil, wrapError(errCallInvalidParams, fmt.Errorf("currencies outside of avax must have contractAddress in metadata field")) } if s.config.IsStandardMode() && !mapper.EqualFoldContains(s.config.TokenWhiteList, value.(string)) { return nil, wrapError(errCallInvalidParams, fmt.Errorf("only addresses contained in token whitelist are supported")) } identifierAddress := req.AccountIdentifier.Address if has0xPrefix(identifierAddress) { identifierAddress = identifierAddress[2:42] } data, err := hexutil.Decode(BalanceOfMethodPrefix + identifierAddress) if err != nil { return nil, wrapError(errCallInvalidParams, fmt.Errorf("failed to decode contractAddress in metadata field")) } contractAddress := ethcommon.HexToAddress(value.(string)) callMsg := interfaces.CallMsg{To: &contractAddress, Data: data} response, err := s.client.CallContract(ctx, callMsg, header.Number) if err != nil { return nil, wrapError(errInternalError, err) } amount := mapper.Erc20Amount(response, contractAddress, currency.Symbol, uint8(currency.Decimals), false) balances = append(balances, amount) } resp := &types.AccountBalanceResponse{ BlockIdentifier: &types.BlockIdentifier{ Index: header.Number.Int64(), Hash: header.Hash().String(), }, Balances: balances, Metadata: metadataMap, } return resp, nil } // AccountCoins implements the /account/coins endpoint func (s AccountService) AccountCoins( ctx context.Context, req *types.AccountCoinsRequest, ) (*types.AccountCoinsResponse, *types.Error) { if s.config.IsOfflineMode() { return nil, errUnavailableOffline } return nil, errNotImplemented } <|start_filename|>mapper/address_test.go<|end_filename|> package mapper import ( "strings" "testing" ethcommon "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/assert" ) func TestAdress(t *testing.T) { t.Run("ConvertEVMTopicHashToAddress", func(t *testing.T) { addressString := "0x54761841b2005ee456ba5a5a46ee78dded90b16d" hash := ethcommon.HexToHash(addressString) convertedAddress := ConvertEVMTopicHashToAddress(&hash) assert.Equal(t, strings.ToLower(addressString), strings.ToLower(convertedAddress.String())) }) } <|start_filename|>service/service_construction_test.go<|end_filename|> package service import ( "context" "encoding/hex" "encoding/json" "math/big" "testing" "github.com/ava-labs/avalanche-rosetta/mapper" mocks "github.com/ava-labs/avalanche-rosetta/mocks/client" "github.com/ava-labs/coreth/interfaces" "github.com/coinbase/rosetta-sdk-go/types" "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/assert" ) func TestConstructionMetadata(t *testing.T) { service := ConstructionService{ config: &Config{Mode: ModeOnline}, } t.Run("unavailable in offline mode", func(t *testing.T) { service := ConstructionService{ config: &Config{ Mode: ModeOffline, }, } resp, err := service.ConstructionMetadata( context.Background(), &types.ConstructionMetadataRequest{}, ) assert.Nil(t, resp) assert.Equal(t, errUnavailableOffline.Code, err.Code) }) t.Run("requires from address", func(t *testing.T) { resp, err := service.ConstructionMetadata( context.Background(), &types.ConstructionMetadataRequest{}, ) assert.Nil(t, resp) assert.Equal(t, errInvalidInput.Code, err.Code) assert.Equal(t, "from address is not provided", err.Details["error"]) }) } func TestContructionHash(t *testing.T) { service := ConstructionService{} t.Run("no transaction", func(t *testing.T) { resp, err := service.ConstructionHash( context.Background(), &types.ConstructionHashRequest{}, ) assert.Nil(t, resp) assert.Equal(t, errInvalidInput.Code, err.Code) assert.Equal(t, "signed transaction value is not provided", err.Details["error"]) }) t.Run("invalid transaction", func(t *testing.T) { resp, err := service.ConstructionHash(context.Background(), &types.ConstructionHashRequest{ SignedTransaction: "{}", }) assert.Nil(t, resp) assert.Equal(t, errInvalidInput.Code, err.Code) }) t.Run("valid transaction", func(t *testing.T) { signed := `{"nonce":"0x6","gasPrice":"0x6d6e2edc00","gas":"0x5208","to":"0x85ad9d1fcf50b72255e4288dca0ad29f5f509409","value":"0xde0b6b3a7640000","input":"0x","v":"0x150f6","r":"0x64d46cc17cbdbcf73b204a6979172eb3148237ecd369181b105e92b0d7fa49a7","s":"0x285063de57245f532a14b13f605bed047a9d20ebfd0db28e01bc8cc9eaac40ee","hash":"0x92ea9280c1653aa9042c7a4d3a608c2149db45064609c18b270c7c73738e2a46"}` //nolint:lll resp, err := service.ConstructionHash(context.Background(), &types.ConstructionHashRequest{ SignedTransaction: signed, }) assert.Nil(t, err) assert.Equal( t, "0x92ea9280c1653aa9042c7a4d3a608c2149db45064609c18b270c7c73738e2a46", resp.TransactionIdentifier.Hash, ) }) } func TestConstructionDerive(t *testing.T) { service := ConstructionService{} t.Run("no public key", func(t *testing.T) { resp, err := service.ConstructionDerive( context.Background(), &types.ConstructionDeriveRequest{}, ) assert.Nil(t, resp) assert.Equal(t, errInvalidInput.Code, err.Code) assert.Equal(t, "public key is not provided", err.Details["error"]) }) t.Run("invalid public key", func(t *testing.T) { resp, err := service.ConstructionDerive( context.Background(), &types.ConstructionDeriveRequest{ PublicKey: &types.PublicKey{ Bytes: []byte("invaliddata"), CurveType: types.Secp256k1, }, }, ) assert.Nil(t, resp) assert.Equal(t, errInvalidInput.Code, err.Code) assert.Equal(t, "invalid public key", err.Details["error"]) }) t.Run("valid public key", func(t *testing.T) { src := "03d0156cec2e01eff9c66e5dbc3c70f98214ec90a25eb43320ebcddc1a94b677f0" b, _ := hex.DecodeString(src) resp, err := service.ConstructionDerive( context.Background(), &types.ConstructionDeriveRequest{ PublicKey: &types.PublicKey{ Bytes: b, CurveType: types.Secp256k1, }, }, ) assert.Nil(t, err) assert.Equal( t, "0x156daFC6e9A1304fD5C9AB686acB4B3c802FE3f7", resp.AccountIdentifier.Address, ) }) } func forceMarshalMap(t *testing.T, i interface{}) map[string]interface{} { m, err := marshalJSONMap(i) if err != nil { t.Fatalf("could not marshal map %s", types.PrintStruct(i)) } return m } func TestPreprocessMetadata(t *testing.T) { ctx := context.Background() client := &mocks.Client{} networkIdentifier := &types.NetworkIdentifier{ Network: "Fuji", Blockchain: "Avalanche", } service := ConstructionService{ config: &Config{Mode: ModeOnline}, client: client, } intent := `[{"operation_identifier":{"index":0},"type":"CALL","account":{"address":"0xe3a5B4d7f79d64088C8d4ef153A7DDe2B2d47309"},"amount":{"value":"-42894881044106498","currency":{"symbol":"AVAX","decimals":18}}},{"operation_identifier":{"index":1},"type":"CALL","account":{"address":"0x57B414a0332B5CaB885a451c2a28a07d1e9b8a8d"},"amount":{"value":"42894881044106498","currency":{"symbol":"AVAX","decimals":18}}}]` //nolint t.Run("basic flow", func(t *testing.T) { var ops []*types.Operation assert.NoError(t, json.Unmarshal([]byte(intent), &ops)) preprocessResponse, err := service.ConstructionPreprocess( ctx, &types.ConstructionPreprocessRequest{ NetworkIdentifier: networkIdentifier, Operations: ops, }, ) assert.Nil(t, err) optionsRaw := `{"from":"0xe3a5B4d7f79d64088C8d4ef153A7DDe2B2d47309","to":"0x57B414a0332B5CaB885a451c2a28a07d1e9b8a8d","value":"0x9864aac3510d02"}` //nolint var opt options assert.NoError(t, json.Unmarshal([]byte(optionsRaw), &opt)) assert.Equal(t, &types.ConstructionPreprocessResponse{ Options: forceMarshalMap(t, &opt), }, preprocessResponse) metadata := &metadata{ GasPrice: big.NewInt(1000000000), GasLimit: 21_001, Nonce: 0, } client.On( "SuggestGasPrice", ctx, ).Return( big.NewInt(1000000000), nil, ).Once() to := common.HexToAddress("0x57B414a0332B5CaB885a451c2a28a07d1e9b8a8d") client.On( "EstimateGas", ctx, interfaces.CallMsg{ From: common.HexToAddress("0xe3a5B4d7f79d64088C8d4ef153A7DDe2B2d47309"), To: &to, Value: big.NewInt(42894881044106498), }, ).Return( uint64(21001), nil, ).Once() client.On( "NonceAt", ctx, common.HexToAddress("0xe3a5B4d7f79d64088C8d4ef153A7DDe2B2d47309"), (*big.Int)(nil), ).Return( uint64(0), nil, ).Once() metadataResponse, err := service.ConstructionMetadata(ctx, &types.ConstructionMetadataRequest{ NetworkIdentifier: networkIdentifier, Options: forceMarshalMap(t, &opt), }) assert.Nil(t, err) assert.Equal(t, &types.ConstructionMetadataResponse{ Metadata: forceMarshalMap(t, metadata), SuggestedFee: []*types.Amount{ { Value: "21001000000000", Currency: mapper.AvaxCurrency, }, }, }, metadataResponse) }) t.Run("basic flow (backwards compatible)", func(t *testing.T) { var ops []*types.Operation assert.NoError(t, json.Unmarshal([]byte(intent), &ops)) optionsRaw := `{"from":"0xe3a5B4d7f79d64088C8d4ef153A7DDe2B2d47309"}` //nolint var opt options assert.NoError(t, json.Unmarshal([]byte(optionsRaw), &opt)) metadata := &metadata{ GasPrice: big.NewInt(1000000000), GasLimit: 21_000, Nonce: 0, } client.On( "SuggestGasPrice", ctx, ).Return( big.NewInt(1000000000), nil, ).Once() client.On( "NonceAt", ctx, common.HexToAddress("0xe3a5B4d7f79d64088C8d4ef153A7DDe2B2d47309"), (*big.Int)(nil), ).Return( uint64(0), nil, ).Once() metadataResponse, err := service.ConstructionMetadata(ctx, &types.ConstructionMetadataRequest{ NetworkIdentifier: networkIdentifier, Options: forceMarshalMap(t, &opt), }) assert.Nil(t, err) assert.Equal(t, &types.ConstructionMetadataResponse{ Metadata: forceMarshalMap(t, metadata), SuggestedFee: []*types.Amount{ { Value: "21000000000000", Currency: mapper.AvaxCurrency, }, }, }, metadataResponse) }) t.Run("custom gas price flow", func(t *testing.T) { var ops []*types.Operation assert.NoError(t, json.Unmarshal([]byte(intent), &ops)) preprocessResponse, err := service.ConstructionPreprocess( ctx, &types.ConstructionPreprocessRequest{ NetworkIdentifier: networkIdentifier, Operations: ops, Metadata: map[string]interface{}{ "gas_price": "1100000000", }, }, ) assert.Nil(t, err) optionsRaw := `{"from":"0xe3a5B4d7f79d64088C8d4ef153A7DDe2B2d47309","to":"0x57B414a0332B5CaB885a451c2a28a07d1e9b8a8d","value":"0x9864aac3510d02","gas_price":"0x4190ab00"}` //nolint var opt options assert.NoError(t, json.Unmarshal([]byte(optionsRaw), &opt)) assert.Equal(t, &types.ConstructionPreprocessResponse{ Options: forceMarshalMap(t, &opt), }, preprocessResponse) metadata := &metadata{ GasPrice: big.NewInt(1100000000), GasLimit: 21_000, Nonce: 0, } to := common.HexToAddress("0x57B414a0332B5CaB885a451c2a28a07d1e9b8a8d") client.On( "EstimateGas", ctx, interfaces.CallMsg{ From: common.HexToAddress("0xe3a5B4d7f79d64088C8d4ef153A7DDe2B2d47309"), To: &to, Value: big.NewInt(42894881044106498), }, ).Return( uint64(21000), nil, ).Once() client.On( "NonceAt", ctx, common.HexToAddress("0xe3a5B4d7f79d64088C8d4ef153A7DDe2B2d47309"), (*big.Int)(nil), ).Return( uint64(0), nil, ).Once() metadataResponse, err := service.ConstructionMetadata(ctx, &types.ConstructionMetadataRequest{ NetworkIdentifier: networkIdentifier, Options: forceMarshalMap(t, &opt), }) assert.Nil(t, err) assert.Equal(t, &types.ConstructionMetadataResponse{ Metadata: forceMarshalMap(t, metadata), SuggestedFee: []*types.Amount{ { Value: "23100000000000", Currency: mapper.AvaxCurrency, }, }, }, metadataResponse) }) t.Run("custom gas price flow (ignore multiplier)", func(t *testing.T) { var ops []*types.Operation assert.NoError(t, json.Unmarshal([]byte(intent), &ops)) multiplier := float64(1.1) preprocessResponse, err := service.ConstructionPreprocess( ctx, &types.ConstructionPreprocessRequest{ NetworkIdentifier: networkIdentifier, Operations: ops, SuggestedFeeMultiplier: &multiplier, Metadata: map[string]interface{}{ "gas_price": "1100000000", }, }, ) assert.Nil(t, err) optionsRaw := `{"from":"0xe3a5B4d7f79d64088C8d4ef153A7DDe2B2d47309","to":"0x57B414a0332B5CaB885a451c2a28a07d1e9b8a8d","value":"0x9864aac3510d02","gas_price":"0x4190ab00","suggested_fee_multiplier":1.1}` //nolint var opt options assert.NoError(t, json.Unmarshal([]byte(optionsRaw), &opt)) assert.Equal(t, &types.ConstructionPreprocessResponse{ Options: forceMarshalMap(t, &opt), }, preprocessResponse) metadata := &metadata{ GasPrice: big.NewInt(1100000000), GasLimit: 21_000, Nonce: 0, } to := common.HexToAddress("0x57B414a0332B5CaB885a451c2a28a07d1e9b8a8d") client.On( "EstimateGas", ctx, interfaces.CallMsg{ From: common.HexToAddress("0xe3a5B4d7f79d64088C8d4ef153A7DDe2B2d47309"), To: &to, Value: big.NewInt(42894881044106498), }, ).Return( uint64(21000), nil, ).Once() client.On( "NonceAt", ctx, common.HexToAddress("0xe3a5B4d7f79d64088C8d4ef153A7DDe2B2d47309"), (*big.Int)(nil), ).Return( uint64(0), nil, ).Once() metadataResponse, err := service.ConstructionMetadata(ctx, &types.ConstructionMetadataRequest{ NetworkIdentifier: networkIdentifier, Options: forceMarshalMap(t, &opt), }) assert.Nil(t, err) assert.Equal(t, &types.ConstructionMetadataResponse{ Metadata: forceMarshalMap(t, metadata), SuggestedFee: []*types.Amount{ { Value: "23100000000000", Currency: mapper.AvaxCurrency, }, }, }, metadataResponse) }) t.Run("fee multiplier", func(t *testing.T) { var ops []*types.Operation assert.NoError(t, json.Unmarshal([]byte(intent), &ops)) multiplier := float64(1.1) preprocessResponse, err := service.ConstructionPreprocess( ctx, &types.ConstructionPreprocessRequest{ NetworkIdentifier: networkIdentifier, Operations: ops, SuggestedFeeMultiplier: &multiplier, }, ) assert.Nil(t, err) optionsRaw := `{"from":"0xe3a5B4d7f79d64088C8d4ef153A7DDe2B2d47309","to":"0x57B414a0332B5CaB885a451c2a28a07d1e9b8a8d","value":"0x9864aac3510d02","suggested_fee_multiplier":1.1}` //nolint var opt options assert.NoError(t, json.Unmarshal([]byte(optionsRaw), &opt)) assert.Equal(t, &types.ConstructionPreprocessResponse{ Options: forceMarshalMap(t, &opt), }, preprocessResponse) metadata := &metadata{ GasPrice: big.NewInt(1100000000), GasLimit: 21_000, Nonce: 0, } to := common.HexToAddress("0x57B414a0332B5CaB885a451c2a28a07d1e9b8a8d") client.On( "EstimateGas", ctx, interfaces.CallMsg{ From: common.HexToAddress("0xe3a5B4d7f79d64088C8d4ef153A7DDe2B2d47309"), To: &to, Value: big.NewInt(42894881044106498), }, ).Return( uint64(21000), nil, ).Once() client.On( "SuggestGasPrice", ctx, ).Return( big.NewInt(1000000000), nil, ).Once() client.On( "NonceAt", ctx, common.HexToAddress("0xe3a5B4d7f79d64088C8d4ef153A7DDe2B2d47309"), (*big.Int)(nil), ).Return( uint64(0), nil, ).Once() metadataResponse, err := service.ConstructionMetadata(ctx, &types.ConstructionMetadataRequest{ NetworkIdentifier: networkIdentifier, Options: forceMarshalMap(t, &opt), }) assert.Nil(t, err) assert.Equal(t, &types.ConstructionMetadataResponse{ Metadata: forceMarshalMap(t, metadata), SuggestedFee: []*types.Amount{ { Value: "23100000000000", Currency: mapper.AvaxCurrency, }, }, }, metadataResponse) }) t.Run("custom nonce", func(t *testing.T) { var ops []*types.Operation assert.NoError(t, json.Unmarshal([]byte(intent), &ops)) multiplier := float64(1.1) preprocessResponse, err := service.ConstructionPreprocess( ctx, &types.ConstructionPreprocessRequest{ NetworkIdentifier: networkIdentifier, Operations: ops, SuggestedFeeMultiplier: &multiplier, Metadata: map[string]interface{}{ "nonce": "1", }, }, ) assert.Nil(t, err) optionsRaw := `{"from":"0xe3a5B4d7f79d64088C8d4ef153A7DDe2B2d47309","to":"0x57B414a0332B5CaB885a451c2a28a07d1e9b8a8d","value":"0x9864aac3510d02","suggested_fee_multiplier":1.1, "nonce":"0x1"}` //nolint var opt options assert.NoError(t, json.Unmarshal([]byte(optionsRaw), &opt)) assert.Equal(t, &types.ConstructionPreprocessResponse{ Options: forceMarshalMap(t, &opt), }, preprocessResponse) metadata := &metadata{ GasPrice: big.NewInt(1100000000), GasLimit: 21_000, Nonce: 1, } to := common.HexToAddress("0x57B414a0332B5CaB885a451c2a28a07d1e9b8a8d") client.On( "EstimateGas", ctx, interfaces.CallMsg{ From: common.HexToAddress("0xe3a5B4d7f79d64088C8d4ef153A7DDe2B2d47309"), To: &to, Value: big.NewInt(42894881044106498), }, ).Return( uint64(21000), nil, ).Once() client.On( "SuggestGasPrice", ctx, ).Return( big.NewInt(1000000000), nil, ).Once() metadataResponse, err := service.ConstructionMetadata(ctx, &types.ConstructionMetadataRequest{ NetworkIdentifier: networkIdentifier, Options: forceMarshalMap(t, &opt), }) assert.Nil(t, err) assert.Equal(t, &types.ConstructionMetadataResponse{ Metadata: forceMarshalMap(t, metadata), SuggestedFee: []*types.Amount{ { Value: "23100000000000", Currency: mapper.AvaxCurrency, }, }, }, metadataResponse) }) t.Run("custom gas limit", func(t *testing.T) { var ops []*types.Operation assert.NoError(t, json.Unmarshal([]byte(intent), &ops)) multiplier := float64(1.1) preprocessResponse, err := service.ConstructionPreprocess( ctx, &types.ConstructionPreprocessRequest{ NetworkIdentifier: networkIdentifier, Operations: ops, SuggestedFeeMultiplier: &multiplier, Metadata: map[string]interface{}{ "gas_limit": "40000", }, }, ) assert.Nil(t, err) optionsRaw := `{"from":"0xe3a5B4d7f79d64088C8d4ef153A7DDe2B2d47309","to":"0x57B414a0332B5CaB885a451c2a28a07d1e9b8a8d","value":"0x9864aac3510d02","suggested_fee_multiplier":1.1,"gas_limit":"0x9c40"}` //nolint:lll var opt options assert.NoError(t, json.Unmarshal([]byte(optionsRaw), &opt)) assert.Equal(t, &types.ConstructionPreprocessResponse{ Options: forceMarshalMap(t, &opt), }, preprocessResponse) metadata := &metadata{ GasPrice: big.NewInt(1100000000), GasLimit: 40_000, Nonce: 0, } client.On( "SuggestGasPrice", ctx, ).Return( big.NewInt(1000000000), nil, ).Once() client.On( "NonceAt", ctx, common.HexToAddress("0xe3a5B4d7f79d64088C8d4ef153A7DDe2B2d47309"), (*big.Int)(nil), ).Return( uint64(0), nil, ).Once() metadataResponse, err := service.ConstructionMetadata(ctx, &types.ConstructionMetadataRequest{ NetworkIdentifier: networkIdentifier, Options: forceMarshalMap(t, &opt), }) assert.Nil(t, err) assert.Equal(t, &types.ConstructionMetadataResponse{ Metadata: forceMarshalMap(t, metadata), SuggestedFee: []*types.Amount{ { Value: "44000000000000", Currency: mapper.AvaxCurrency, }, }, }, metadataResponse) }) } <|start_filename|>service/rosetta.go<|end_filename|> package service const ( NodeVersion = "1.7.3" MiddlewareVersion = "0.0.26" BlockchainName = "Avalanche" ) <|start_filename|>client/evm_logs.go<|end_filename|> package client import ( "context" "fmt" "strings" "github.com/ava-labs/avalanchego/cache" "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/ethclient" "github.com/ava-labs/coreth/interfaces" "github.com/ethereum/go-ethereum/common" ) const ( logCacheSize = 100 transferMethodHash = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef" ) // EvmLogsClient is a client for requesting evm logs type EvmLogsClient struct { ethClient *ethclient.Client cache *cache.LRU } // NewEvmLogsClient returns a new EVM Logs client func NewEvmLogsClient(endpoint string) (*EvmLogsClient, error) { endpoint = strings.TrimSuffix(endpoint, "/") c, err := ethclient.Dial(fmt.Sprintf("%s%s", endpoint, prefixEth)) if err != nil { return nil, err } cache := &cache.LRU{Size: logCacheSize} return &EvmLogsClient{ ethClient: c, cache: cache, }, nil } // EvmTransferLogs returns a set of evm logs based on the requested block hash and transaction hash func (c *EvmLogsClient) EvmTransferLogs( ctx context.Context, blockHash common.Hash, transactionHash common.Hash, ) ([]types.Log, error) { blockLogs, isCached := c.cache.Get(blockHash.String()) if !isCached { var err error var topics [][]common.Hash = [][]common.Hash{{common.HexToHash(transferMethodHash)}} var filter interfaces.FilterQuery = interfaces.FilterQuery{BlockHash: &blockHash, Topics: topics} blockLogs, err = c.ethClient.FilterLogs(ctx, filter) if err != nil { return nil, err } c.cache.Put(blockHash.String(), blockLogs) } var filteredLogs []types.Log for _, log := range blockLogs.([]types.Log) { if log.TxHash == transactionHash { filteredLogs = append(filteredLogs, log) } } return filteredLogs, nil } <|start_filename|>service/errors.go<|end_filename|> package service import ( "github.com/coinbase/rosetta-sdk-go/types" ) var ( // Errors lists all available error types Errors = []*types.Error{ errNotImplemented, errNotSupported, errNotReady, errUnavailableOffline, errInternalError, errInvalidInput, errClientError, errBlockInvalidInput, errBlockNotFound, errCallInvalidMethod, } // General errors errNotReady = makeError(1, "Node is not ready", true) //nolint:gomnd errNotImplemented = makeError(2, "Endpoint is not implemented", false) //nolint:gomnd errNotSupported = makeError(3, "Endpoint is not supported", false) //nolint:gomnd errUnavailableOffline = makeError(4, "Endpoint is not available offline", false) //nolint:gomnd errInternalError = makeError(5, "Internal server error", true) //nolint:gomnd errInvalidInput = makeError(6, "Invalid input", false) //nolint:gomnd errClientError = makeError(7, "Client error", true) //nolint:gomnd errBlockInvalidInput = makeError(8, "Block number or hash is required", false) //nolint:gomnd errBlockNotFound = makeError(9, "Block was not found", true) //nolint:gomnd errCallInvalidMethod = makeError(10, "Invalid call method", false) //nolint:gomnd errCallInvalidParams = makeError(11, "invalid call params", false) //nolint:gomnd ) func makeError(code int32, message string, retriable bool) *types.Error { return &types.Error{ Code: code, Message: message, Retriable: retriable, Details: map[string]interface{}{}, } } func wrapError(err *types.Error, message interface{}) *types.Error { newErr := makeError(err.Code, err.Message, err.Retriable) if err.Description != nil { newErr.Description = err.Description } for k, v := range err.Details { newErr.Details[k] = v } switch t := message.(type) { case error: newErr.Details["error"] = t.Error() default: newErr.Details["error"] = t } return newErr } <|start_filename|>mapper/amount.go<|end_filename|> package mapper import ( "math/big" "strconv" "github.com/coinbase/rosetta-sdk-go/types" "github.com/ethereum/go-ethereum/common" ) func Amount(value *big.Int, currency *types.Currency) *types.Amount { if value == nil { return nil } return &types.Amount{ Value: value.String(), Currency: AvaxCurrency, } } func FeeAmount(value int64) *types.Amount { return &types.Amount{ Value: strconv.FormatInt(value, 10), //nolint:gomnd Currency: AvaxCurrency, } } func AvaxAmount(value *big.Int) *types.Amount { return Amount(value, AvaxCurrency) } func Erc20Amount( data []byte, contractAddress common.Address, contractSymbol string, contractDecimal uint8, isSender bool) *types.Amount { value := common.BytesToHash(data) decimalValue := value.Big() if isSender { decimalValue = new(big.Int).Neg(decimalValue) } metadata := make(map[string]interface{}) metadata[ContractAddressMetadata] = contractAddress.String() return &types.Amount{ Value: decimalValue.String(), Currency: &types.Currency{ Symbol: contractSymbol, Decimals: int32(contractDecimal), Metadata: metadata, }, } } <|start_filename|>mapper/codec.go<|end_filename|> package mapper import ( "github.com/ava-labs/avalanchego/codec" "github.com/ava-labs/avalanchego/codec/linearcodec" "github.com/ava-labs/avalanchego/utils/wrappers" "github.com/ava-labs/avalanchego/vms/secp256k1fx" "github.com/ava-labs/coreth/plugin/evm" ) const ( preApricotCodecVersion uint16 = 0 codecRegistrationSkip int = 3 ) var ( codecManager codec.Manager ) func init() { codecManager = codec.NewDefaultManager() errs := wrappers.Errs{} preApricotCodec := initPreApricotCodec(&errs) errs.Add( codecManager.RegisterCodec(preApricotCodecVersion, preApricotCodec), ) if errs.Errored() { panic(errs.Err) } } func initPreApricotCodec(errs *wrappers.Errs) linearcodec.Codec { c := linearcodec.NewDefault() errs.Add( c.RegisterType(&evm.UnsignedImportTx{}), c.RegisterType(&evm.UnsignedExportTx{}), ) c.SkipRegistrations(codecRegistrationSkip) errs.Add( c.RegisterType(&secp256k1fx.TransferInput{}), c.RegisterType(&secp256k1fx.MintOutput{}), c.RegisterType(&secp256k1fx.TransferOutput{}), c.RegisterType(&secp256k1fx.MintOperation{}), c.RegisterType(&secp256k1fx.Credential{}), c.RegisterType(&secp256k1fx.Input{}), c.RegisterType(&secp256k1fx.OutputOwners{}), ) return c } <|start_filename|>client/info.go<|end_filename|> package client import ( "context" "fmt" "strings" ) const ( methodGetBlockchainID = "info.getBlockchainID" methodGetNetworkID = "info.getNetworkID" methodGetNetworkName = "info.getNetworkName" methodGetNodeID = "info.getNodeID" methodGetNodeVersion = "info.getNodeVersion" methodGetPeers = "info.peers" methodIsBootstrapped = "info.isBootstrapped" ) // InfoClient is a client for the Info API type InfoClient struct { rpc *RPC } // NewInfoClient returns a new client to Info API func NewInfoClient(endpoint string) (*InfoClient, error) { c := Dial(fmt.Sprintf("%s%s", endpoint, prefixInfo)) return &InfoClient{rpc: c}, nil } // IsBootstrapped returns true if a chans is bootstrapped func (c *InfoClient) IsBootstrapped(ctx context.Context, chain string) (bool, error) { args := map[string]string{"chain": chain} resp := map[string]bool{} err := c.rpc.Call(ctx, methodIsBootstrapped, args, &resp) return resp["isBootstrapped"], err } // BlockchainID returns the current blockchain identifier func (c *InfoClient) BlockchainID(ctx context.Context, alias string) (string, error) { data, err := c.rpc.CallRaw(ctx, methodGetBlockchainID, map[string]string{"alias": alias}) if err != nil { return "", err } return string(data), nil } // NetworkID returns the current network identifier func (c *InfoClient) NetworkID(ctx context.Context) (string, error) { data, err := c.rpc.CallRaw(ctx, methodGetNetworkID, nil) if err != nil { return "", err } return string(data), nil } // NetworkName returns the current network name func (c *InfoClient) NetworkName(ctx context.Context) (string, error) { resp := map[string]string{} err := c.rpc.Call(ctx, methodGetNetworkName, nil, &resp) return strings.Title(resp["networkName"]), err } // NodeID return the current node identifier func (c *InfoClient) NodeID(ctx context.Context) (string, error) { data, err := c.rpc.CallRaw(ctx, methodGetNodeID, nil) if err != nil { return "", err } return string(data), nil } // NodeVersion returns the current node version func (c *InfoClient) NodeVersion(ctx context.Context) (string, error) { resp := map[string]string{} if err := c.rpc.Call(ctx, methodGetNodeVersion, nil, &resp); err != nil { return "", err } return resp["version"], nil } // Peers returns the list of active peers func (c *InfoClient) Peers(ctx context.Context) ([]Peer, error) { resp := infoPeersResponse{} if err := c.rpc.Call(ctx, methodGetPeers, nil, &resp); err != nil { return nil, err } return resp.Peers, nil } <|start_filename|>mapper/address.go<|end_filename|> package mapper import ( ethcommon "github.com/ethereum/go-ethereum/common" ) // ConvertEVMTopicHashToAddress uses the last 20 bytes of a common.Hash to create a common.Address func ConvertEVMTopicHashToAddress(hash *ethcommon.Hash) *ethcommon.Address { if hash == nil { return nil } address := ethcommon.BytesToAddress(hash[12:32]) return &address } <|start_filename|>client/contract.go<|end_filename|> package client import ( "fmt" "strings" "github.com/ava-labs/avalanchego/cache" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/ethclient" ) const ( contractCacheSize = 1024 ) // ContractClient is a client for the calling contract information type ContractClient struct { ethClient *ethclient.Client cache *cache.LRU } // NewContractClient returns a new ContractInfo client func NewContractClient(endpoint string) (*ContractClient, error) { endpoint = strings.TrimSuffix(endpoint, "/") c, err := ethclient.Dial(fmt.Sprintf("%s%s", endpoint, prefixEth)) if err != nil { return nil, err } cache := &cache.LRU{Size: contractCacheSize} return &ContractClient{ ethClient: c, cache: cache, }, nil } // ContractInfo returns the ContractInfo for a specific address func (c *ContractClient) ContractInfo(contractAddress common.Address, isErc20 bool) (*ContractInfo, error) { cachedInfo, isCached := c.cache.Get(contractAddress) if isCached { castCachedInfo := cachedInfo.(*ContractInfo) return castCachedInfo, nil } token, err := NewContractInfoToken(contractAddress, c.ethClient) if err != nil { return nil, err } symbol, symbolErr := token.Symbol(nil) decimals, decimalErr := token.Decimals(nil) // Any of these indicate a failure to get complete information from contract if symbolErr != nil || decimalErr != nil || symbol == "" || decimals == 0 { if isErc20 { symbol = UnknownERC20Symbol decimals = UnknownERC20Decimals } else { symbol = UnknownERC721Symbol decimals = UnknownERC721Decimals } } contractInfo := &ContractInfo{Symbol: symbol, Decimals: decimals} // Cache defaults for contract address to avoid unnecessary lookups c.cache.Put(contractAddress, contractInfo) return contractInfo, nil } <|start_filename|>client/eth.go<|end_filename|> package client import ( "context" "fmt" "strings" "github.com/ava-labs/coreth/ethclient" "github.com/ethereum/go-ethereum/eth/tracers" ) var ( tracerTimeout = "180s" ) // EthClient provides access to Coreth API type EthClient struct { *ethclient.Client rpc *RPC traceConfig *tracers.TraceConfig } // NewEthClient returns a new EVM client func NewEthClient(endpoint string) (*EthClient, error) { endpoint = strings.TrimSuffix(endpoint, "/") c, err := ethclient.Dial(fmt.Sprintf("%s%s", endpoint, prefixEth)) if err != nil { return nil, err } raw := Dial(fmt.Sprintf("%s%s", endpoint, prefixEth)) return &EthClient{ Client: c, rpc: raw, traceConfig: &tracers.TraceConfig{ Timeout: &tracerTimeout, Tracer: &jsTracer, }, }, nil } // TxPoolStatus return the current tx pool status func (c *EthClient) TxPoolStatus(ctx context.Context) (*TxPoolStatus, error) { status := &TxPoolStatus{} err := c.rpc.Call(ctx, "txpool_status", nil, status) if err != nil { status = nil } return status, err } // TxPoolContent returns the tx pool content func (c *EthClient) TxPoolContent(ctx context.Context) (*TxPoolContent, error) { content := &TxPoolContent{} err := c.rpc.Call(ctx, "txpool_inspect", nil, content) if err != nil { content = nil } return content, err } // TraceTransaction returns a transaction trace func (c *EthClient) TraceTransaction(ctx context.Context, hash string) (*Call, []*FlatCall, error) { result := &Call{} args := []interface{}{hash, c.traceConfig} err := c.rpc.Call(context.Background(), "debug_traceTransaction", args, &result) if err != nil { return nil, nil, err } flattened := result.init() return result, flattened, nil }
ava-labs/avalanche-rosetta
<|start_filename|>functions/graphql.js<|end_filename|> const { createLambdaServer } = require("./bundle/server") const graphQLServer = createLambdaServer(); exports.handler = graphQLServer.createHandler({ cors: { origin: '*' } });
Wysnard/serverless-typescript-graphql-netlify-starter
<|start_filename|>src/components/CheckboxGroupField.js<|end_filename|> import Checkbox from "antd/lib/checkbox"; import { customMap, defaultTo } from "../maps/mapError"; import createComponent from "./BaseComponent"; const CheckboxGroup = Checkbox.Group; const checkboxGroupMap = customMap((mapProps, { input: { onChange, value = [] } }) => { value = defaultTo(value, []); return { ...mapProps, onChange, value }; }); export default createComponent( CheckboxGroup, checkboxGroupMap ); <|start_filename|>src/components/TextField.js<|end_filename|> import Input from "antd/lib/input"; import textFieldMap from "../maps/textFieldMap"; import createComponent from "./BaseComponent"; export default createComponent(Input, textFieldMap); <|start_filename|>src/maps/eventMap.js<|end_filename|> import { customMap } from "./mapError"; export default customMap((mapProps, { input: { onChange } }) => ({ ...mapProps, onChange: v => onChange(v.target.value) })); <|start_filename|>src/components/TextAreaField.js<|end_filename|> import Input from "antd/lib/input"; import textFieldMap from "../maps/textFieldMap"; import createComponent from "./BaseComponent"; const { TextArea } = Input; export default createComponent(TextArea, textFieldMap); <|start_filename|>src/index.js<|end_filename|> import createComponent from "./components/BaseComponent"; import { customMap } from "./maps/mapError"; export { default as CheckboxGroupField } from "./components/CheckboxGroupField"; export { default as LazyTextField } from "./components/LazyTextField"; export { default as SelectField } from "./components/SelectField"; export { default as CheckboxField } from "./components/CheckboxField"; export { default as RadioField } from "./components/RadioField"; export { default as TextField } from "./components/TextField"; export { default as TextAreaField } from "./components/TextAreaField"; export { default as SwitchField } from "./components/SwitchField"; export { default as NumberField } from "./components/NumberField"; export { default as SliderField } from "./components/SliderField"; export * from "./components/DatePicker"; export { createComponent, customMap }; <|start_filename|>src/components/NumberField.js<|end_filename|> import InputNumber from "antd/lib/input-number"; import mapError from "../maps/mapError"; import createComponent from "./BaseComponent"; export default createComponent(InputNumber, mapError); <|start_filename|>stories/index.js<|end_filename|> import React from "react"; import { storiesOf } from "@storybook/react"; import { action } from "@storybook/addon-actions"; import "./TextInput"; import { linkTo } from "@storybook/addon-links"; import { withKnobs, text, boolean, number } from "@storybook/addon-knobs";
maysam/redux-form-antd
<|start_filename|>facebook-id-of.js<|end_filename|> 'use strict'; const https = require('https'); const rePattern = new RegExp(/entity_id":"(\d*)"/); function facebookIdOfPromise(username) { const options = { hostname: 'www.facebook.com', port: 443, path: `/${username}`, method: 'GET', headers: { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36', 'Accept-Language': 'en-GB,en-US;q=0.8,en;q=0.6' } }; return new Promise((resolve, reject) => { const request = https.request(options, response => { let body = ''; response.setEncoding('utf8'); response.on('data', chunk => { body += chunk; }); response.on('end', () => { const arrMatches = body.match(rePattern); if (arrMatches && arrMatches.length > 1) { resolve(arrMatches[1]); } else { reject(new Error('Facebook user not found')); } }); }); request.on('error', err => reject(err)); request.end(); }); } function facebookIdOfCallback(username, callback) { facebookIdOfPromise(username) .then(id => callback(null, id)) .catch(err => callback(err)); } function facebookIdOf(username, callback) { if (callback) { return facebookIdOfCallback(username, callback); } return facebookIdOfPromise(username); } module.exports = facebookIdOf; <|start_filename|>cli.js<|end_filename|> #!/usr/bin/env node 'use strict'; const chalk = require('chalk'); const logUpdate = require('log-update'); const facebookIdOf = require('./facebook-id-of'); const arg = process.argv[2]; if (!arg || arg === '-h' || arg === '--help') { help(); } loading(); facebookIdOf(arg) .then(success) .catch(error); function help() { console.log(`${chalk.cyan('Usage:')} facebook-id-of <username>`); process.exit(0); } function loading() { if (process.stdout.isTTY) { logUpdate(`${chalk.cyan.bold('›')} Contacting Facebook ...`); } } function success(id) { if (process.stdout.isTTY) { logUpdate( `${chalk.green.bold('›')} ${chalk.dim('Facebook ID of')} ${arg}: ${id}`, ); } else { console.log(id); } process.exit(0); } function error(err) { if (process.stdout.isTTY) { logUpdate(`${chalk.red.bold('›')} ${err}`); } else { console.log(err); } process.exit(1); }
KomodoHQ/facebook-id-of
<|start_filename|>source/v0/UDPSocket.cpp<|end_filename|> /* * PackageLicenseDeclared: Apache-2.0 * Copyright (c) 2015 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "sockets/v0/UDPSocket.h" #include "sal/socket_api.h" using namespace mbed::Sockets::v0; UDPSocket::UDPSocket(socket_stack_t stack): /* Store the default handler */ Socket(stack) { _socket.family = SOCKET_DGRAM; } UDPSocket::~UDPSocket() { } socket_error_t UDPSocket::connect(const SocketAddr *address, const uint16_t port) { if (_socket.api == NULL) { return SOCKET_ERROR_BAD_STACK; } socket_error_t err = _socket.api->connect(&_socket, address->getAddr(), port); return err; } socket_error_t UDPSocket::open(const socket_address_family_t af, const socket_proto_family_t pf) { (void)af; (void)pf; return SOCKET_ERROR_UNIMPLEMENTED; } <|start_filename|>test/echo-tcp-client/main.cpp<|end_filename|> /* * PackageLicenseDeclared: Apache-2.0 * Copyright (c) 2015 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "mbed-drivers/mbed.h" #include "sockets/TCPStream.h" #include "sal-stack-lwip/lwipv4_init.h" #include "sal-iface-eth/EthernetInterface.h" #include "minar/minar.h" #include "core-util/FunctionPointer.h" #include "greentea-client/test_env.h" #include "utest/utest.h" #include "unity/unity.h" using namespace utest::v1; using namespace mbed::Sockets::v0; EthernetInterface eth; class TCPEchoClient; typedef mbed::util::FunctionPointer2<void, bool, TCPEchoClient*> fpterminate_t; void terminate(bool status, TCPEchoClient* client); char out_buffer[] = "Hello World\n"; char buffer[256]; char out_success[] = "{{success}}\n{{end}}\n"; TCPEchoClient *client; int port; class TCPEchoClient { public: TCPEchoClient(socket_stack_t stack) : _stream(stack), _done(false), _disconnected(true) { _stream.setOnError(TCPStream::ErrorHandler_t(this, &TCPEchoClient::onError)); } ~TCPEchoClient(){ if (_stream.isConnected()) _stream.close(); } void onError(Socket *s, socket_error_t err) { (void) s; TEST_ASSERT_NOT_EQUAL_MESSAGE(SOCKET_ERROR_NONE, err, socket_strerror(err)); printf("MBED: Socket Error: %s (%d)\r\n", socket_strerror(err), err); _done = true; minar::Scheduler::postCallback(fpterminate_t(terminate).bind(false,this)); } void start_test(char * host_addr, uint16_t port) { printf("Trying to resolve address %s" NL, host_addr); _port = port; _done = false; _disconnected = true; socket_error_t err = _stream.open(SOCKET_AF_INET4); TEST_ASSERT_EQUAL_MESSAGE(SOCKET_ERROR_NONE, err, "MBED: Failed to open socket!"); err = _stream.resolve(host_addr,TCPStream::DNSHandler_t(this, &TCPEchoClient::onDNS)); TEST_ASSERT_EQUAL_MESSAGE(SOCKET_ERROR_NONE, err, "MBED: Failed to resolve host address!"); } void onDNS(Socket *s, struct socket_addr sa, const char* domain) { (void) s; _resolvedAddr.setAddr(&sa); /* TODO: add support for getting AF from addr */ /* Open the socket */ _resolvedAddr.fmtIPv6(buffer, sizeof(buffer)); printf("MBED: Resolved %s to %s\r\n", domain, buffer); /* Register the read handler */ _stream.setOnReadable(TCPStream::ReadableHandler_t(this, &TCPEchoClient::onRx)); _stream.setOnSent(TCPStream::SentHandler_t(this, &TCPEchoClient::onSent)); _stream.setOnDisconnect(TCPStream::DisconnectHandler_t(this, &TCPEchoClient::onDisconnect)); /* Send the query packet to the remote host */ socket_error_t err = _stream.connect(_resolvedAddr, _port, TCPStream::ConnectHandler_t(this,&TCPEchoClient::onConnect)); TEST_ASSERT_EQUAL_MESSAGE(SOCKET_ERROR_NONE, err, "MBED: Failed to connect host server!"); } void onConnect(TCPStream *s) { (void) s; _disconnected = false; _unacked = sizeof(out_buffer) - 1; printf ("MBED: Sending (%d bytes) to host: %s" NL, _unacked, out_buffer); socket_error_t err = _stream.send(out_buffer, sizeof(out_buffer) - 1); TEST_ASSERT_EQUAL_MESSAGE(SOCKET_ERROR_NONE, err, "MBED: TCPClient failed to send data!"); } void onRx(Socket* s) { (void) s; size_t n = sizeof(buffer)-1; socket_error_t err = _stream.recv(buffer, &n); TEST_ASSERT_EQUAL_MESSAGE(SOCKET_ERROR_NONE, err, "MBED: TCPClient failed to recv data!"); buffer[n] = 0; printf ("MBED: Rx (%d bytes) from host: %s" NL, n, buffer); if (!_done && n > 0) { TEST_ASSERT_EQUAL_STRING_LEN_MESSAGE(out_buffer, buffer, n, "MBED: TCPClient round trip data validation failed!"); _unacked += sizeof(out_success) - 1; printf ("MBED: Sending (%d bytes) to host: %s" NL, _unacked, out_success); err = _stream.send(out_success, sizeof(out_success) - 1); _done = true; TEST_ASSERT_EQUAL_MESSAGE(SOCKET_ERROR_NONE, err, "MBED: TCPClient failed to send data!"); } if (!_done) { // Failed to validate rceived data. Terminating... minar::Scheduler::postCallback(fpterminate_t(terminate).bind(false,this)); } } void onSent(Socket *s, uint16_t nbytes) { (void) s; _unacked -= nbytes; printf ("MBED: Sent %d bytes" NL, nbytes); if (_done && (_unacked == 0)) { minar::Scheduler::postCallback(fpterminate_t(terminate).bind(true,this)); } } void onDisconnect(TCPStream *s) { (void) s; _disconnected = true; } protected: TCPStream _stream; SocketAddr _resolvedAddr; uint16_t _port; volatile bool _done; volatile bool _disconnected; volatile size_t _unacked; }; void terminate(bool status, TCPEchoClient* ) { if (client) { printf("MBED: Test finished!"); delete client; client = NULL; eth.disconnect(); TEST_ASSERT_TRUE_MESSAGE(status, "MBED: test failed!"); Harness::validate_callback(); } } control_t test_echo_tcp_client() { socket_error_t err = lwipv4_socket_init(); TEST_ASSERT_EQUAL(SOCKET_ERROR_NONE, err); TEST_ASSERT_EQUAL(0, eth.init()); //Use DHCP eth.connect(); printf("TCPClient IP Address is %s" NL, eth.getIPAddress()); greentea_send_kv("target_ip", eth.getIPAddress()); memset(buffer, 0, sizeof(buffer)); port = 0; printf("TCPClient waiting for server IP and port..." NL); char recv_key[] = "host_port"; char port_value[] = "65325"; greentea_send_kv("host_ip", " "); TEST_ASSERT_NOT_EQUAL_MESSAGE(0, greentea_parse_kv(recv_key, buffer, sizeof(recv_key), sizeof(buffer)), "MBED: Failed to recv/parse key value from host test!"); greentea_send_kv("host_port", " "); TEST_ASSERT_NOT_EQUAL_MESSAGE(0, greentea_parse_kv(recv_key, port_value, sizeof(recv_key), sizeof(port_value)), "MBED: Failed to recv/parse key value from host test!"); sscanf(port_value, "%d", &port); client = new TCPEchoClient(SOCKET_STACK_LWIP_IPV4); { mbed::util::FunctionPointer2<void, char *, uint16_t> fp(client, &TCPEchoClient::start_test); minar::Scheduler::postCallback(fp.bind(buffer, port)); } return CaseTimeout(15000); } // Cases -------------------------------------------------------------------------------------------------------------- Case cases[] = { Case("Test Echo TCP Client", test_echo_tcp_client), }; status_t greentea_setup(const size_t number_of_cases) { // Handshake with greentea // Host test timeout should be more than target utest timeout to let target cleanup the test and send test summary. GREENTEA_SETUP(20, "tcpecho_client_auto"); return greentea_test_setup_handler(number_of_cases); } Specification specification(greentea_setup, cases); void app_start(int, char*[]) { Harness::run(specification); } <|start_filename|>sockets/v0/SocketAddr.h<|end_filename|> /* * PackageLicenseDeclared: Apache-2.0 * Copyright (c) 2015 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __SOCKETS_V0_SOCKETADDR_H__ #define __SOCKETS_V0_SOCKETADDR_H__ #include "sal/socket_types.h" namespace mbed { namespace Sockets { namespace v0 { /** * SocketAddr is a container class for storing IP addresses. * * SocketAddr provides a common interface for setting and getting IP addresses * * When an IPv4 address is set, SocketAddr stores it in IPv4-mapped IPv6. It is assumed that any address in the * ::ffff:0000:0000 address range should be treated as an IPv4 address. */ class SocketAddr { public: /** * Get a pointer to the internal struct socket_addr storage * * @return The address of the internal struct */ struct socket_addr * getAddr() {return &_addr;} /** * Get a const pointer to the internal struct socket_addr storage * * @return The address of the internal struct */ const struct socket_addr * getAddr() const {return &_addr;} /** * Copy the contents of an existing struct socket_addr into the internal storage * * @param[in] addr the original address to copy */ void setAddr(const struct socket_addr *addr); /** * Copy the contents of an existing SocketAddr into the internal storage * * @param[in] addr the original address to copy */ void setAddr(const SocketAddr *addr); /** * Parse a string representation of the address into the SocketAddr * * This function uses inet_pton and has the restrictions expected with that API. * * @param[in] addr the original address to copy * @retval SOCKET_ERROR_NONE Format completed * @retval SOCKET_ERROR_BAD_ADDRESS Unrecognized address format * @retval SOCKET_ERROR_BAD_ARGUMENT An unexpected argument was provided * @retval SOCKET_ERROR_UNKNOWN An unexpected error occurred */ socket_error_t setAddr(socket_address_family_t af, const char *addr); /** * Return the size of the internal storage. * * @return the space consumed by a SocketAddr */ size_t getAddrSize() const {return sizeof(_addr.ipv6be);} /** * Check if the internal address is an IPv4 address * This checks if the address falls in the `::ffff:0000:0000` range. * * @retval true the IP address is IPv4 * @retval false otherwise */ bool is_v4() const; /** * Format the IP address in IPv4 dotted-quad Format * * @param[out] buf the buffer to fill * @param[in] size the size of the buffer to fill. Must be at least 16 chars long (incl. terminator). * * @retval -1 error formatting * @retval 0 format successful */ int fmtIPv4(char *buf, size_t size) const; /// Convenience function for using statically allocated buffers. template< size_t N > int fmtIPv4(char (&buf)[N]) { return fmtIPv4(buf, N); } /** * Format the IP address in IPv6 colon separated format * * If the IP address is IPv6, colon-separated format is used. * If the IP address is IPv4, then the address is formatted as a 96-bit prefix in colon-separated format, followed * by a 32-bit dotted-quad. * * * @param[out] buf the buffer to fill * @param[in] size the size of the buffer to fill. * Must be at least 23 chars long (incl. terminator) for an IPv4 address in IPv6 format. * Must be at least 46 chars long for a complete IPv6 address. Smaller buffers may be used * for abbreviated addresses, such as ::1 * * @retval 0 formatting was successful * @retval -1 formatting failed */ int fmtIPv6(char *buf, size_t size) const; /// Convenience function for using statically allocated buffers. template< size_t N > int fmtIPv6(char (&buf)[N]) { return fmtIPv6(buf, N); } protected: struct socket_addr _addr; }; } // namespace v0 } // namespace Sockets } // namespace mbed #endif // __SOCKETS_V0_SOCKETADDR_H__ <|start_filename|>source/v0/TCPStream.cpp<|end_filename|> /* * PackageLicenseDeclared: Apache-2.0 * Copyright (c) 2015 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "sockets/v0/TCPStream.h" #include "sockets/v0/SocketAddr.h" #include "sal/socket_api.h" #include "minar/minar.h" using namespace mbed::Sockets::v0; TCPStream::TCPStream(const socket_stack_t stack) : /* Store the default handler */ TCPAsynch(stack), /* Zero the handlers */ _onConnect(NULL), _onDisconnect(NULL) { /* NOTE: _socket is initialized by TCPAsynch. */ } TCPStream::TCPStream(const struct socket *sock) : /* Store the default handler */ TCPAsynch(sock->stack), /* Zero the handlers */ _onConnect(NULL), _onDisconnect(NULL) { _socket.family = sock->family; _socket.impl = sock->impl; socket_error_t err = _socket.api->accept(&_socket, reinterpret_cast<socket_api_handler_t>(_irq.entry())); error_check(err); } TCPStream::TCPStream(struct socket* listener, const struct socket *sock, socket_error_t &err) : /* Store the default handler */ TCPAsynch(sock->stack), /* Zero the handlers */ _onConnect(NULL), _onDisconnect(NULL) { _socket.family = sock->family; _socket.impl = sock->impl; err = socket_accept(listener, &_socket, reinterpret_cast<socket_api_handler_t>(_irq.entry())); } TCPStream::~TCPStream() { } socket_error_t TCPStream::connect(const SocketAddr &address, const uint16_t port, const ConnectHandler_t &onConnect) { if (_socket.api == NULL){ return SOCKET_ERROR_BAD_STACK; } _onConnect = onConnect; socket_error_t err = _socket.api->connect(&_socket, address.getAddr(), port); return err; } void TCPStream::_eventHandler(struct socket_event *ev) { switch (ev->event) { case SOCKET_EVENT_CONNECT: if (_onConnect) minar::Scheduler::postCallback(_onConnect.bind(this)); break; case SOCKET_EVENT_DISCONNECT: if (_onDisconnect) minar::Scheduler::postCallback(_onDisconnect.bind(this)); break; default: // Call the aSocket event handler if the event is a generic one Socket::_eventHandler(ev); break; } } void TCPStream::setNagle(bool enable) { void * enable_ptr; if(enable) { enable_ptr = (void*)1; } else { enable_ptr = NULL; } _socket.api->set_option(&_socket, SOCKET_PROTO_LEVEL_TCP, SOCKET_OPT_NAGLE, enable_ptr, 0); } <|start_filename|>sockets/v0/TCPAsynch.h<|end_filename|> /* * PackageLicenseDeclared: Apache-2.0 * Copyright (c) 2015 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __MBED_NET_SOCKETS_V0_TCP_ASYNCH__ #define __MBED_NET_SOCKETS_V0_TCP_ASYNCH__ #include "Socket.h" #include "sal/socket_api.h" #include "minar/minar.h" namespace mbed { namespace Sockets { namespace v0 { class TCPAsynch: public Socket { protected: TCPAsynch(const socket_stack_t stack); ~TCPAsynch(); public: /** * Open the socket. * Instantiates and initializes the underlying socket. Receive is started immediately after * the socket is opened. * @param[in] af Address family (SOCKET_AF_INET4 or SOCKET_AF_INET6), currently only IPv4 is supported * @retval SOCKET_ERROR_NONE on success * @retval SOCKET_ERROR_BAD_STACK if there is no valid underlying network stack * @retval SOCKET_ERROR_BAD_FAMILY if an invalid Address is supplied * @return Error code on failure */ virtual socket_error_t open(const socket_address_family_t af); protected: static minar::callback_handle_t _tick_handle; // uintptr_t is used to guarantee that there will always be a large enough // counter to avoid overflows. Memory allocation will always fail before // counter overflow if the counter is the same size as the pointer type and // sizeof(TCPAsynch) > 0 static uintptr_t _TCPSockets; private: socket_error_t open(const socket_address_family_t af, const socket_proto_family_t pf); }; } // namespace v0 } // namespace Sockets } // namespace mbed #endif // __MBED_NET_SOCKETS_V0_TCP_ASYNCH__ <|start_filename|>source/v0/TCPListener.cpp<|end_filename|> /* * PackageLicenseDeclared: Apache-2.0 * Copyright (c) 2015 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "sockets/v0/TCPListener.h" #include "sockets/v0/TCPStream.h" #include "sal/socket_api.h" #include "minar/minar.h" using namespace mbed::Sockets::v0; TCPListener::TCPListener(const socket_stack_t stack) : TCPAsynch(stack), _onIncoming(NULL) { } TCPListener::~TCPListener() { stop_listening(); } socket_error_t TCPListener::start_listening(IncomingHandler_t listenHandler, uint32_t backlog) { if (_socket.api == NULL) { return SOCKET_ERROR_BAD_STACK; } _onIncoming = listenHandler; socket_error_t err = _socket.api->start_listen(&_socket, backlog); return err; } socket_error_t TCPListener::stop_listening() { if (_socket.api == NULL) { return SOCKET_ERROR_BAD_STACK; } socket_error_t err = _socket.api->stop_listen(&_socket); return err; } TCPStream * TCPListener::accept(void *new_impl) { struct socket new_socket = _socket; new_socket.impl = new_impl; new_socket.stack = _socket.stack; new_socket.family = _socket.family; socket_error_t err; TCPStream * stream = new TCPStream(&_socket, &new_socket, err); if(err != SOCKET_ERROR_NONE) { delete stream; return NULL; } return stream; } void TCPListener::reject(void * impl) { //TODO: Add support for reject struct socket s; s.impl = impl; s.stack = _socket.stack; s.api = _socket.api; s.family = _socket.family; s.api->close(&s); } void TCPListener::_eventHandler(struct socket_event *ev) { switch(ev->event) { case SOCKET_EVENT_RX_ERROR: case SOCKET_EVENT_TX_ERROR: case SOCKET_EVENT_ERROR: if (_onError) minar::Scheduler::postCallback(_onError.bind(this, ev->i.e)); break; case SOCKET_EVENT_RX_DONE: case SOCKET_EVENT_TX_DONE: case SOCKET_EVENT_CONNECT: case SOCKET_EVENT_DISCONNECT: if(_onError) minar::Scheduler::postCallback(_onError.bind(this, SOCKET_ERROR_UNIMPLEMENTED)); break; case SOCKET_EVENT_DNS: if (_onDNS) minar::Scheduler::postCallback(_onDNS.bind(this, ev->i.d.addr, ev->i.d.domain)); break; case SOCKET_EVENT_ACCEPT: if (_onIncoming) minar::Scheduler::postCallback(_onIncoming.bind(this, ev->i.a.newimpl)); //TODO: write reject API break; case SOCKET_EVENT_NONE: default: break; } } <|start_filename|>sockets/v0/UDPSocket.h<|end_filename|> /* * PackageLicenseDeclared: Apache-2.0 * Copyright (c) 2015 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __SOCKETS_V0_UDPSOCKET_H__ #define __SOCKETS_V0_UDPSOCKET_H__ #include <stddef.h> #include <stdint.h> #include "Socket.h" namespace mbed { namespace Sockets { namespace v0 { /* UDP socket class */ class UDPSocket: public Socket { public: /** * UDP socket constructor. * Does not allocate an underlying UDP Socket instance. * @param[in] stack The network stack to use for this socket. */ UDPSocket(socket_stack_t stack); /** * UDP Socket destructor */ ~UDPSocket(); /** * Open a UDP socket * Instantiates and initializes the underlying socket. Receive is started immediately after * the socket is opened. * @param[in] af Address family (SOCKET_AF_INET4 or SOCKET_AF_INET6), currently only IPv4 is supported * @retval SOCKET_ERROR_NONE on success * @retval SOCKET_ERROR_BAD_FAMILY if an invalid Address is supplied * @return Error code on failure */ socket_error_t inline open(const socket_address_family_t af) { return Socket::open(af,SOCKET_DGRAM); } /** * Connect to a remote host. * This is an internal configuration API only. No network traffic is generated. * @param[in] address The remote host to connect to * @param[in] port The remote port to connect to * @retval SOCKET_ERROR_NONE on success * @retval SOCKET_ERROR_NULL_PTR if address is NULL * @return Error code on failure */ socket_error_t connect(const SocketAddr *address, const uint16_t port); private: socket_error_t open(const socket_address_family_t af, const socket_proto_family_t pf); }; } // namespace v0 } // namespace Sockets } // namespace mbed #endif // __SOCKETS_V0_UDPSOCKET_H__ <|start_filename|>source/v0/SocketAddr.cpp<|end_filename|> /* * PackageLicenseDeclared: Apache-2.0 * Copyright (c) 2015 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <string.h> #include <stdio.h> #include "sockets/v0/SocketAddr.h" #include "sal/socket_api.h" using namespace mbed::Sockets::v0; void SocketAddr::setAddr(const struct socket_addr *addr) { socket_addr_copy(&_addr, addr); } void SocketAddr::setAddr(const SocketAddr *addr) { setAddr(addr->getAddr()); } socket_error_t SocketAddr::setAddr(socket_address_family_t af, const char *addr) { int rc = inet_pton(af, addr, &_addr); // Convert from inet_pton return codes to -1/0 switch (rc) { case 1: return SOCKET_ERROR_NONE; case 0: return SOCKET_ERROR_BAD_ADDRESS; case -1: return SOCKET_ERROR_BAD_ARGUMENT; default: return SOCKET_ERROR_UNKNOWN; } } bool SocketAddr::is_v4() const { return socket_addr_is_ipv4(&_addr); } // Returns 0 on success int SocketAddr::fmtIPv4(char *buf, size_t size) const { if (!is_v4()){ return -1; } if (buf == NULL) { return -1; } char * ptr = inet_ntop(SOCKET_AF_INET4, &(_addr.ipv6be[3]), buf, size); return (ptr == NULL)?-1:0; } int SocketAddr::fmtIPv6(char *buf, size_t size) const { if (buf == NULL) { return -1; } char * ptr = inet_ntop(SOCKET_AF_INET6, &_addr, buf, size); return (ptr == NULL)?-1:0; } <|start_filename|>test/echo-udp-client/main.cpp<|end_filename|> /* * PackageLicenseDeclared: Apache-2.0 * Copyright (c) 2015 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "mbed-drivers/mbed.h" #include "sal/socket_api.h" #include <algorithm> #include "sockets/UDPSocket.h" #include "sal-iface-eth/EthernetInterface.h" #include "sal-stack-lwip/lwipv4_init.h" #include "minar/minar.h" #include "core-util/FunctionPointer.h" #include "greentea-client/test_env.h" #include "utest/utest.h" #include "unity/unity.h" #define CHECK(RC, STEP) if (RC < 0) error(STEP": %d\r\n", RC) using namespace utest::v1; using namespace mbed::Sockets::v0; namespace { const int BUFFER_SIZE = 64; const int MAX_ECHO_LOOPS = 100; const char ASCII_MAX = '~' - ' '; } char char_rand() { return (rand() % ASCII_MAX) + ' '; } #ifndef min #define min(A,B) \ ((A)<(B)?(A):(B)) #endif class UDPEchoClient; typedef mbed::util::FunctionPointer2<void, bool, UDPEchoClient*> fpterminate_t; void terminate(bool status, UDPEchoClient* client); char buffer[BUFFER_SIZE] = {0}; int port = 0; UDPEchoClient *client; EthernetInterface eth; class UDPEchoClient { public: UDPEchoClient(socket_stack_t stack) : _usock(stack) { _usock.setOnError(UDPSocket::ErrorHandler_t(this, &UDPEchoClient::onError)); } ~UDPEchoClient(){ if (_usock.isConnected()) _usock.close(); } void start_test(char * host_addr, uint16_t port) { loop_ctr = 0; _port = port; socket_error_t err = _usock.open(SOCKET_AF_INET4); TEST_ASSERT_EQUAL_MESSAGE(SOCKET_ERROR_NONE, err, "MBED: UDPClient unable to open socket" NL); printf("MBED: Trying to resolve address %s" NL, host_addr); err = _usock.resolve(host_addr,UDPSocket::DNSHandler_t(this, &UDPEchoClient::onDNS)); TEST_ASSERT_EQUAL_MESSAGE(SOCKET_ERROR_NONE, err, "MBED: UDPClient failed to resolve host server address" NL); } void onError(Socket *s, socket_error_t err) { (void) s; TEST_ASSERT_NOT_EQUAL(SOCKET_ERROR_NONE, err); printf("MBED: Socket Error: %s (%d)\r\n", socket_strerror(err), err); minar::Scheduler::postCallback(fpterminate_t(terminate).bind(false,this)); } void onDNS(Socket *s, struct socket_addr sa, const char * domain) { (void) s; /* Extract the Socket event to read the resolved address */ _resolvedAddr.setAddr(&sa); _resolvedAddr.fmtIPv6(out_buffer, sizeof(out_buffer)); printf("MBED: Resolved %s to %s\r\n", domain, out_buffer); /* TODO: add support for getting AF from addr */ socket_error_t err = _usock.open(SOCKET_AF_INET4); TEST_ASSERT_EQUAL_MESSAGE(SOCKET_ERROR_NONE, err, "MBED: UDPClient failed to open socket!" NL); /* Register the read handler */ _usock.setOnReadable(UDPSocket::ReadableHandler_t(this, &UDPEchoClient::onRx)); /* Send the query packet to the remote host */ send_test(); } void onRx(Socket *s) { (void) s; unsigned int n = sizeof(buffer); socket_error_t err = _usock.recv(buffer, &n); TEST_ASSERT_EQUAL_MESSAGE(SOCKET_ERROR_NONE, err, "MBED: UDPClient failed to recv data!" NL); int rc = memcmp(buffer, out_buffer, min(BUFFER_SIZE,n)); TEST_ASSERT_EQUAL_MESSAGE(0, rc, "MBED: UDPClient round trip data validation error!" NL); loop_ctr++; if (loop_ctr < MAX_ECHO_LOOPS) { send_test(); } if (loop_ctr >= MAX_ECHO_LOOPS) { _usock.send_to(buffer, strlen(buffer), &_resolvedAddr, _port); minar::Scheduler::postCallback(fpterminate_t(terminate).bind(true,this)); } } protected: void send_test() { std::generate(out_buffer, out_buffer + BUFFER_SIZE, char_rand); socket_error_t err = _usock.send_to(out_buffer, sizeof(BUFFER_SIZE), &_resolvedAddr, _port); TEST_ASSERT_EQUAL_MESSAGE(SOCKET_ERROR_NONE, err, "MBED: UDPClient failed to send data!" NL); } protected: UDPSocket _usock; SocketAddr _resolvedAddr; uint16_t _port; char out_buffer[BUFFER_SIZE]; char buffer[BUFFER_SIZE]; uint32_t loop_ctr; volatile bool done; }; void terminate(bool status, UDPEchoClient* ) { if (client) { printf("MBED: Test finished!"); delete client; client = NULL; eth.disconnect(); TEST_ASSERT_TRUE_MESSAGE(status, "MBED: test failed!"); Harness::validate_callback(); } } control_t test_echo_udp_client() { socket_error_t err = lwipv4_socket_init(); TEST_ASSERT_EQUAL_MESSAGE(SOCKET_ERROR_NONE, err, "Failed to init LWIPv4 socket!"); printf("MBED: Initializing ethernet connection." NL); //Use DHCP TEST_ASSERT_EQUAL_MESSAGE(0, eth.init(), "Failed to init LWIPv4 socket!"); eth.connect(); printf("MBED: IP Address is %s" NL, eth.getIPAddress()); greentea_send_kv("target_ip", eth.getIPAddress()); memset(buffer, 0, sizeof(buffer)); port = 0; printf("UDPClient waiting for server IP and port..." NL); char recv_key[] = "host_port"; char port_value[] = "65325"; greentea_send_kv("host_ip", " "); TEST_ASSERT_NOT_EQUAL_MESSAGE(0, greentea_parse_kv(recv_key, buffer, sizeof(recv_key), sizeof(buffer)), "MBED: Failed to recv/parse key value from host!"); greentea_send_kv("host_port", " "); TEST_ASSERT_NOT_EQUAL_MESSAGE(0, greentea_parse_kv(recv_key, port_value, sizeof(recv_key), sizeof(port_value)), "MBED: Failed to recv/parse key value from host!"); sscanf(port_value, "%d", &port); client = new UDPEchoClient(SOCKET_STACK_LWIP_IPV4); { mbed::util::FunctionPointer2<void, char *, uint16_t> fp(client, &UDPEchoClient::start_test); minar::Scheduler::postCallback(fp.bind(buffer, port)); } return CaseTimeout(25000); } // Cases -------------------------------------------------------------------------------------------------------------- Case cases[] = { Case("Test Echo UDP Client", test_echo_udp_client), }; status_t greentea_setup(const size_t number_of_cases) { // Handshake with greentea // Host test timeout should be more than target utest timeout to let target cleanup the test and send test summary. GREENTEA_SETUP(30, "udpecho_client_auto"); return greentea_test_setup_handler(number_of_cases); } void greentea_teardown(const size_t passed, const size_t failed, const failure_t failure) { greentea_test_teardown_handler(passed, failed, failure); GREENTEA_TESTSUITE_RESULT(failed == 0); } Specification specification(greentea_setup, cases, greentea_teardown); void app_start(int, char*[]) { Harness::run(specification); } <|start_filename|>sockets/v0/Socket.h<|end_filename|> /* * PackageLicenseDeclared: Apache-2.0 * Copyright (c) 2015 ARM Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __SOCKETS_V0_SOCKET_H__ #define __SOCKETS_V0_SOCKET_H__ #include <stddef.h> #include <stdint.h> #include "mbed-drivers/mbed.h" #include "core-util/FunctionPointer.h" #include "mbed-drivers/CThunk.h" #include "sal/socket_types.h" #include "SocketAddr.h" namespace mbed { namespace Sockets { namespace v0 { /** * \brief Socket implements most of the interfaces required for sockets. * Socket is a pure virtual class; it should never be instantiated directly, but it provides * common functionality for derived classes. */ class Socket { public: typedef mbed::util::FunctionPointer3<void, Socket *, struct socket_addr, const char *> DNSHandler_t; typedef mbed::util::FunctionPointer2<void, Socket *, socket_error_t> ErrorHandler_t; typedef mbed::util::FunctionPointer1<void, Socket *> ReadableHandler_t; typedef mbed::util::FunctionPointer2<void, Socket *, uint16_t> SentHandler_t; protected: /** * Socket constructor * Initializes the Socket object. Initializes the underlying struct socket. Does not instantiate * an underlying network stack socket. * Since it is somewhat awkward to provide the network stack, a future change will provide * a way to pass the network interface to the socket constructor, which will extract the stack from * the interface. * @param[in] stack The network stack to use for this socket. */ Socket(const socket_stack_t stack); /** * Socket destructor * Frees the underlying socket implementation. */ virtual ~Socket(); public: /** * Start the process of resolving a domain name. * If the input is a text IP address, an event is queued immediately; otherwise, onDNS is * queued as soon as DNS is resolved. * @param[in] address The domain name to resolve * @param[in] onDNS The handler to call when the name is resolved * @retval SOCKET_ERROR_NONE on success * @retval SOCKET_ERROR_NULL_PTR if address is NULL * @return Error code on failure */ virtual socket_error_t resolve(const char* address, const DNSHandler_t &onDNS); /** * Open the socket. * Instantiates and initializes the underlying socket. Receive is started immediately after * the socket is opened. * @param[in] af Address family (SOCKET_AF_INET4 or SOCKET_AF_INET6), currently only IPv4 is supported * @param[in] pf Protocol family (SOCKET_DGRAM or SOCKET_STREAM) * @retval SOCKET_ERROR_NONE on success * @retval SOCKET_ERROR_BAD_STACK if there is no valid underlying network stack * @retval SOCKET_ERROR_BAD_FAMILY if an invalid Address or Protocol family is supplied * @return Error code on failure */ virtual socket_error_t open(const socket_address_family_t af, const socket_proto_family_t pf); /** * Binds the socket's local address and IP. * 0.0.0.0 is accepted as a local address if only the port is meant to be bound. * The behaviour of bind("0.0.0.0",...) is undefined where two or more stacks are in use. * Specifying a port value of 0, will instruct the stack to allocate an available port * automatically. * * @param[in] address The string representation of the address to bind * @param[in] port The local port to bind * @retval SOCKET_ERROR_NONE on success * @retval SOCKET_ERROR_NULL_PTR if the socket has not been opened or the address is NULL * @return Error code on failure */ virtual socket_error_t bind(const char *address, const uint16_t port); /** * bind(const SocketAddr *, const uint16_t) is the same as bind(const char *, const uint16_t), * except that the address passed in is a SocketAddr. * @param[in] address The address to bind * @param[in] port The local port to bind * @retval SOCKET_ERROR_NONE on success * @retval SOCKET_ERROR_NULL_PTR if the supplied address is NULL * @return Error code on failure */ virtual socket_error_t bind(const SocketAddr *address, const uint16_t port); /** * Set the error handler. * Errors are ignored if onError is not set. * @param[in] onError */ virtual void setOnError(const ErrorHandler_t &onError); /** * Set the received data handler * Received data is queued until it is read using recv or recv_from. * @param[in] onReadable the handler to use for receive events */ virtual void setOnReadable(const ReadableHandler_t &onReadable); /** * Receive a message * @param[out] buf The buffer to fill * @param[in,out] len A pointer to the size of the receive buffer. Sets the maximum number of bytes * to read but is updated with the actual number of bytes copied on success. len is not changed on * failure * @retval SOCKET_ERROR_NONE on success * @retval SOCKET_ERROR_NULL_PTR if the socket has not been opened, buf is NULL or len is NULL * @return Error code on failure */ virtual socket_error_t recv(void * buf, size_t *len); /** * Receive a message with the sender address and port * This API is not valid for SOCK_STREAM * @param[out] buf The buffer to fill * @param[in,out] len A pointer to the size of the receive buffer. Sets the maximum number of bytes * to read but is updated with the actual number of bytes copied on success. len is not changed on * failure * @param[out] remote_addr Pointer to an address structure to fill with the sender address * @param[out] remote_port Pointer to a uint16_t to fill with the sender port * @retval SOCKET_ERROR_NONE on success * @retval SOCKET_ERROR_NULL_PTR if the socket has not been opened or any of the pointer arguments * are NULL * @return Error code on failure */ virtual socket_error_t recv_from(void * buf, size_t *len, SocketAddr *remote_addr, uint16_t *remote_port); /** * Set the onSent handler. * The exact moment this handler is called varies from implementation to implementation. * On LwIP, onSent is called when the remote host ACK's data in TCP sockets, or when the message enters * the network stack in UDP sockets. * @param[in] onSent The handler to call when a send completes */ virtual void setOnSent(const SentHandler_t &onSent); /** * Send a message * Sends a message over an open connection. This call is valid for UDP sockets, provided that connect() * has been called. * @param[in] buf The payload to send * @param[in] len The size of the payload * @retval SOCKET_ERROR_NONE on success * @retval SOCKET_ERROR_NULL_PTR if the socket has not been opened or buf is NULL * @return Error code on failure */ virtual socket_error_t send(const void * buf, const size_t len); /** * Send a message to a specific address and port * This API is not valid for SOCK_STREAM * @param[in] buf The payload to send * @param[in] len The size of the payload * @param[in] address The address to send to * @param[in] port The remote port to send to * @retval SOCKET_ERROR_NONE on success * @retval SOCKET_ERROR_NULL_PTR if the socket has not been opened, buf is NULL or the * remote_addr is NULL * @return Error code on failure */ virtual socket_error_t send_to(const void * buf, const size_t len, const SocketAddr *remote_addr, uint16_t remote_port); /** * Shuts down a socket. * Sending and receiving are no longer possible after close() is called. * The socket is not deallocated on close. A socket must not be reopened, it should be * destroyed (either with delete, or by going out of scope) after calling close. * Calling open on a closed socket can result in a memory leak. * @retval SOCKET_ERROR_NONE on success * @retval SOCKET_ERROR_NULL_PTR if the socket has not been opened * @return Error code on failure */ virtual socket_error_t close(); /** * Error checking utility * Generates an event on error, does nothing on SOCKET_ERROR_NONE * @param[in] err the error code to check * @return false if err is SOCKET_ERROR_NONE, true otherwise */ virtual bool error_check(socket_error_t err); /** * Checks the socket status to determine whether it is still connected. * @return true if the socket is connected, false if it is not */ virtual bool isConnected() const; /** * Get the local address of the socket if bound. * Populates the SocketAddr object with the local address * * @param[out] addr a pointer to a SocketAddr object * @retval SOCKET_ERROR_NONE on success * @retval SOCKET_ERROR_NULL_PTR if the socket has not been opened or the addr is NULL * @retval SOCKET_ERROR_NOT_BOUND if the socket has not been bound * @return Error code on failure */ virtual socket_error_t getLocalAddr(SocketAddr *addr) const; /** * Get the local port of the socket if bound. * Populates the uint16_t object with the local port * * @param[out] port a pointer to a uint16_t * @retval SOCKET_ERROR_NONE on success * @retval SOCKET_ERROR_NULL_PTR if the socket has not been opened or the port is NULL * @retval SOCKET_ERROR_NOT_BOUND if the socket has not been bound * @return Error code on failure */ virtual socket_error_t getLocalPort(uint16_t *port) const; /** * Get the remote address of the socket if connected. * Populates the SocketAddr object with the remote address * * @param[out] addr a pointer to a SocketAddr object * @retval SOCKET_ERROR_NONE on success * @retval SOCKET_ERROR_NULL_PTR if the socket has not been opened or the addr is NULL * @retval SOCKET_ERROR_NO_CONNECTION if the socket has not been connected * @return Error code on failure */ virtual socket_error_t getRemoteAddr(SocketAddr *addr) const; /** * Get the remote port of the socket if connected. * Populates the uint16_t object with the remote port * * @param[out] port a pointer to a uint16_t * @retval SOCKET_ERROR_NONE on success * @retval SOCKET_ERROR_NULL_PTR if the socket has not been opened or the port is NULL * @retval SOCKET_ERROR_NO_CONNECTION if the socket has not been connected * @return Error code on failure */ virtual socket_error_t getRemotePort(uint16_t *port) const; #if 0 // not implemented yet static long ntohl(long); static short ntohs(short); static long long ntohll(long long); #endif protected: /** \internal * The internal event handler * @param[in] ev The event to handle */ virtual void _eventHandler(struct socket_event *ev); protected: /** Function pointer to the user-supplied DNS response handling function * \internal * This function pointer is called every time a DNS response is received. * If the function pointer is false when cast to a boolean, DNS events are discarded. */ DNSHandler_t _onDNS; /** Function pointer to the user-supplied error handling function * \internal * This function pointer is called when an error condition is encountered in a part * of the code which does not have a direct call path back to user-supplied code * If NULL, error handling is discarded. */ ErrorHandler_t _onError; /** Function pointer to the user-supplied data available handling function * This function pointer is called when data is available on the socket. It is called once for * each event generated by the socket layer, so partial reads can leave data available on the * socket and greedy reads can cause extra events with no data to read. * Suggested handling is to use greedy reads and terminate early in events with no */ ReadableHandler_t _onReadable; ///< Function pointer to the user-supplied socket readable function SentHandler_t _onSent; CThunk<Socket> _irq; public: struct socket _socket; private: socket_event_t *_event; /** * Internal event handler. * @param[in] arg */ void _nvEventHandler(void * arg); }; } // namespace v0 } // namespace Sockets } // namespace mbed #endif // __SOCKETS_V0_SOCKET_H__
ARMmbed/sockets
<|start_filename|>starter/src/templates/page.js<|end_filename|> import React from "react" import { graphql } from "gatsby" import Layout from "@/components/layout" import Sections from "@/components/sections" import SEO from "@/components/seo" const DynamicPage = ({ data, pageContext }) => { const { contentSections, metadata, localizations } = data.strapiPage const global = data.strapiGlobal return ( <> <SEO seo={metadata} global={global} /> <Layout global={global} pageContext={{ ...pageContext, localizations }}> <Sections sections={contentSections} /> </Layout> </> ) } export default DynamicPage export const query = graphql` fragment GlobalData on StrapiGlobal { favicon { localFile { publicURL } } footer { id columns { id links { id newTab text url } title } id logo { alternativeText localFile { childImageSharp { gatsbyImageData( placeholder: BLURRED formats: [AUTO, WEBP, AVIF] ) } } } smallText } id metaTitleSuffix metadata { metaDescription metaTitle shareImage { localFile { publicURL } } } navbar { button { id newTab text type url } id links { url text newTab id } logo { localFile { childImageSharp { gatsbyImageData( placeholder: BLURRED formats: [AUTO, WEBP, AVIF] ) } } } } notificationBanner { id text type } } query DynamicPageQuery($id: String!, $locale: String!) { strapiGlobal(locale: { eq: $locale }) { ...GlobalData } strapiPage(id: { eq: $id }) { slug shortName metadata { metaTitle metaDescription shareImage { localFile { publicURL } } } localizations { id locale } contentSections } } `
thek1d21/webify-corporate
<|start_filename|>example/file-upload/server.js<|end_filename|> var main = require('./logic.js'); var express = require('express'); var app = express(); var bodyParser = require('body-parser'); app.listen(3000) var connector = require('http-connector')(); console.log("check localhost:3000"); var PromisePipe = main.PromisePipe; app.use(bodyParser.json()) app.use(express.static("./")) PromisePipe.stream('server','client').connector(connector.HTTPServerClientStream(app)) <|start_filename|>example/simple-todo/package.json<|end_filename|> { "name": "promise-pipe-example", "version": "0.0.1", "description": "##install", "scripts": { "start": "node node_modules/browserify/bin/cmd.js -r ./client.js:client > bundle.js;node server.js" }, "repository": { "type": "git", "url": "git://github.com/edjafarov/PromisePipe.git" }, "author": "", "license": "ISC", "bugs": { "url": "https://github.com/edjafarov/PromisePipe/issues" }, "homepage": "https://github.com/edjafarov/PromisePipe", "dependencies": { "promise-pipe": "*", "express": "~4.12.3", "socket.io": "~1.3.5", "es6-promise": "~2.1.1" }, "devDependencies": { "browserify": "~9.0.7" } } <|start_filename|>example/auction/src/actions.js<|end_filename|> var chain = require('./serverChains/chains'); export default function(PromisePipe){ return { login: PromisePipe() .then(chain.verifyCredentials) .then(chain.putUserInSession) .emit("me:success") .redirect('/') .catch((err, context)=>{ console.log(err) context.client.emit('login:fail', err); }), logout: PromisePipe() .then(chain.crearUserFromSession) .emit("me:logout"), getSession: PromisePipe() .then(chain.getCurrentUser) .emit("me:success"), makeABid: PromisePipe() .then(chain.makeABid) .then(chain.getItemsByIds) .then(chain.addBidIds) .then(chain.broadcast), watch: PromisePipe() .then(chain.watch) } } <|start_filename|>example/PPRouter/example/src/router.js<|end_filename|> import RouterFactory from "../../index" var Router = RouterFactory(); Router(function(Router){ Router('/items', function(Router){ Router('/:id').component(itemComp).then(getItem); }).component(itemsComp).then(getItems); }).component(rootComp).then(count) function itemComp(params){ return `<div> <label>ID: ${params.data.id}</label> <h5>name: ${params.data.name}</h5> <p>${params.data.description}</p> ${params.children || ''} </div>` } function itemsComp(params){ var items = params.data.map(item => `<li><a href="/items/${item.id}">${item.name}</a></li>`).join(""); return `<div> <ul>${items}</ul> ${params.children || ''} </div>` } function rootComp(params){ return `<div> <h1><a href="/">Router Example APP</a> (${params.data || 0})</h1> <a href="/items">Items</a> ${params.children || ''} </div>` } function getItems(){ return new Promise(function(resolve, reject){ setTimeout(function(){ resolve(Items); }, 100); }) } function getItem(data, context){ return Items.reduce(function(result, item){ if(result) return result; if(item.id == context.params.id) return item; }, null); } function count(){ return new Promise(function(resolve, reject){ setTimeout(function(){ resolve(Items.length); }, 100); }) } var Items = [ { id:1, name: "Item1", description: "The Item Description" }, { id:2, name: "Item2", description: "The Item2 Description" }, { id:3, name: "Item3", description: "The Item3 Description" } ]; export var Router = Router; <|start_filename|>example/auction/src/stores/BasicStore.js<|end_filename|> var Emitter = require('events').EventEmitter; module.exports = function StoreFactory(storeName, base){ base = Object.keys(base).reduce(function(context, name){ context[name] = { configurable: false, enumerable: false, writable: typeof(base[name]) !== 'function', value: base[name] } return context; },{}); base.name = { configurable: false, enumerable: false, writable: false, value: storeName } return { name: storeName, create: function(){ return Object.create(new Emitter(), base); } } } <|start_filename|>example/mongotodo-api/api.server.js<|end_filename|> var main = require('./api.logic.js'); var express = require('express'); var app = express(); var server = require('http').Server(app); var io = require('socket.io')(server); var cookieParser = require('cookie-parser'); var expressSession = require('express-session'); var MongoStore = require('connect-mongo')(expressSession); var connectors = require('../connectors/SessionSocketIODuplexStream') var myCookieParser = cookieParser('secret'); var sessionStore = new MongoStore({ url: process.env.MONGOHQ_URL || "mongodb://localhost:27017/test" }); server.listen(process.env.PORT || 3333) console.log("check localhost:" + process.env.PORT || 3333); var PromisePipe = main.PromisePipe; app.use(myCookieParser); app.use(expressSession({ secret: 'secret', store: sessionStore })); var SessionSockets = require('session.socket.io') , sessionSockets = new SessionSockets(io, sessionStore, myCookieParser); var SocketIOSRC = require('fs').readFileSync("node_modules/socket.io/node_modules/socket.io-client/socket.io.js").toString(); var addSockets = 'var socket = io.connect("http://localhost:3333");\n' var addConnector = "var connector = (" + connectors.SIOClientServerStream.toString() + ")(socket)\n"; var PromiseSRC = require('fs').readFileSync("node_modules/es6-promise/dist/es6-promise.js").toString(); var PromiseInject = "var PromiseObj = {};var module,define;(function(self){\n" + PromiseSRC + "})(PromiseObj);var Promise = PromiseObj.Promise;\n"; var SocketIOInject = "var SocketIOObj = {exports:{}};(function(exports, module){\n" + SocketIOSRC + "})(SocketIOObj.exports, SocketIOObj);var io = SocketIOObj.exports;\n"; var returnAPI = 'return (' + PromisePipe.api.provide(connectors.SIOServerClientStream(sessionSockets)) + ")(connector)"; var ApiSRC = "window.exampleAPI = (function(){\n" + SocketIOInject + addSockets + addConnector + PromiseInject + returnAPI+ "\n})(); console.log(exampleAPI);"; app.use(function(req, res, next){ //console.log(req.originalUrl); if(req.originalUrl === "/ppApi"){ res.setHeader('content-type', 'text/javascript'); res.end(ApiSRC); } }) <|start_filename|>example/PPRouter/router.js<|end_filename|> var commonObj = {}; var realRequire = require; var define, requireModule, require, requirejs; /*! * @overview RSVP - a tiny implementation of Promises/A+. * @copyright Copyright (c) 2014 <NAME>, <NAME>, <NAME> and contributors * @license Licensed under MIT license * See https://raw.githubusercontent.com/tildeio/rsvp.js/master/LICENSE * @version 3.0.18 */ (function() { "use strict"; function lib$rsvp$utils$$objectOrFunction(x) { return typeof x === 'function' || (typeof x === 'object' && x !== null); } function lib$rsvp$utils$$isFunction(x) { return typeof x === 'function'; } function lib$rsvp$utils$$isMaybeThenable(x) { return typeof x === 'object' && x !== null; } var lib$rsvp$utils$$_isArray; if (!Array.isArray) { lib$rsvp$utils$$_isArray = function (x) { return Object.prototype.toString.call(x) === '[object Array]'; }; } else { lib$rsvp$utils$$_isArray = Array.isArray; } var lib$rsvp$utils$$isArray = lib$rsvp$utils$$_isArray; var lib$rsvp$utils$$now = Date.now || function() { return new Date().getTime(); }; function lib$rsvp$utils$$F() { } var lib$rsvp$utils$$o_create = (Object.create || function (o) { if (arguments.length > 1) { throw new Error('Second argument not supported'); } if (typeof o !== 'object') { throw new TypeError('Argument must be an object'); } lib$rsvp$utils$$F.prototype = o; return new lib$rsvp$utils$$F(); }); function lib$rsvp$events$$indexOf(callbacks, callback) { for (var i=0, l=callbacks.length; i<l; i++) { if (callbacks[i] === callback) { return i; } } return -1; } function lib$rsvp$events$$callbacksFor(object) { var callbacks = object._promiseCallbacks; if (!callbacks) { callbacks = object._promiseCallbacks = {}; } return callbacks; } var lib$rsvp$events$$default = { /** `RSVP.EventTarget.mixin` extends an object with EventTarget methods. For Example: ```javascript var object = {}; RSVP.EventTarget.mixin(object); object.on('finished', function(event) { // handle event }); object.trigger('finished', { detail: value }); ``` `EventTarget.mixin` also works with prototypes: ```javascript var Person = function() {}; RSVP.EventTarget.mixin(Person.prototype); var yehuda = new Person(); var tom = new Person(); yehuda.on('poke', function(event) { console.log('Yehuda says OW'); }); tom.on('poke', function(event) { console.log('Tom says OW'); }); yehuda.trigger('poke'); tom.trigger('poke'); ``` @method mixin @for RSVP.EventTarget @private @param {Object} object object to extend with EventTarget methods */ 'mixin': function(object) { object['on'] = this['on']; object['off'] = this['off']; object['trigger'] = this['trigger']; object._promiseCallbacks = undefined; return object; }, /** Registers a callback to be executed when `eventName` is triggered ```javascript object.on('event', function(eventInfo){ // handle the event }); object.trigger('event'); ``` @method on @for RSVP.EventTarget @private @param {String} eventName name of the event to listen for @param {Function} callback function to be called when the event is triggered. */ 'on': function(eventName, callback) { var allCallbacks = lib$rsvp$events$$callbacksFor(this), callbacks; callbacks = allCallbacks[eventName]; if (!callbacks) { callbacks = allCallbacks[eventName] = []; } if (lib$rsvp$events$$indexOf(callbacks, callback) === -1) { callbacks.push(callback); } }, /** You can use `off` to stop firing a particular callback for an event: ```javascript function doStuff() { // do stuff! } object.on('stuff', doStuff); object.trigger('stuff'); // doStuff will be called // Unregister ONLY the doStuff callback object.off('stuff', doStuff); object.trigger('stuff'); // doStuff will NOT be called ``` If you don't pass a `callback` argument to `off`, ALL callbacks for the event will not be executed when the event fires. For example: ```javascript var callback1 = function(){}; var callback2 = function(){}; object.on('stuff', callback1); object.on('stuff', callback2); object.trigger('stuff'); // callback1 and callback2 will be executed. object.off('stuff'); object.trigger('stuff'); // callback1 and callback2 will not be executed! ``` @method off @for RSVP.EventTarget @private @param {String} eventName event to stop listening to @param {Function} callback optional argument. If given, only the function given will be removed from the event's callback queue. If no `callback` argument is given, all callbacks will be removed from the event's callback queue. */ 'off': function(eventName, callback) { var allCallbacks = lib$rsvp$events$$callbacksFor(this), callbacks, index; if (!callback) { allCallbacks[eventName] = []; return; } callbacks = allCallbacks[eventName]; index = lib$rsvp$events$$indexOf(callbacks, callback); if (index !== -1) { callbacks.splice(index, 1); } }, /** Use `trigger` to fire custom events. For example: ```javascript object.on('foo', function(){ console.log('foo event happened!'); }); object.trigger('foo'); // 'foo event happened!' logged to the console ``` You can also pass a value as a second argument to `trigger` that will be passed as an argument to all event listeners for the event: ```javascript object.on('foo', function(value){ console.log(value.name); }); object.trigger('foo', { name: 'bar' }); // 'bar' logged to the console ``` @method trigger @for RSVP.EventTarget @private @param {String} eventName name of the event to be triggered @param {Any} options optional value to be passed to any event handlers for the given `eventName` */ 'trigger': function(eventName, options) { var allCallbacks = lib$rsvp$events$$callbacksFor(this), callbacks, callback; if (callbacks = allCallbacks[eventName]) { // Don't cache the callbacks.length since it may grow for (var i=0; i<callbacks.length; i++) { callback = callbacks[i]; callback(options); } } } }; var lib$rsvp$config$$config = { instrument: false }; lib$rsvp$events$$default['mixin'](lib$rsvp$config$$config); function lib$rsvp$config$$configure(name, value) { if (name === 'onerror') { // handle for legacy users that expect the actual // error to be passed to their function added via // `RSVP.configure('onerror', someFunctionHere);` lib$rsvp$config$$config['on']('error', value); return; } if (arguments.length === 2) { lib$rsvp$config$$config[name] = value; } else { return lib$rsvp$config$$config[name]; } } var lib$rsvp$instrument$$queue = []; function lib$rsvp$instrument$$scheduleFlush() { setTimeout(function() { var entry; for (var i = 0; i < lib$rsvp$instrument$$queue.length; i++) { entry = lib$rsvp$instrument$$queue[i]; var payload = entry.payload; payload.guid = payload.key + payload.id; payload.childGuid = payload.key + payload.childId; if (payload.error) { payload.stack = payload.error.stack; } lib$rsvp$config$$config['trigger'](entry.name, entry.payload); } lib$rsvp$instrument$$queue.length = 0; }, 50); } function lib$rsvp$instrument$$instrument(eventName, promise, child) { if (1 === lib$rsvp$instrument$$queue.push({ name: eventName, payload: { key: promise._guidKey, id: promise._id, eventName: eventName, detail: promise._result, childId: child && child._id, label: promise._label, timeStamp: lib$rsvp$utils$$now(), error: lib$rsvp$config$$config["instrument-with-stack"] ? new Error(promise._label) : null }})) { lib$rsvp$instrument$$scheduleFlush(); } } var lib$rsvp$instrument$$default = lib$rsvp$instrument$$instrument; function lib$rsvp$$internal$$withOwnPromise() { return new TypeError('A promises callback cannot return that same promise.'); } function lib$rsvp$$internal$$noop() {} var lib$rsvp$$internal$$PENDING = void 0; var lib$rsvp$$internal$$FULFILLED = 1; var lib$rsvp$$internal$$REJECTED = 2; var lib$rsvp$$internal$$GET_THEN_ERROR = new lib$rsvp$$internal$$ErrorObject(); function lib$rsvp$$internal$$getThen(promise) { try { return promise.then; } catch(error) { lib$rsvp$$internal$$GET_THEN_ERROR.error = error; return lib$rsvp$$internal$$GET_THEN_ERROR; } } function lib$rsvp$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) { try { then.call(value, fulfillmentHandler, rejectionHandler); } catch(e) { return e; } } function lib$rsvp$$internal$$handleForeignThenable(promise, thenable, then) { lib$rsvp$config$$config.async(function(promise) { var sealed = false; var error = lib$rsvp$$internal$$tryThen(then, thenable, function(value) { if (sealed) { return; } sealed = true; if (thenable !== value) { lib$rsvp$$internal$$resolve(promise, value); } else { lib$rsvp$$internal$$fulfill(promise, value); } }, function(reason) { if (sealed) { return; } sealed = true; lib$rsvp$$internal$$reject(promise, reason); }, 'Settle: ' + (promise._label || ' unknown promise')); if (!sealed && error) { sealed = true; lib$rsvp$$internal$$reject(promise, error); } }, promise); } function lib$rsvp$$internal$$handleOwnThenable(promise, thenable) { if (thenable._state === lib$rsvp$$internal$$FULFILLED) { lib$rsvp$$internal$$fulfill(promise, thenable._result); } else if (thenable._state === lib$rsvp$$internal$$REJECTED) { thenable._onError = null; lib$rsvp$$internal$$reject(promise, thenable._result); } else { lib$rsvp$$internal$$subscribe(thenable, undefined, function(value) { if (thenable !== value) { lib$rsvp$$internal$$resolve(promise, value); } else { lib$rsvp$$internal$$fulfill(promise, value); } }, function(reason) { lib$rsvp$$internal$$reject(promise, reason); }); } } function lib$rsvp$$internal$$handleMaybeThenable(promise, maybeThenable) { if (maybeThenable.constructor === promise.constructor) { lib$rsvp$$internal$$handleOwnThenable(promise, maybeThenable); } else { var then = lib$rsvp$$internal$$getThen(maybeThenable); if (then === lib$rsvp$$internal$$GET_THEN_ERROR) { lib$rsvp$$internal$$reject(promise, lib$rsvp$$internal$$GET_THEN_ERROR.error); } else if (then === undefined) { lib$rsvp$$internal$$fulfill(promise, maybeThenable); } else if (lib$rsvp$utils$$isFunction(then)) { lib$rsvp$$internal$$handleForeignThenable(promise, maybeThenable, then); } else { lib$rsvp$$internal$$fulfill(promise, maybeThenable); } } } function lib$rsvp$$internal$$resolve(promise, value) { if (promise === value) { lib$rsvp$$internal$$fulfill(promise, value); } else if (lib$rsvp$utils$$objectOrFunction(value)) { lib$rsvp$$internal$$handleMaybeThenable(promise, value); } else { lib$rsvp$$internal$$fulfill(promise, value); } } function lib$rsvp$$internal$$publishRejection(promise) { if (promise._onError) { promise._onError(promise._result); } lib$rsvp$$internal$$publish(promise); } function lib$rsvp$$internal$$fulfill(promise, value) { if (promise._state !== lib$rsvp$$internal$$PENDING) { return; } promise._result = value; promise._state = lib$rsvp$$internal$$FULFILLED; if (promise._subscribers.length === 0) { if (lib$rsvp$config$$config.instrument) { lib$rsvp$instrument$$default('fulfilled', promise); } } else { lib$rsvp$config$$config.async(lib$rsvp$$internal$$publish, promise); } } function lib$rsvp$$internal$$reject(promise, reason) { if (promise._state !== lib$rsvp$$internal$$PENDING) { return; } promise._state = lib$rsvp$$internal$$REJECTED; promise._result = reason; lib$rsvp$config$$config.async(lib$rsvp$$internal$$publishRejection, promise); } function lib$rsvp$$internal$$subscribe(parent, child, onFulfillment, onRejection) { var subscribers = parent._subscribers; var length = subscribers.length; parent._onError = null; subscribers[length] = child; subscribers[length + lib$rsvp$$internal$$FULFILLED] = onFulfillment; subscribers[length + lib$rsvp$$internal$$REJECTED] = onRejection; if (length === 0 && parent._state) { lib$rsvp$config$$config.async(lib$rsvp$$internal$$publish, parent); } } function lib$rsvp$$internal$$publish(promise) { var subscribers = promise._subscribers; var settled = promise._state; if (lib$rsvp$config$$config.instrument) { lib$rsvp$instrument$$default(settled === lib$rsvp$$internal$$FULFILLED ? 'fulfilled' : 'rejected', promise); } if (subscribers.length === 0) { return; } var child, callback, detail = promise._result; for (var i = 0; i < subscribers.length; i += 3) { child = subscribers[i]; callback = subscribers[i + settled]; if (child) { lib$rsvp$$internal$$invokeCallback(settled, child, callback, detail); } else { callback(detail); } } promise._subscribers.length = 0; } function lib$rsvp$$internal$$ErrorObject() { this.error = null; } var lib$rsvp$$internal$$TRY_CATCH_ERROR = new lib$rsvp$$internal$$ErrorObject(); function lib$rsvp$$internal$$tryCatch(callback, detail) { try { return callback(detail); } catch(e) { lib$rsvp$$internal$$TRY_CATCH_ERROR.error = e; return lib$rsvp$$internal$$TRY_CATCH_ERROR; } } function lib$rsvp$$internal$$invokeCallback(settled, promise, callback, detail) { var hasCallback = lib$rsvp$utils$$isFunction(callback), value, error, succeeded, failed; if (hasCallback) { value = lib$rsvp$$internal$$tryCatch(callback, detail); if (value === lib$rsvp$$internal$$TRY_CATCH_ERROR) { failed = true; error = value.error; value = null; } else { succeeded = true; } if (promise === value) { lib$rsvp$$internal$$reject(promise, lib$rsvp$$internal$$withOwnPromise()); return; } } else { value = detail; succeeded = true; } if (promise._state !== lib$rsvp$$internal$$PENDING) { // noop } else if (hasCallback && succeeded) { lib$rsvp$$internal$$resolve(promise, value); } else if (failed) { lib$rsvp$$internal$$reject(promise, error); } else if (settled === lib$rsvp$$internal$$FULFILLED) { lib$rsvp$$internal$$fulfill(promise, value); } else if (settled === lib$rsvp$$internal$$REJECTED) { lib$rsvp$$internal$$reject(promise, value); } } function lib$rsvp$$internal$$initializePromise(promise, resolver) { var resolved = false; try { resolver(function resolvePromise(value){ if (resolved) { return; } resolved = true; lib$rsvp$$internal$$resolve(promise, value); }, function rejectPromise(reason) { if (resolved) { return; } resolved = true; lib$rsvp$$internal$$reject(promise, reason); }); } catch(e) { lib$rsvp$$internal$$reject(promise, e); } } function lib$rsvp$enumerator$$makeSettledResult(state, position, value) { if (state === lib$rsvp$$internal$$FULFILLED) { return { state: 'fulfilled', value: value }; } else { return { state: 'rejected', reason: value }; } } function lib$rsvp$enumerator$$Enumerator(Constructor, input, abortOnReject, label) { this._instanceConstructor = Constructor; this.promise = new Constructor(lib$rsvp$$internal$$noop, label); this._abortOnReject = abortOnReject; if (this._validateInput(input)) { this._input = input; this.length = input.length; this._remaining = input.length; this._init(); if (this.length === 0) { lib$rsvp$$internal$$fulfill(this.promise, this._result); } else { this.length = this.length || 0; this._enumerate(); if (this._remaining === 0) { lib$rsvp$$internal$$fulfill(this.promise, this._result); } } } else { lib$rsvp$$internal$$reject(this.promise, this._validationError()); } } var lib$rsvp$enumerator$$default = lib$rsvp$enumerator$$Enumerator; lib$rsvp$enumerator$$Enumerator.prototype._validateInput = function(input) { return lib$rsvp$utils$$isArray(input); }; lib$rsvp$enumerator$$Enumerator.prototype._validationError = function() { return new Error('Array Methods must be provided an Array'); }; lib$rsvp$enumerator$$Enumerator.prototype._init = function() { this._result = new Array(this.length); }; lib$rsvp$enumerator$$Enumerator.prototype._enumerate = function() { var length = this.length; var promise = this.promise; var input = this._input; for (var i = 0; promise._state === lib$rsvp$$internal$$PENDING && i < length; i++) { this._eachEntry(input[i], i); } }; lib$rsvp$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) { var c = this._instanceConstructor; if (lib$rsvp$utils$$isMaybeThenable(entry)) { if (entry.constructor === c && entry._state !== lib$rsvp$$internal$$PENDING) { entry._onError = null; this._settledAt(entry._state, i, entry._result); } else { this._willSettleAt(c.resolve(entry), i); } } else { this._remaining--; this._result[i] = this._makeResult(lib$rsvp$$internal$$FULFILLED, i, entry); } }; lib$rsvp$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) { var promise = this.promise; if (promise._state === lib$rsvp$$internal$$PENDING) { this._remaining--; if (this._abortOnReject && state === lib$rsvp$$internal$$REJECTED) { lib$rsvp$$internal$$reject(promise, value); } else { this._result[i] = this._makeResult(state, i, value); } } if (this._remaining === 0) { lib$rsvp$$internal$$fulfill(promise, this._result); } }; lib$rsvp$enumerator$$Enumerator.prototype._makeResult = function(state, i, value) { return value; }; lib$rsvp$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) { var enumerator = this; lib$rsvp$$internal$$subscribe(promise, undefined, function(value) { enumerator._settledAt(lib$rsvp$$internal$$FULFILLED, i, value); }, function(reason) { enumerator._settledAt(lib$rsvp$$internal$$REJECTED, i, reason); }); }; function lib$rsvp$promise$all$$all(entries, label) { return new lib$rsvp$enumerator$$default(this, entries, true /* abort on reject */, label).promise; } var lib$rsvp$promise$all$$default = lib$rsvp$promise$all$$all; function lib$rsvp$promise$race$$race(entries, label) { /*jshint validthis:true */ var Constructor = this; var promise = new Constructor(lib$rsvp$$internal$$noop, label); if (!lib$rsvp$utils$$isArray(entries)) { lib$rsvp$$internal$$reject(promise, new TypeError('You must pass an array to race.')); return promise; } var length = entries.length; function onFulfillment(value) { lib$rsvp$$internal$$resolve(promise, value); } function onRejection(reason) { lib$rsvp$$internal$$reject(promise, reason); } for (var i = 0; promise._state === lib$rsvp$$internal$$PENDING && i < length; i++) { lib$rsvp$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); } return promise; } var lib$rsvp$promise$race$$default = lib$rsvp$promise$race$$race; function lib$rsvp$promise$resolve$$resolve(object, label) { /*jshint validthis:true */ var Constructor = this; if (object && typeof object === 'object' && object.constructor === Constructor) { return object; } var promise = new Constructor(lib$rsvp$$internal$$noop, label); lib$rsvp$$internal$$resolve(promise, object); return promise; } var lib$rsvp$promise$resolve$$default = lib$rsvp$promise$resolve$$resolve; function lib$rsvp$promise$reject$$reject(reason, label) { /*jshint validthis:true */ var Constructor = this; var promise = new Constructor(lib$rsvp$$internal$$noop, label); lib$rsvp$$internal$$reject(promise, reason); return promise; } var lib$rsvp$promise$reject$$default = lib$rsvp$promise$reject$$reject; var lib$rsvp$promise$$guidKey = 'rsvp_' + lib$rsvp$utils$$now() + '-'; var lib$rsvp$promise$$counter = 0; function lib$rsvp$promise$$needsResolver() { throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); } function lib$rsvp$promise$$needsNew() { throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); } /** Promise objects represent the eventual result of an asynchronous operation. The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise’s eventual value or the reason why the promise cannot be fulfilled. Terminology ----------- - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - `thenable` is an object or function that defines a `then` method. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - `exception` is a value that is thrown using the throw statement. - `reason` is a value that indicates why a promise was rejected. - `settled` the final resting state of a promise, fulfilled or rejected. A promise can be in one of three states: pending, fulfilled, or rejected. Promises that are fulfilled have a fulfillment value and are in the fulfilled state. Promises that are rejected have a rejection reason and are in the rejected state. A fulfillment value is never a thenable. Promises can also be said to *resolve* a value. If this value is also a promise, then the original promise's settled state will match the value's settled state. So a promise that *resolves* a promise that rejects will itself reject, and a promise that *resolves* a promise that fulfills will itself fulfill. Basic Usage: ------------ ```js var promise = new Promise(function(resolve, reject) { // on success resolve(value); // on failure reject(reason); }); promise.then(function(value) { // on fulfillment }, function(reason) { // on rejection }); ``` Advanced Usage: --------------- Promises shine when abstracting away asynchronous interactions such as `XMLHttpRequest`s. ```js function getJSON(url) { return new Promise(function(resolve, reject){ var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onreadystatechange = handler; xhr.responseType = 'json'; xhr.setRequestHeader('Accept', 'application/json'); xhr.send(); function handler() { if (this.readyState === this.DONE) { if (this.status === 200) { resolve(this.response); } else { reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); } } }; }); } getJSON('/posts.json').then(function(json) { // on fulfillment }, function(reason) { // on rejection }); ``` Unlike callbacks, promises are great composable primitives. ```js Promise.all([ getJSON('/posts'), getJSON('/comments') ]).then(function(values){ values[0] // => postsJSON values[1] // => commentsJSON return values; }); ``` @class RSVP.Promise @param {function} resolver @param {String} label optional string for labeling the promise. Useful for tooling. @constructor */ function lib$rsvp$promise$$Promise(resolver, label) { this._id = lib$rsvp$promise$$counter++; this._label = label; this._state = undefined; this._result = undefined; this._subscribers = []; if (lib$rsvp$config$$config.instrument) { lib$rsvp$instrument$$default('created', this); } if (lib$rsvp$$internal$$noop !== resolver) { if (!lib$rsvp$utils$$isFunction(resolver)) { lib$rsvp$promise$$needsResolver(); } if (!(this instanceof lib$rsvp$promise$$Promise)) { lib$rsvp$promise$$needsNew(); } lib$rsvp$$internal$$initializePromise(this, resolver); } } var lib$rsvp$promise$$default = lib$rsvp$promise$$Promise; // deprecated lib$rsvp$promise$$Promise.cast = lib$rsvp$promise$resolve$$default; lib$rsvp$promise$$Promise.all = lib$rsvp$promise$all$$default; lib$rsvp$promise$$Promise.race = lib$rsvp$promise$race$$default; lib$rsvp$promise$$Promise.resolve = lib$rsvp$promise$resolve$$default; lib$rsvp$promise$$Promise.reject = lib$rsvp$promise$reject$$default; lib$rsvp$promise$$Promise.prototype = { constructor: lib$rsvp$promise$$Promise, _guidKey: lib$rsvp$promise$$guidKey, _onError: function (reason) { lib$rsvp$config$$config.async(function(promise) { setTimeout(function() { if (promise._onError) { lib$rsvp$config$$config['trigger']('error', reason); } }, 0); }, this); }, /** The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled. ```js findUser().then(function(user){ // user is available }, function(reason){ // user is unavailable, and you are given the reason why }); ``` Chaining -------- The return value of `then` is itself a promise. This second, 'downstream' promise is resolved with the return value of the first promise's fulfillment or rejection handler, or rejected if the handler throws an exception. ```js findUser().then(function (user) { return user.name; }, function (reason) { return 'default name'; }).then(function (userName) { // If `findUser` fulfilled, `userName` will be the user's name, otherwise it // will be `'default name'` }); findUser().then(function (user) { throw new Error('Found user, but still unhappy'); }, function (reason) { throw new Error('`findUser` rejected and we're unhappy'); }).then(function (value) { // never reached }, function (reason) { // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. }); ``` If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. ```js findUser().then(function (user) { throw new PedagogicalException('Upstream error'); }).then(function (value) { // never reached }).then(function (value) { // never reached }, function (reason) { // The `PedgagocialException` is propagated all the way down to here }); ``` Assimilation ------------ Sometimes the value you want to propagate to a downstream promise can only be retrieved asynchronously. This can be achieved by returning a promise in the fulfillment or rejection handler. The downstream promise will then be pending until the returned promise is settled. This is called *assimilation*. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // The user's comments are now available }); ``` If the assimliated promise rejects, then the downstream promise will also reject. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // If `findCommentsByAuthor` fulfills, we'll have the value here }, function (reason) { // If `findCommentsByAuthor` rejects, we'll have the reason here }); ``` Simple Example -------------- Synchronous Example ```javascript var result; try { result = findResult(); // success } catch(reason) { // failure } ``` Errback Example ```js findResult(function(result, err){ if (err) { // failure } else { // success } }); ``` Promise Example; ```javascript findResult().then(function(result){ // success }, function(reason){ // failure }); ``` Advanced Example -------------- Synchronous Example ```javascript var author, books; try { author = findAuthor(); books = findBooksByAuthor(author); // success } catch(reason) { // failure } ``` Errback Example ```js function foundBooks(books) { } function failure(reason) { } findAuthor(function(author, err){ if (err) { failure(err); // failure } else { try { findBoooksByAuthor(author, function(books, err) { if (err) { failure(err); } else { try { foundBooks(books); } catch(reason) { failure(reason); } } }); } catch(error) { failure(err); } // success } }); ``` Promise Example; ```javascript findAuthor(). then(findBooksByAuthor). then(function(books){ // found books }).catch(function(reason){ // something went wrong }); ``` @method then @param {Function} onFulfilled @param {Function} onRejected @param {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} */ then: function(onFulfillment, onRejection, label) { var parent = this; var state = parent._state; if (state === lib$rsvp$$internal$$FULFILLED && !onFulfillment || state === lib$rsvp$$internal$$REJECTED && !onRejection) { if (lib$rsvp$config$$config.instrument) { lib$rsvp$instrument$$default('chained', this, this); } return this; } parent._onError = null; var child = new this.constructor(lib$rsvp$$internal$$noop, label); var result = parent._result; if (lib$rsvp$config$$config.instrument) { lib$rsvp$instrument$$default('chained', parent, child); } if (state) { var callback = arguments[state - 1]; lib$rsvp$config$$config.async(function(){ lib$rsvp$$internal$$invokeCallback(state, child, callback, result); }); } else { lib$rsvp$$internal$$subscribe(parent, child, onFulfillment, onRejection); } return child; }, /** `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same as the catch block of a try/catch statement. ```js function findAuthor(){ throw new Error('couldn't find that author'); } // synchronous try { findAuthor(); } catch(reason) { // something went wrong } // async with promises findAuthor().catch(function(reason){ // something went wrong }); ``` @method catch @param {Function} onRejection @param {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} */ 'catch': function(onRejection, label) { return this.then(null, onRejection, label); }, /** `finally` will be invoked regardless of the promise's fate just as native try/catch/finally behaves Synchronous example: ```js findAuthor() { if (Math.random() > 0.5) { throw new Error(); } return new Author(); } try { return findAuthor(); // succeed or fail } catch(error) { return findOtherAuther(); } finally { // always runs // doesn't affect the return value } ``` Asynchronous example: ```js findAuthor().catch(function(reason){ return findOtherAuther(); }).finally(function(){ // author was either found, or not }); ``` @method finally @param {Function} callback @param {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} */ 'finally': function(callback, label) { var constructor = this.constructor; return this.then(function(value) { return constructor.resolve(callback()).then(function(){ return value; }); }, function(reason) { return constructor.resolve(callback()).then(function(){ throw reason; }); }, label); } }; function lib$rsvp$all$settled$$AllSettled(Constructor, entries, label) { this._superConstructor(Constructor, entries, false /* don't abort on reject */, label); } lib$rsvp$all$settled$$AllSettled.prototype = lib$rsvp$utils$$o_create(lib$rsvp$enumerator$$default.prototype); lib$rsvp$all$settled$$AllSettled.prototype._superConstructor = lib$rsvp$enumerator$$default; lib$rsvp$all$settled$$AllSettled.prototype._makeResult = lib$rsvp$enumerator$$makeSettledResult; lib$rsvp$all$settled$$AllSettled.prototype._validationError = function() { return new Error('allSettled must be called with an array'); }; function lib$rsvp$all$settled$$allSettled(entries, label) { return new lib$rsvp$all$settled$$AllSettled(lib$rsvp$promise$$default, entries, label).promise; } var lib$rsvp$all$settled$$default = lib$rsvp$all$settled$$allSettled; function lib$rsvp$all$$all(array, label) { return lib$rsvp$promise$$default.all(array, label); } var lib$rsvp$all$$default = lib$rsvp$all$$all; var lib$rsvp$asap$$len = 0; var lib$rsvp$asap$$toString = {}.toString; var lib$rsvp$asap$$vertxNext; function lib$rsvp$asap$$asap(callback, arg) { lib$rsvp$asap$$queue[lib$rsvp$asap$$len] = callback; lib$rsvp$asap$$queue[lib$rsvp$asap$$len + 1] = arg; lib$rsvp$asap$$len += 2; if (lib$rsvp$asap$$len === 2) { // If len is 1, that means that we need to schedule an async flush. // If additional callbacks are queued before the queue is flushed, they // will be processed by this flush that we are scheduling. lib$rsvp$asap$$scheduleFlush(); } } var lib$rsvp$asap$$default = lib$rsvp$asap$$asap; var lib$rsvp$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined; var lib$rsvp$asap$$browserGlobal = lib$rsvp$asap$$browserWindow || {}; var lib$rsvp$asap$$BrowserMutationObserver = lib$rsvp$asap$$browserGlobal.MutationObserver || lib$rsvp$asap$$browserGlobal.WebKitMutationObserver; var lib$rsvp$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; // test for web worker but not in IE10 var lib$rsvp$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; // node function lib$rsvp$asap$$useNextTick() { var nextTick = process.nextTick; // node version 0.10.x displays a deprecation warning when nextTick is used recursively // setImmediate should be used instead instead var version = process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/); if (Array.isArray(version) && version[1] === '0' && version[2] === '10') { nextTick = setImmediate; } return function() { nextTick(lib$rsvp$asap$$flush); }; } // vertx function lib$rsvp$asap$$useVertxTimer() { return function() { lib$rsvp$asap$$vertxNext(lib$rsvp$asap$$flush); }; } function lib$rsvp$asap$$useMutationObserver() { var iterations = 0; var observer = new lib$rsvp$asap$$BrowserMutationObserver(lib$rsvp$asap$$flush); var node = document.createTextNode(''); observer.observe(node, { characterData: true }); return function() { node.data = (iterations = ++iterations % 2); }; } // web worker function lib$rsvp$asap$$useMessageChannel() { var channel = new MessageChannel(); channel.port1.onmessage = lib$rsvp$asap$$flush; return function () { channel.port2.postMessage(0); }; } function lib$rsvp$asap$$useSetTimeout() { return function() { setTimeout(lib$rsvp$asap$$flush, 1); }; } var lib$rsvp$asap$$queue = new Array(1000); function lib$rsvp$asap$$flush() { for (var i = 0; i < lib$rsvp$asap$$len; i+=2) { var callback = lib$rsvp$asap$$queue[i]; var arg = lib$rsvp$asap$$queue[i+1]; callback(arg); lib$rsvp$asap$$queue[i] = undefined; lib$rsvp$asap$$queue[i+1] = undefined; } lib$rsvp$asap$$len = 0; } function lib$rsvp$asap$$attemptVertex() { try { var r = require; var vertx = r('vertx'); lib$rsvp$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext; return lib$rsvp$asap$$useVertxTimer(); } catch(e) { return lib$rsvp$asap$$useSetTimeout(); } } var lib$rsvp$asap$$scheduleFlush; // Decide what async method to use to triggering processing of queued callbacks: if (lib$rsvp$asap$$isNode) { lib$rsvp$asap$$scheduleFlush = lib$rsvp$asap$$useNextTick(); } else if (lib$rsvp$asap$$BrowserMutationObserver) { lib$rsvp$asap$$scheduleFlush = lib$rsvp$asap$$useMutationObserver(); } else if (lib$rsvp$asap$$isWorker) { lib$rsvp$asap$$scheduleFlush = lib$rsvp$asap$$useMessageChannel(); } else if (lib$rsvp$asap$$browserWindow === undefined && typeof require === 'function') { lib$rsvp$asap$$scheduleFlush = lib$rsvp$asap$$attemptVertex(); } else { lib$rsvp$asap$$scheduleFlush = lib$rsvp$asap$$useSetTimeout(); } function lib$rsvp$defer$$defer(label) { var deferred = { }; deferred['promise'] = new lib$rsvp$promise$$default(function(resolve, reject) { deferred['resolve'] = resolve; deferred['reject'] = reject; }, label); return deferred; } var lib$rsvp$defer$$default = lib$rsvp$defer$$defer; function lib$rsvp$filter$$filter(promises, filterFn, label) { return lib$rsvp$promise$$default.all(promises, label).then(function(values) { if (!lib$rsvp$utils$$isFunction(filterFn)) { throw new TypeError("You must pass a function as filter's second argument."); } var length = values.length; var filtered = new Array(length); for (var i = 0; i < length; i++) { filtered[i] = filterFn(values[i]); } return lib$rsvp$promise$$default.all(filtered, label).then(function(filtered) { var results = new Array(length); var newLength = 0; for (var i = 0; i < length; i++) { if (filtered[i]) { results[newLength] = values[i]; newLength++; } } results.length = newLength; return results; }); }); } var lib$rsvp$filter$$default = lib$rsvp$filter$$filter; function lib$rsvp$promise$hash$$PromiseHash(Constructor, object, label) { this._superConstructor(Constructor, object, true, label); } var lib$rsvp$promise$hash$$default = lib$rsvp$promise$hash$$PromiseHash; lib$rsvp$promise$hash$$PromiseHash.prototype = lib$rsvp$utils$$o_create(lib$rsvp$enumerator$$default.prototype); lib$rsvp$promise$hash$$PromiseHash.prototype._superConstructor = lib$rsvp$enumerator$$default; lib$rsvp$promise$hash$$PromiseHash.prototype._init = function() { this._result = {}; }; lib$rsvp$promise$hash$$PromiseHash.prototype._validateInput = function(input) { return input && typeof input === 'object'; }; lib$rsvp$promise$hash$$PromiseHash.prototype._validationError = function() { return new Error('Promise.hash must be called with an object'); }; lib$rsvp$promise$hash$$PromiseHash.prototype._enumerate = function() { var promise = this.promise; var input = this._input; var results = []; for (var key in input) { if (promise._state === lib$rsvp$$internal$$PENDING && Object.prototype.hasOwnProperty.call(input, key)) { results.push({ position: key, entry: input[key] }); } } var length = results.length; this._remaining = length; var result; for (var i = 0; promise._state === lib$rsvp$$internal$$PENDING && i < length; i++) { result = results[i]; this._eachEntry(result.entry, result.position); } }; function lib$rsvp$hash$settled$$HashSettled(Constructor, object, label) { this._superConstructor(Constructor, object, false, label); } lib$rsvp$hash$settled$$HashSettled.prototype = lib$rsvp$utils$$o_create(lib$rsvp$promise$hash$$default.prototype); lib$rsvp$hash$settled$$HashSettled.prototype._superConstructor = lib$rsvp$enumerator$$default; lib$rsvp$hash$settled$$HashSettled.prototype._makeResult = lib$rsvp$enumerator$$makeSettledResult; lib$rsvp$hash$settled$$HashSettled.prototype._validationError = function() { return new Error('hashSettled must be called with an object'); }; function lib$rsvp$hash$settled$$hashSettled(object, label) { return new lib$rsvp$hash$settled$$HashSettled(lib$rsvp$promise$$default, object, label).promise; } var lib$rsvp$hash$settled$$default = lib$rsvp$hash$settled$$hashSettled; function lib$rsvp$hash$$hash(object, label) { return new lib$rsvp$promise$hash$$default(lib$rsvp$promise$$default, object, label).promise; } var lib$rsvp$hash$$default = lib$rsvp$hash$$hash; function lib$rsvp$map$$map(promises, mapFn, label) { return lib$rsvp$promise$$default.all(promises, label).then(function(values) { if (!lib$rsvp$utils$$isFunction(mapFn)) { throw new TypeError("You must pass a function as map's second argument."); } var length = values.length; var results = new Array(length); for (var i = 0; i < length; i++) { results[i] = mapFn(values[i]); } return lib$rsvp$promise$$default.all(results, label); }); } var lib$rsvp$map$$default = lib$rsvp$map$$map; function lib$rsvp$node$$Result() { this.value = undefined; } var lib$rsvp$node$$ERROR = new lib$rsvp$node$$Result(); var lib$rsvp$node$$GET_THEN_ERROR = new lib$rsvp$node$$Result(); function lib$rsvp$node$$getThen(obj) { try { return obj.then; } catch(error) { lib$rsvp$node$$ERROR.value= error; return lib$rsvp$node$$ERROR; } } function lib$rsvp$node$$tryApply(f, s, a) { try { f.apply(s, a); } catch(error) { lib$rsvp$node$$ERROR.value = error; return lib$rsvp$node$$ERROR; } } function lib$rsvp$node$$makeObject(_, argumentNames) { var obj = {}; var name; var i; var length = _.length; var args = new Array(length); for (var x = 0; x < length; x++) { args[x] = _[x]; } for (i = 0; i < argumentNames.length; i++) { name = argumentNames[i]; obj[name] = args[i + 1]; } return obj; } function lib$rsvp$node$$arrayResult(_) { var length = _.length; var args = new Array(length - 1); for (var i = 1; i < length; i++) { args[i - 1] = _[i]; } return args; } function lib$rsvp$node$$wrapThenable(then, promise) { return { then: function(onFulFillment, onRejection) { return then.call(promise, onFulFillment, onRejection); } }; } function lib$rsvp$node$$denodeify(nodeFunc, options) { var fn = function() { var self = this; var l = arguments.length; var args = new Array(l + 1); var arg; var promiseInput = false; for (var i = 0; i < l; ++i) { arg = arguments[i]; if (!promiseInput) { // TODO: clean this up promiseInput = lib$rsvp$node$$needsPromiseInput(arg); if (promiseInput === lib$rsvp$node$$GET_THEN_ERROR) { var p = new lib$rsvp$promise$$default(lib$rsvp$$internal$$noop); lib$rsvp$$internal$$reject(p, lib$rsvp$node$$GET_THEN_ERROR.value); return p; } else if (promiseInput && promiseInput !== true) { arg = lib$rsvp$node$$wrapThenable(promiseInput, arg); } } args[i] = arg; } var promise = new lib$rsvp$promise$$default(lib$rsvp$$internal$$noop); args[l] = function(err, val) { if (err) lib$rsvp$$internal$$reject(promise, err); else if (options === undefined) lib$rsvp$$internal$$resolve(promise, val); else if (options === true) lib$rsvp$$internal$$resolve(promise, lib$rsvp$node$$arrayResult(arguments)); else if (lib$rsvp$utils$$isArray(options)) lib$rsvp$$internal$$resolve(promise, lib$rsvp$node$$makeObject(arguments, options)); else lib$rsvp$$internal$$resolve(promise, val); }; if (promiseInput) { return lib$rsvp$node$$handlePromiseInput(promise, args, nodeFunc, self); } else { return lib$rsvp$node$$handleValueInput(promise, args, nodeFunc, self); } }; fn.__proto__ = nodeFunc; return fn; } var lib$rsvp$node$$default = lib$rsvp$node$$denodeify; function lib$rsvp$node$$handleValueInput(promise, args, nodeFunc, self) { var result = lib$rsvp$node$$tryApply(nodeFunc, self, args); if (result === lib$rsvp$node$$ERROR) { lib$rsvp$$internal$$reject(promise, result.value); } return promise; } function lib$rsvp$node$$handlePromiseInput(promise, args, nodeFunc, self){ return lib$rsvp$promise$$default.all(args).then(function(args){ var result = lib$rsvp$node$$tryApply(nodeFunc, self, args); if (result === lib$rsvp$node$$ERROR) { lib$rsvp$$internal$$reject(promise, result.value); } return promise; }); } function lib$rsvp$node$$needsPromiseInput(arg) { if (arg && typeof arg === 'object') { if (arg.constructor === lib$rsvp$promise$$default) { return true; } else { return lib$rsvp$node$$getThen(arg); } } else { return false; } } function lib$rsvp$race$$race(array, label) { return lib$rsvp$promise$$default.race(array, label); } var lib$rsvp$race$$default = lib$rsvp$race$$race; function lib$rsvp$reject$$reject(reason, label) { return lib$rsvp$promise$$default.reject(reason, label); } var lib$rsvp$reject$$default = lib$rsvp$reject$$reject; function lib$rsvp$resolve$$resolve(value, label) { return lib$rsvp$promise$$default.resolve(value, label); } var lib$rsvp$resolve$$default = lib$rsvp$resolve$$resolve; function lib$rsvp$rethrow$$rethrow(reason) { setTimeout(function() { throw reason; }); throw reason; } var lib$rsvp$rethrow$$default = lib$rsvp$rethrow$$rethrow; // default async is asap; lib$rsvp$config$$config.async = lib$rsvp$asap$$default; var lib$rsvp$$cast = lib$rsvp$resolve$$default; function lib$rsvp$$async(callback, arg) { lib$rsvp$config$$config.async(callback, arg); } function lib$rsvp$$on() { lib$rsvp$config$$config['on'].apply(lib$rsvp$config$$config, arguments); } function lib$rsvp$$off() { lib$rsvp$config$$config['off'].apply(lib$rsvp$config$$config, arguments); } // Set up instrumentation through `window.__PROMISE_INTRUMENTATION__` if (typeof window !== 'undefined' && typeof window['__PROMISE_INSTRUMENTATION__'] === 'object') { var lib$rsvp$$callbacks = window['__PROMISE_INSTRUMENTATION__']; lib$rsvp$config$$configure('instrument', true); for (var lib$rsvp$$eventName in lib$rsvp$$callbacks) { if (lib$rsvp$$callbacks.hasOwnProperty(lib$rsvp$$eventName)) { lib$rsvp$$on(lib$rsvp$$eventName, lib$rsvp$$callbacks[lib$rsvp$$eventName]); } } } var lib$rsvp$umd$$RSVP = { 'race': lib$rsvp$race$$default, 'Promise': lib$rsvp$promise$$default, 'allSettled': lib$rsvp$all$settled$$default, 'hash': lib$rsvp$hash$$default, 'hashSettled': lib$rsvp$hash$settled$$default, 'denodeify': lib$rsvp$node$$default, 'on': lib$rsvp$$on, 'off': lib$rsvp$$off, 'map': lib$rsvp$map$$default, 'filter': lib$rsvp$filter$$default, 'resolve': lib$rsvp$resolve$$default, 'reject': lib$rsvp$reject$$default, 'all': lib$rsvp$all$$default, 'rethrow': lib$rsvp$rethrow$$default, 'defer': lib$rsvp$defer$$default, 'EventTarget': lib$rsvp$events$$default, 'configure': lib$rsvp$config$$configure, 'async': lib$rsvp$$async }; this['RSVP'] = lib$rsvp$umd$$RSVP; }).call(commonObj); (function() { "use strict"; function $$route$recognizer$dsl$$Target(path, matcher, delegate) { this.path = path; this.matcher = matcher; this.delegate = delegate; } $$route$recognizer$dsl$$Target.prototype = { to: function(target, callback) { var delegate = this.delegate; if (delegate && delegate.willAddRoute) { target = delegate.willAddRoute(this.matcher.target, target); } this.matcher.add(this.path, target); if (callback) { if (callback.length === 0) { throw new Error("You must have an argument in the function passed to `to`"); } this.matcher.addChild(this.path, target, callback, this.delegate); } return this; } }; function $$route$recognizer$dsl$$Matcher(target) { this.routes = {}; this.children = {}; this.target = target; } $$route$recognizer$dsl$$Matcher.prototype = { add: function(path, handler) { this.routes[path] = handler; }, addChild: function(path, target, callback, delegate) { var matcher = new $$route$recognizer$dsl$$Matcher(target); this.children[path] = matcher; var match = $$route$recognizer$dsl$$generateMatch(path, matcher, delegate); if (delegate && delegate.contextEntered) { delegate.contextEntered(target, match); } callback(match); } }; function $$route$recognizer$dsl$$generateMatch(startingPath, matcher, delegate) { return function(path, nestedCallback) { var fullPath = startingPath + path; if (nestedCallback) { nestedCallback($$route$recognizer$dsl$$generateMatch(fullPath, matcher, delegate)); } else { return new $$route$recognizer$dsl$$Target(startingPath + path, matcher, delegate); } }; } function $$route$recognizer$dsl$$addRoute(routeArray, path, handler) { var len = 0; for (var i=0, l=routeArray.length; i<l; i++) { len += routeArray[i].path.length; } path = path.substr(len); var route = { path: path, handler: handler }; routeArray.push(route); } function $$route$recognizer$dsl$$eachRoute(baseRoute, matcher, callback, binding) { var routes = matcher.routes; for (var path in routes) { if (routes.hasOwnProperty(path)) { var routeArray = baseRoute.slice(); $$route$recognizer$dsl$$addRoute(routeArray, path, routes[path]); if (matcher.children[path]) { $$route$recognizer$dsl$$eachRoute(routeArray, matcher.children[path], callback, binding); } else { callback.call(binding, routeArray); } } } } var $$route$recognizer$dsl$$default = function(callback, addRouteCallback) { var matcher = new $$route$recognizer$dsl$$Matcher(); callback($$route$recognizer$dsl$$generateMatch("", matcher, this.delegate)); $$route$recognizer$dsl$$eachRoute([], matcher, function(route) { if (addRouteCallback) { addRouteCallback(this, route); } else { this.add(route); } }, this); }; var $$route$recognizer$$specials = [ '/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\' ]; var $$route$recognizer$$escapeRegex = new RegExp('(\\' + $$route$recognizer$$specials.join('|\\') + ')', 'g'); function $$route$recognizer$$isArray(test) { return Object.prototype.toString.call(test) === "[object Array]"; } // A Segment represents a segment in the original route description. // Each Segment type provides an `eachChar` and `regex` method. // // The `eachChar` method invokes the callback with one or more character // specifications. A character specification consumes one or more input // characters. // // The `regex` method returns a regex fragment for the segment. If the // segment is a dynamic of star segment, the regex fragment also includes // a capture. // // A character specification contains: // // * `validChars`: a String with a list of all valid characters, or // * `invalidChars`: a String with a list of all invalid characters // * `repeat`: true if the character specification can repeat function $$route$recognizer$$StaticSegment(string) { this.string = string; } $$route$recognizer$$StaticSegment.prototype = { eachChar: function(callback) { var string = this.string, ch; for (var i=0, l=string.length; i<l; i++) { ch = string.charAt(i); callback({ validChars: ch }); } }, regex: function() { return this.string.replace($$route$recognizer$$escapeRegex, '\\$1'); }, generate: function() { return this.string; } }; function $$route$recognizer$$DynamicSegment(name) { this.name = name; } $$route$recognizer$$DynamicSegment.prototype = { eachChar: function(callback) { callback({ invalidChars: "/", repeat: true }); }, regex: function() { return "([^/]+)"; }, generate: function(params) { return params[this.name]; } }; function $$route$recognizer$$StarSegment(name) { this.name = name; } $$route$recognizer$$StarSegment.prototype = { eachChar: function(callback) { callback({ invalidChars: "", repeat: true }); }, regex: function() { return "(.+)"; }, generate: function(params) { return params[this.name]; } }; function $$route$recognizer$$EpsilonSegment() {} $$route$recognizer$$EpsilonSegment.prototype = { eachChar: function() {}, regex: function() { return ""; }, generate: function() { return ""; } }; function $$route$recognizer$$parse(route, names, specificity) { // normalize route as not starting with a "/". Recognition will // also normalize. if (route.charAt(0) === "/") { route = route.substr(1); } var segments = route.split("/"), results = []; // A routes has specificity determined by the order that its different segments // appear in. This system mirrors how the magnitude of numbers written as strings // works. // Consider a number written as: "abc". An example would be "200". Any other number written // "xyz" will be smaller than "abc" so long as `a > z`. For instance, "199" is smaller // then "200", even though "y" and "z" (which are both 9) are larger than "0" (the value // of (`b` and `c`). This is because the leading symbol, "2", is larger than the other // leading symbol, "1". // The rule is that symbols to the left carry more weight than symbols to the right // when a number is written out as a string. In the above strings, the leading digit // represents how many 100's are in the number, and it carries more weight than the middle // number which represents how many 10's are in the number. // This system of number magnitude works well for route specificity, too. A route written as // `a/b/c` will be more specific than `x/y/z` as long as `a` is more specific than // `x`, irrespective of the other parts. // Because of this similarity, we assign each type of segment a number value written as a // string. We can find the specificity of compound routes by concatenating these strings // together, from left to right. After we have looped through all of the segments, // we convert the string to a number. specificity.val = ''; for (var i=0, l=segments.length; i<l; i++) { var segment = segments[i], match; if (match = segment.match(/^:([^\/]+)$/)) { results.push(new $$route$recognizer$$DynamicSegment(match[1])); names.push(match[1]); specificity.val += '3'; } else if (match = segment.match(/^\*([^\/]+)$/)) { results.push(new $$route$recognizer$$StarSegment(match[1])); specificity.val += '2'; names.push(match[1]); } else if(segment === "") { results.push(new $$route$recognizer$$EpsilonSegment()); specificity.val += '1'; } else { results.push(new $$route$recognizer$$StaticSegment(segment)); specificity.val += '4'; } } specificity.val = +specificity.val; return results; } // A State has a character specification and (`charSpec`) and a list of possible // subsequent states (`nextStates`). // // If a State is an accepting state, it will also have several additional // properties: // // * `regex`: A regular expression that is used to extract parameters from paths // that reached this accepting state. // * `handlers`: Information on how to convert the list of captures into calls // to registered handlers with the specified parameters // * `types`: How many static, dynamic or star segments in this route. Used to // decide which route to use if multiple registered routes match a path. // // Currently, State is implemented naively by looping over `nextStates` and // comparing a character specification against a character. A more efficient // implementation would use a hash of keys pointing at one or more next states. function $$route$recognizer$$State(charSpec) { this.charSpec = charSpec; this.nextStates = []; } $$route$recognizer$$State.prototype = { get: function(charSpec) { var nextStates = this.nextStates; for (var i=0, l=nextStates.length; i<l; i++) { var child = nextStates[i]; var isEqual = child.charSpec.validChars === charSpec.validChars; isEqual = isEqual && child.charSpec.invalidChars === charSpec.invalidChars; if (isEqual) { return child; } } }, put: function(charSpec) { var state; // If the character specification already exists in a child of the current // state, just return that state. if (state = this.get(charSpec)) { return state; } // Make a new state for the character spec state = new $$route$recognizer$$State(charSpec); // Insert the new state as a child of the current state this.nextStates.push(state); // If this character specification repeats, insert the new state as a child // of itself. Note that this will not trigger an infinite loop because each // transition during recognition consumes a character. if (charSpec.repeat) { state.nextStates.push(state); } // Return the new state return state; }, // Find a list of child states matching the next character match: function(ch) { // DEBUG "Processing `" + ch + "`:" var nextStates = this.nextStates, child, charSpec, chars; // DEBUG " " + debugState(this) var returned = []; for (var i=0, l=nextStates.length; i<l; i++) { child = nextStates[i]; charSpec = child.charSpec; if (typeof (chars = charSpec.validChars) !== 'undefined') { if (chars.indexOf(ch) !== -1) { returned.push(child); } } else if (typeof (chars = charSpec.invalidChars) !== 'undefined') { if (chars.indexOf(ch) === -1) { returned.push(child); } } } return returned; } /** IF DEBUG , debug: function() { var charSpec = this.charSpec, debug = "[", chars = charSpec.validChars || charSpec.invalidChars; if (charSpec.invalidChars) { debug += "^"; } debug += chars; debug += "]"; if (charSpec.repeat) { debug += "+"; } return debug; } END IF **/ }; /** IF DEBUG function debug(log) { console.log(log); } function debugState(state) { return state.nextStates.map(function(n) { if (n.nextStates.length === 0) { return "( " + n.debug() + " [accepting] )"; } return "( " + n.debug() + " <then> " + n.nextStates.map(function(s) { return s.debug() }).join(" or ") + " )"; }).join(", ") } END IF **/ // Sort the routes by specificity function $$route$recognizer$$sortSolutions(states) { return states.sort(function(a, b) { return b.specificity.val - a.specificity.val; }); } function $$route$recognizer$$recognizeChar(states, ch) { var nextStates = []; for (var i=0, l=states.length; i<l; i++) { var state = states[i]; nextStates = nextStates.concat(state.match(ch)); } return nextStates; } var $$route$recognizer$$oCreate = Object.create || function(proto) { function F() {} F.prototype = proto; return new F(); }; function $$route$recognizer$$RecognizeResults(queryParams) { this.queryParams = queryParams || {}; } $$route$recognizer$$RecognizeResults.prototype = $$route$recognizer$$oCreate({ splice: Array.prototype.splice, slice: Array.prototype.slice, push: Array.prototype.push, length: 0, queryParams: null }); function $$route$recognizer$$findHandler(state, path, queryParams) { var handlers = state.handlers, regex = state.regex; var captures = path.match(regex), currentCapture = 1; var result = new $$route$recognizer$$RecognizeResults(queryParams); for (var i=0, l=handlers.length; i<l; i++) { var handler = handlers[i], names = handler.names, params = {}; for (var j=0, m=names.length; j<m; j++) { params[names[j]] = captures[currentCapture++]; } result.push({ handler: handler.handler, params: params, isDynamic: !!names.length }); } return result; } function $$route$recognizer$$addSegment(currentState, segment) { segment.eachChar(function(ch) { var state; currentState = currentState.put(ch); }); return currentState; } function $$route$recognizer$$decodeQueryParamPart(part) { // http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1 part = part.replace(/\+/gm, '%20'); return decodeURIComponent(part); } // The main interface var $$route$recognizer$$RouteRecognizer = function() { this.rootState = new $$route$recognizer$$State(); this.names = {}; }; $$route$recognizer$$RouteRecognizer.prototype = { add: function(routes, options) { var currentState = this.rootState, regex = "^", specificity = {}, handlers = [], allSegments = [], name; var isEmpty = true; for (var i=0, l=routes.length; i<l; i++) { var route = routes[i], names = []; var segments = $$route$recognizer$$parse(route.path, names, specificity); allSegments = allSegments.concat(segments); for (var j=0, m=segments.length; j<m; j++) { var segment = segments[j]; if (segment instanceof $$route$recognizer$$EpsilonSegment) { continue; } isEmpty = false; // Add a "/" for the new segment currentState = currentState.put({ validChars: "/" }); regex += "/"; // Add a representation of the segment to the NFA and regex currentState = $$route$recognizer$$addSegment(currentState, segment); regex += segment.regex(); } var handler = { handler: route.handler, names: names }; handlers.push(handler); } if (isEmpty) { currentState = currentState.put({ validChars: "/" }); regex += "/"; } currentState.handlers = handlers; currentState.regex = new RegExp(regex + "$"); currentState.specificity = specificity; if (name = options && options.as) { this.names[name] = { segments: allSegments, handlers: handlers }; } }, handlersFor: function(name) { var route = this.names[name], result = []; if (!route) { throw new Error("There is no route named " + name); } for (var i=0, l=route.handlers.length; i<l; i++) { result.push(route.handlers[i]); } return result; }, hasRoute: function(name) { return !!this.names[name]; }, generate: function(name, params) { var route = this.names[name], output = ""; if (!route) { throw new Error("There is no route named " + name); } var segments = route.segments; for (var i=0, l=segments.length; i<l; i++) { var segment = segments[i]; if (segment instanceof $$route$recognizer$$EpsilonSegment) { continue; } output += "/"; output += segment.generate(params); } if (output.charAt(0) !== '/') { output = '/' + output; } if (params && params.queryParams) { output += this.generateQueryString(params.queryParams, route.handlers); } return output; }, generateQueryString: function(params, handlers) { var pairs = []; var keys = []; for(var key in params) { if (params.hasOwnProperty(key)) { keys.push(key); } } keys.sort(); for (var i = 0, len = keys.length; i < len; i++) { key = keys[i]; var value = params[key]; if (value == null) { continue; } var pair = encodeURIComponent(key); if ($$route$recognizer$$isArray(value)) { for (var j = 0, l = value.length; j < l; j++) { var arrayPair = key + '[]' + '=' + encodeURIComponent(value[j]); pairs.push(arrayPair); } } else { pair += "=" + encodeURIComponent(value); pairs.push(pair); } } if (pairs.length === 0) { return ''; } return "?" + pairs.join("&"); }, parseQueryString: function(queryString) { var pairs = queryString.split("&"), queryParams = {}; for(var i=0; i < pairs.length; i++) { var pair = pairs[i].split('='), key = $$route$recognizer$$decodeQueryParamPart(pair[0]), keyLength = key.length, isArray = false, value; if (pair.length === 1) { value = 'true'; } else { //Handle arrays if (keyLength > 2 && key.slice(keyLength -2) === '[]') { isArray = true; key = key.slice(0, keyLength - 2); if(!queryParams[key]) { queryParams[key] = []; } } value = pair[1] ? $$route$recognizer$$decodeQueryParamPart(pair[1]) : ''; } if (isArray) { queryParams[key].push(value); } else { queryParams[key] = value; } } return queryParams; }, recognize: function(path) { var states = [ this.rootState ], pathLen, i, l, queryStart, queryParams = {}, isSlashDropped = false; queryStart = path.indexOf('?'); if (queryStart !== -1) { var queryString = path.substr(queryStart + 1, path.length); path = path.substr(0, queryStart); queryParams = this.parseQueryString(queryString); } path = decodeURI(path); // DEBUG GROUP path if (path.charAt(0) !== "/") { path = "/" + path; } pathLen = path.length; if (pathLen > 1 && path.charAt(pathLen - 1) === "/") { path = path.substr(0, pathLen - 1); isSlashDropped = true; } for (i=0, l=path.length; i<l; i++) { states = $$route$recognizer$$recognizeChar(states, path.charAt(i)); if (!states.length) { break; } } // END DEBUG GROUP var solutions = []; for (i=0, l=states.length; i<l; i++) { if (states[i].handlers) { solutions.push(states[i]); } } states = $$route$recognizer$$sortSolutions(solutions); var state = solutions[0]; if (state && state.handlers) { // if a trailing slash was dropped and a star segment is the last segment // specified, put the trailing slash back if (isSlashDropped && state.regex.source.slice(-5) === "(.+)$") { path = path + "/"; } return $$route$recognizer$$findHandler(state, path, queryParams); } } }; $$route$recognizer$$RouteRecognizer.prototype.map = $$route$recognizer$dsl$$default; $$route$recognizer$$RouteRecognizer.VERSION = '0.1.7'; var $$route$recognizer$$default = $$route$recognizer$$RouteRecognizer; this['RouteRecognizer'] = $$route$recognizer$$default; }).call(commonObj); (function() { var registry = {}, seen = {}; define = function(name, deps, callback) { registry[name] = { deps: deps, callback: callback }; }; requirejs = require = requireModule = function(name) { if (seen[name]) { return seen[name]; } seen[name] = {}; if (!registry[name]) { throw new Error("Could not find module " + name); } var mod = registry[name], deps = mod.deps, callback = mod.callback, reified = [], exports; for (var i=0, l=deps.length; i<l; i++) { if (deps[i] === 'exports') { reified.push(exports = {}); } else { reified.push(requireModule(resolve(deps[i]))); } } var value = callback.apply(this, reified); return seen[name] = exports || value; function resolve(child) { if (child.charAt(0) !== '.') { return child; } var parts = child.split("/"); var parentBase = name.split("/").slice(0, -1); for (var i=0, l=parts.length; i<l; i++) { var part = parts[i]; if (part === '..') { parentBase.pop(); } else if (part === '.') { continue; } else { parentBase.push(part); } } return parentBase.join("/"); } }; })(); define("router/handler-info", ["./utils","rsvp/promise","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; var bind = __dependency1__.bind; var merge = __dependency1__.merge; var serialize = __dependency1__.serialize; var promiseLabel = __dependency1__.promiseLabel; var applyHook = __dependency1__.applyHook; var Promise = __dependency2__["default"]; function HandlerInfo(_props) { var props = _props || {}; merge(this, props); this.initialize(props); } HandlerInfo.prototype = { name: null, handler: null, params: null, context: null, // Injected by the handler info factory. factory: null, initialize: function() {}, log: function(payload, message) { if (payload.log) { payload.log(this.name + ': ' + message); } }, promiseLabel: function(label) { return promiseLabel("'" + this.name + "' " + label); }, getUnresolved: function() { return this; }, serialize: function() { return this.params || {}; }, resolve: function(shouldContinue, payload) { var checkForAbort = bind(this, this.checkForAbort, shouldContinue), beforeModel = bind(this, this.runBeforeModelHook, payload), model = bind(this, this.getModel, payload), afterModel = bind(this, this.runAfterModelHook, payload), becomeResolved = bind(this, this.becomeResolved, payload); return Promise.resolve(undefined, this.promiseLabel("Start handler")) .then(checkForAbort, null, this.promiseLabel("Check for abort")) .then(beforeModel, null, this.promiseLabel("Before model")) .then(checkForAbort, null, this.promiseLabel("Check if aborted during 'beforeModel' hook")) .then(model, null, this.promiseLabel("Model")) .then(checkForAbort, null, this.promiseLabel("Check if aborted in 'model' hook")) .then(afterModel, null, this.promiseLabel("After model")) .then(checkForAbort, null, this.promiseLabel("Check if aborted in 'afterModel' hook")) .then(becomeResolved, null, this.promiseLabel("Become resolved")); }, runBeforeModelHook: function(payload) { if (payload.trigger) { payload.trigger(true, 'willResolveModel', payload, this.handler); } return this.runSharedModelHook(payload, 'beforeModel', []); }, runAfterModelHook: function(payload, resolvedModel) { // Stash the resolved model on the payload. // This makes it possible for users to swap out // the resolved model in afterModel. var name = this.name; this.stashResolvedModel(payload, resolvedModel); return this.runSharedModelHook(payload, 'afterModel', [resolvedModel]) .then(function() { // Ignore the fulfilled value returned from afterModel. // Return the value stashed in resolvedModels, which // might have been swapped out in afterModel. return payload.resolvedModels[name]; }, null, this.promiseLabel("Ignore fulfillment value and return model value")); }, runSharedModelHook: function(payload, hookName, args) { this.log(payload, "calling " + hookName + " hook"); if (this.queryParams) { args.push(this.queryParams); } args.push(payload); var result = applyHook(this.handler, hookName, args); if (result && result.isTransition) { result = null; } return Promise.resolve(result, this.promiseLabel("Resolve value returned from one of the model hooks")); }, // overridden by subclasses getModel: null, checkForAbort: function(shouldContinue, promiseValue) { return Promise.resolve(shouldContinue(), this.promiseLabel("Check for abort")).then(function() { // We don't care about shouldContinue's resolve value; // pass along the original value passed to this fn. return promiseValue; }, null, this.promiseLabel("Ignore fulfillment value and continue")); }, stashResolvedModel: function(payload, resolvedModel) { payload.resolvedModels = payload.resolvedModels || {}; payload.resolvedModels[this.name] = resolvedModel; }, becomeResolved: function(payload, resolvedContext) { var params = this.serialize(resolvedContext); if (payload) { this.stashResolvedModel(payload, resolvedContext); payload.params = payload.params || {}; payload.params[this.name] = params; } return this.factory('resolved', { context: resolvedContext, name: this.name, handler: this.handler, params: params }); }, shouldSupercede: function(other) { // Prefer this newer handlerInfo over `other` if: // 1) The other one doesn't exist // 2) The names don't match // 3) This handler has a context that doesn't match // the other one (or the other one doesn't have one). // 4) This handler has parameters that don't match the other. if (!other) { return true; } var contextsMatch = (other.context === this.context); return other.name !== this.name || (this.hasOwnProperty('context') && !contextsMatch) || (this.hasOwnProperty('params') && !paramsMatch(this.params, other.params)); } }; function paramsMatch(a, b) { if ((!a) ^ (!b)) { // Only one is null. return false; } if (!a) { // Both must be null. return true; } // Note: this assumes that both params have the same // number of keys, but since we're comparing the // same handlers, they should. for (var k in a) { if (a.hasOwnProperty(k) && a[k] !== b[k]) { return false; } } return true; } __exports__["default"] = HandlerInfo; }); define("router/handler-info/factory", ["router/handler-info/resolved-handler-info","router/handler-info/unresolved-handler-info-by-object","router/handler-info/unresolved-handler-info-by-param","exports"], function(__dependency1__, __dependency2__, __dependency3__, __exports__) { "use strict"; var ResolvedHandlerInfo = __dependency1__["default"]; var UnresolvedHandlerInfoByObject = __dependency2__["default"]; var UnresolvedHandlerInfoByParam = __dependency3__["default"]; handlerInfoFactory.klasses = { resolved: ResolvedHandlerInfo, param: UnresolvedHandlerInfoByParam, object: UnresolvedHandlerInfoByObject }; function handlerInfoFactory(name, props) { var Ctor = handlerInfoFactory.klasses[name], handlerInfo = new Ctor(props || {}); handlerInfo.factory = handlerInfoFactory; return handlerInfo; } __exports__["default"] = handlerInfoFactory; }); define("router/handler-info/resolved-handler-info", ["../handler-info","router/utils","rsvp/promise","exports"], function(__dependency1__, __dependency2__, __dependency3__, __exports__) { "use strict"; var HandlerInfo = __dependency1__["default"]; var subclass = __dependency2__.subclass; var promiseLabel = __dependency2__.promiseLabel; var Promise = __dependency3__["default"]; var ResolvedHandlerInfo = subclass(HandlerInfo, { resolve: function(shouldContinue, payload) { // A ResolvedHandlerInfo just resolved with itself. if (payload && payload.resolvedModels) { payload.resolvedModels[this.name] = this.context; } return Promise.resolve(this, this.promiseLabel("Resolve")); }, getUnresolved: function() { return this.factory('param', { name: this.name, handler: this.handler, params: this.params }); }, isResolved: true }); __exports__["default"] = ResolvedHandlerInfo; }); define("router/handler-info/unresolved-handler-info-by-object", ["../handler-info","router/utils","rsvp/promise","exports"], function(__dependency1__, __dependency2__, __dependency3__, __exports__) { "use strict"; var HandlerInfo = __dependency1__["default"]; var merge = __dependency2__.merge; var subclass = __dependency2__.subclass; var promiseLabel = __dependency2__.promiseLabel; var isParam = __dependency2__.isParam; var Promise = __dependency3__["default"]; var UnresolvedHandlerInfoByObject = subclass(HandlerInfo, { getModel: function(payload) { this.log(payload, this.name + ": resolving provided model"); return Promise.resolve(this.context); }, initialize: function(props) { this.names = props.names || []; this.context = props.context; }, /** @private Serializes a handler using its custom `serialize` method or by a default that looks up the expected property name from the dynamic segment. @param {Object} model the model to be serialized for this handler */ serialize: function(_model) { var model = _model || this.context, names = this.names, handler = this.handler; var object = {}; if (isParam(model)) { object[names[0]] = model; return object; } // Use custom serialize if it exists. if (handler.serialize) { return handler.serialize(model, names); } if (names.length !== 1) { return; } var name = names[0]; if (/_id$/.test(name)) { object[name] = model.id; } else { object[name] = model; } return object; } }); __exports__["default"] = UnresolvedHandlerInfoByObject; }); define("router/handler-info/unresolved-handler-info-by-param", ["../handler-info","router/utils","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; var HandlerInfo = __dependency1__["default"]; var resolveHook = __dependency2__.resolveHook; var merge = __dependency2__.merge; var subclass = __dependency2__.subclass; var promiseLabel = __dependency2__.promiseLabel; // Generated by URL transitions and non-dynamic route segments in named Transitions. var UnresolvedHandlerInfoByParam = subclass (HandlerInfo, { initialize: function(props) { this.params = props.params || {}; }, getModel: function(payload) { var fullParams = this.params; if (payload && payload.queryParams) { fullParams = {}; merge(fullParams, this.params); fullParams.queryParams = payload.queryParams; } var handler = this.handler; var hookName = resolveHook(handler, 'deserialize') || resolveHook(handler, 'model'); return this.runSharedModelHook(payload, hookName, [fullParams]); } }); __exports__["default"] = UnresolvedHandlerInfoByParam; }); define("router/router", ["route-recognizer","rsvp/promise","./utils","./transition-state","./transition","./transition-intent/named-transition-intent","./transition-intent/url-transition-intent","./handler-info","exports"], function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__, __dependency7__, __dependency8__, __exports__) { "use strict"; var RouteRecognizer = __dependency1__["default"]; var Promise = __dependency2__["default"]; var trigger = __dependency3__.trigger; var log = __dependency3__.log; var slice = __dependency3__.slice; var forEach = __dependency3__.forEach; var merge = __dependency3__.merge; var serialize = __dependency3__.serialize; var extractQueryParams = __dependency3__.extractQueryParams; var getChangelist = __dependency3__.getChangelist; var promiseLabel = __dependency3__.promiseLabel; var callHook = __dependency3__.callHook; var TransitionState = __dependency4__["default"]; var logAbort = __dependency5__.logAbort; var Transition = __dependency5__.Transition; var TransitionAborted = __dependency5__.TransitionAborted; var NamedTransitionIntent = __dependency6__["default"]; var URLTransitionIntent = __dependency7__["default"]; var ResolvedHandlerInfo = __dependency8__.ResolvedHandlerInfo; var pop = Array.prototype.pop; function Router(_options) { var options = _options || {}; this.getHandler = options.getHandler || this.getHandler; this.updateURL = options.updateURL || this.updateURL; this.replaceURL = options.replaceURL || this.replaceURL; this.didTransition = options.didTransition || this.didTransition; this.willTransition = options.willTransition || this.willTransition; this.delegate = options.delegate || this.delegate; this.triggerEvent = options.triggerEvent || this.triggerEvent; this.log = options.log || this.log; this.recognizer = new RouteRecognizer(); this.reset(); } function getTransitionByIntent(intent, isIntermediate) { var wasTransitioning = !!this.activeTransition; var oldState = wasTransitioning ? this.activeTransition.state : this.state; var newTransition; var newState = intent.applyToState(oldState, this.recognizer, this.getHandler, isIntermediate); var queryParamChangelist = getChangelist(oldState.queryParams, newState.queryParams); if (handlerInfosEqual(newState.handlerInfos, oldState.handlerInfos)) { // This is a no-op transition. See if query params changed. if (queryParamChangelist) { newTransition = this.queryParamsTransition(queryParamChangelist, wasTransitioning, oldState, newState); if (newTransition) { return newTransition; } } // No-op. No need to create a new transition. return new Transition(this); } if (isIntermediate) { setupContexts(this, newState); return; } // Create a new transition to the destination route. newTransition = new Transition(this, intent, newState); // Abort and usurp any previously active transition. if (this.activeTransition) { this.activeTransition.abort(); } this.activeTransition = newTransition; // Transition promises by default resolve with resolved state. // For our purposes, swap out the promise to resolve // after the transition has been finalized. newTransition.promise = newTransition.promise.then(function(result) { return finalizeTransition(newTransition, result.state); }, null, promiseLabel("Settle transition promise when transition is finalized")); if (!wasTransitioning) { notifyExistingHandlers(this, newState, newTransition); } fireQueryParamDidChange(this, newState, queryParamChangelist); return newTransition; } Router.prototype = { /** The main entry point into the router. The API is essentially the same as the `map` method in `route-recognizer`. This method extracts the String handler at the last `.to()` call and uses it as the name of the whole route. @param {Function} callback */ map: function(callback) { this.recognizer.delegate = this.delegate; this.recognizer.map(callback, function(recognizer, routes) { for (var i = routes.length - 1, proceed = true; i >= 0 && proceed; --i) { var route = routes[i]; recognizer.add(routes, { as: route.handler }); proceed = route.path === '/' || route.path === '' || route.handler.slice(-6) === '.index'; } }); }, hasRoute: function(route) { return this.recognizer.hasRoute(route); }, getHandler: function() {}, queryParamsTransition: function(changelist, wasTransitioning, oldState, newState) { var router = this; fireQueryParamDidChange(this, newState, changelist); if (!wasTransitioning && this.activeTransition) { // One of the handlers in queryParamsDidChange // caused a transition. Just return that transition. return this.activeTransition; } else { // Running queryParamsDidChange didn't change anything. // Just update query params and be on our way. // We have to return a noop transition that will // perform a URL update at the end. This gives // the user the ability to set the url update // method (default is replaceState). var newTransition = new Transition(this); newTransition.queryParamsOnly = true; oldState.queryParams = finalizeQueryParamChange(this, newState.handlerInfos, newState.queryParams, newTransition); newTransition.promise = newTransition.promise.then(function(result) { updateURL(newTransition, oldState, true); if (router.didTransition) { router.didTransition(router.currentHandlerInfos); } return result; }, null, promiseLabel("Transition complete")); return newTransition; } }, // NOTE: this doesn't really belong here, but here // it shall remain until our ES6 transpiler can // handle cyclical deps. transitionByIntent: function(intent, isIntermediate) { try { return getTransitionByIntent.apply(this, arguments); } catch(e) { return new Transition(this, intent, null, e); } }, /** Clears the current and target route handlers and triggers exit on each of them starting at the leaf and traversing up through its ancestors. */ reset: function() { if (this.state) { forEach(this.state.handlerInfos.slice().reverse(), function(handlerInfo) { var handler = handlerInfo.handler; callHook(handler, 'exit'); }); } this.state = new TransitionState(); this.currentHandlerInfos = null; }, activeTransition: null, /** var handler = handlerInfo.handler; The entry point for handling a change to the URL (usually via the back and forward button). Returns an Array of handlers and the parameters associated with those parameters. @param {String} url a URL to process @return {Array} an Array of `[handler, parameter]` tuples */ handleURL: function(url) { // Perform a URL-based transition, but don't change // the URL afterward, since it already happened. var args = slice.call(arguments); if (url.charAt(0) !== '/') { args[0] = '/' + url; } return doTransition(this, args).method(null); }, /** Hook point for updating the URL. @param {String} url a URL to update to */ updateURL: function() { throw new Error("updateURL is not implemented"); }, /** Hook point for replacing the current URL, i.e. with replaceState By default this behaves the same as `updateURL` @param {String} url a URL to update to */ replaceURL: function(url) { this.updateURL(url); }, /** Transition into the specified named route. If necessary, trigger the exit callback on any handlers that are no longer represented by the target route. @param {String} name the name of the route */ transitionTo: function(name) { return doTransition(this, arguments); }, intermediateTransitionTo: function(name) { return doTransition(this, arguments, true); }, refresh: function(pivotHandler) { var state = this.activeTransition ? this.activeTransition.state : this.state; var handlerInfos = state.handlerInfos; var params = {}; for (var i = 0, len = handlerInfos.length; i < len; ++i) { var handlerInfo = handlerInfos[i]; params[handlerInfo.name] = handlerInfo.params || {}; } log(this, "Starting a refresh transition"); var intent = new NamedTransitionIntent({ name: handlerInfos[handlerInfos.length - 1].name, pivotHandler: pivotHandler || handlerInfos[0].handler, contexts: [], // TODO collect contexts...? queryParams: this._changedQueryParams || state.queryParams || {} }); return this.transitionByIntent(intent, false); }, /** Identical to `transitionTo` except that the current URL will be replaced if possible. This method is intended primarily for use with `replaceState`. @param {String} name the name of the route */ replaceWith: function(name) { return doTransition(this, arguments).method('replace'); }, /** Take a named route and context objects and generate a URL. @param {String} name the name of the route to generate a URL for @param {...Object} objects a list of objects to serialize @return {String} a URL */ generate: function(handlerName) { var partitionedArgs = extractQueryParams(slice.call(arguments, 1)), suppliedParams = partitionedArgs[0], queryParams = partitionedArgs[1]; // Construct a TransitionIntent with the provided params // and apply it to the present state of the router. var intent = new NamedTransitionIntent({ name: handlerName, contexts: suppliedParams }); var state = intent.applyToState(this.state, this.recognizer, this.getHandler); var params = {}; for (var i = 0, len = state.handlerInfos.length; i < len; ++i) { var handlerInfo = state.handlerInfos[i]; var handlerParams = handlerInfo.serialize(); merge(params, handlerParams); } params.queryParams = queryParams; return this.recognizer.generate(handlerName, params); }, applyIntent: function(handlerName, contexts) { var intent = new NamedTransitionIntent({ name: handlerName, contexts: contexts }); var state = this.activeTransition && this.activeTransition.state || this.state; return intent.applyToState(state, this.recognizer, this.getHandler); }, isActiveIntent: function(handlerName, contexts, queryParams, _state) { var state = _state || this.state, targetHandlerInfos = state.handlerInfos, found = false, names, object, handlerInfo, handlerObj, i, len; if (!targetHandlerInfos.length) { return false; } var targetHandler = targetHandlerInfos[targetHandlerInfos.length - 1].name; var recogHandlers = this.recognizer.handlersFor(targetHandler); var index = 0; for (len = recogHandlers.length; index < len; ++index) { handlerInfo = targetHandlerInfos[index]; if (handlerInfo.name === handlerName) { break; } } if (index === recogHandlers.length) { // The provided route name isn't even in the route hierarchy. return false; } var testState = new TransitionState(); testState.handlerInfos = targetHandlerInfos.slice(0, index + 1); recogHandlers = recogHandlers.slice(0, index + 1); var intent = new NamedTransitionIntent({ name: targetHandler, contexts: contexts }); var newState = intent.applyToHandlers(testState, recogHandlers, this.getHandler, targetHandler, true, true); var handlersEqual = handlerInfosEqual(newState.handlerInfos, testState.handlerInfos); if (!queryParams || !handlersEqual) { return handlersEqual; } // Get a hash of QPs that will still be active on new route var activeQPsOnNewHandler = {}; merge(activeQPsOnNewHandler, queryParams); var activeQueryParams = state.queryParams; for (var key in activeQueryParams) { if (activeQueryParams.hasOwnProperty(key) && activeQPsOnNewHandler.hasOwnProperty(key)) { activeQPsOnNewHandler[key] = activeQueryParams[key]; } } return handlersEqual && !getChangelist(activeQPsOnNewHandler, queryParams); }, isActive: function(handlerName) { var partitionedArgs = extractQueryParams(slice.call(arguments, 1)); return this.isActiveIntent(handlerName, partitionedArgs[0], partitionedArgs[1]); }, trigger: function(name) { var args = slice.call(arguments); trigger(this, this.currentHandlerInfos, false, args); }, /** Hook point for logging transition status updates. @param {String} message The message to log. */ log: null }; /** @private Fires queryParamsDidChange event */ function fireQueryParamDidChange(router, newState, queryParamChangelist) { // If queryParams changed trigger event if (queryParamChangelist) { // This is a little hacky but we need some way of storing // changed query params given that no activeTransition // is guaranteed to have occurred. router._changedQueryParams = queryParamChangelist.all; trigger(router, newState.handlerInfos, true, ['queryParamsDidChange', queryParamChangelist.changed, queryParamChangelist.all, queryParamChangelist.removed]); router._changedQueryParams = null; } } /** @private Takes an Array of `HandlerInfo`s, figures out which ones are exiting, entering, or changing contexts, and calls the proper handler hooks. For example, consider the following tree of handlers. Each handler is followed by the URL segment it handles. ``` |~index ("/") | |~posts ("/posts") | | |-showPost ("/:id") | | |-newPost ("/new") | | |-editPost ("/edit") | |~about ("/about/:id") ``` Consider the following transitions: 1. A URL transition to `/posts/1`. 1. Triggers the `*model` callbacks on the `index`, `posts`, and `showPost` handlers 2. Triggers the `enter` callback on the same 3. Triggers the `setup` callback on the same 2. A direct transition to `newPost` 1. Triggers the `exit` callback on `showPost` 2. Triggers the `enter` callback on `newPost` 3. Triggers the `setup` callback on `newPost` 3. A direct transition to `about` with a specified context object 1. Triggers the `exit` callback on `newPost` and `posts` 2. Triggers the `serialize` callback on `about` 3. Triggers the `enter` callback on `about` 4. Triggers the `setup` callback on `about` @param {Router} transition @param {TransitionState} newState */ function setupContexts(router, newState, transition) { var partition = partitionHandlers(router.state, newState); var i, l, handler; for (i=0, l=partition.exited.length; i<l; i++) { handler = partition.exited[i].handler; delete handler.context; callHook(handler, 'reset', true, transition); callHook(handler, 'exit', transition); } var oldState = router.oldState = router.state; router.state = newState; var currentHandlerInfos = router.currentHandlerInfos = partition.unchanged.slice(); try { for (i=0, l=partition.reset.length; i<l; i++) { handler = partition.reset[i].handler; callHook(handler, 'reset', false, transition); } for (i=0, l=partition.updatedContext.length; i<l; i++) { handlerEnteredOrUpdated(currentHandlerInfos, partition.updatedContext[i], false, transition); } for (i=0, l=partition.entered.length; i<l; i++) { handlerEnteredOrUpdated(currentHandlerInfos, partition.entered[i], true, transition); } } catch(e) { router.state = oldState; router.currentHandlerInfos = oldState.handlerInfos; throw e; } router.state.queryParams = finalizeQueryParamChange(router, currentHandlerInfos, newState.queryParams, transition); } /** @private Helper method used by setupContexts. Handles errors or redirects that may happen in enter/setup. */ function handlerEnteredOrUpdated(currentHandlerInfos, handlerInfo, enter, transition) { var handler = handlerInfo.handler, context = handlerInfo.context; if (enter) { callHook(handler, 'enter', transition); } if (transition && transition.isAborted) { throw new TransitionAborted(); } handler.context = context; callHook(handler, 'contextDidChange'); callHook(handler, 'setup', context, transition); if (transition && transition.isAborted) { throw new TransitionAborted(); } currentHandlerInfos.push(handlerInfo); return true; } /** @private This function is called when transitioning from one URL to another to determine which handlers are no longer active, which handlers are newly active, and which handlers remain active but have their context changed. Take a list of old handlers and new handlers and partition them into four buckets: * unchanged: the handler was active in both the old and new URL, and its context remains the same * updated context: the handler was active in both the old and new URL, but its context changed. The handler's `setup` method, if any, will be called with the new context. * exited: the handler was active in the old URL, but is no longer active. * entered: the handler was not active in the old URL, but is now active. The PartitionedHandlers structure has four fields: * `updatedContext`: a list of `HandlerInfo` objects that represent handlers that remain active but have a changed context * `entered`: a list of `HandlerInfo` objects that represent handlers that are newly active * `exited`: a list of `HandlerInfo` objects that are no longer active. * `unchanged`: a list of `HanderInfo` objects that remain active. @param {Array[HandlerInfo]} oldHandlers a list of the handler information for the previous URL (or `[]` if this is the first handled transition) @param {Array[HandlerInfo]} newHandlers a list of the handler information for the new URL @return {Partition} */ function partitionHandlers(oldState, newState) { var oldHandlers = oldState.handlerInfos; var newHandlers = newState.handlerInfos; var handlers = { updatedContext: [], exited: [], entered: [], unchanged: [] }; var handlerChanged, contextChanged = false, i, l; for (i=0, l=newHandlers.length; i<l; i++) { var oldHandler = oldHandlers[i], newHandler = newHandlers[i]; if (!oldHandler || oldHandler.handler !== newHandler.handler) { handlerChanged = true; } if (handlerChanged) { handlers.entered.push(newHandler); if (oldHandler) { handlers.exited.unshift(oldHandler); } } else if (contextChanged || oldHandler.context !== newHandler.context) { contextChanged = true; handlers.updatedContext.push(newHandler); } else { handlers.unchanged.push(oldHandler); } } for (i=newHandlers.length, l=oldHandlers.length; i<l; i++) { handlers.exited.unshift(oldHandlers[i]); } handlers.reset = handlers.updatedContext.slice(); handlers.reset.reverse(); return handlers; } function updateURL(transition, state, inputUrl) { var urlMethod = transition.urlMethod; if (!urlMethod) { return; } var router = transition.router, handlerInfos = state.handlerInfos, handlerName = handlerInfos[handlerInfos.length - 1].name, params = {}; for (var i = handlerInfos.length - 1; i >= 0; --i) { var handlerInfo = handlerInfos[i]; merge(params, handlerInfo.params); if (handlerInfo.handler.inaccessibleByURL) { urlMethod = null; } } if (urlMethod) { params.queryParams = transition._visibleQueryParams || state.queryParams; var url = router.recognizer.generate(handlerName, params); if (urlMethod === 'replace') { router.replaceURL(url); } else { router.updateURL(url); } } } /** @private Updates the URL (if necessary) and calls `setupContexts` to update the router's array of `currentHandlerInfos`. */ function finalizeTransition(transition, newState) { try { log(transition.router, transition.sequence, "Resolved all models on destination route; finalizing transition."); var router = transition.router, handlerInfos = newState.handlerInfos, seq = transition.sequence; // Run all the necessary enter/setup/exit hooks setupContexts(router, newState, transition); // Check if a redirect occurred in enter/setup if (transition.isAborted) { // TODO: cleaner way? distinguish b/w targetHandlerInfos? router.state.handlerInfos = router.currentHandlerInfos; return Promise.reject(logAbort(transition)); } updateURL(transition, newState, transition.intent.url); transition.isActive = false; router.activeTransition = null; trigger(router, router.currentHandlerInfos, true, ['didTransition']); if (router.didTransition) { router.didTransition(router.currentHandlerInfos); } log(router, transition.sequence, "TRANSITION COMPLETE."); // Resolve with the final handler. return handlerInfos[handlerInfos.length - 1].handler; } catch(e) { if (!((e instanceof TransitionAborted))) { //var erroneousHandler = handlerInfos.pop(); var infos = transition.state.handlerInfos; transition.trigger(true, 'error', e, transition, infos[infos.length-1].handler); transition.abort(); } throw e; } } /** @private Begins and returns a Transition based on the provided arguments. Accepts arguments in the form of both URL transitions and named transitions. @param {Router} router @param {Array[Object]} args arguments passed to transitionTo, replaceWith, or handleURL */ function doTransition(router, args, isIntermediate) { // Normalize blank transitions to root URL transitions. var name = args[0] || '/'; var lastArg = args[args.length-1]; var queryParams = {}; if (lastArg && lastArg.hasOwnProperty('queryParams')) { queryParams = pop.call(args).queryParams; } var intent; if (args.length === 0) { log(router, "Updating query params"); // A query param update is really just a transition // into the route you're already on. var handlerInfos = router.state.handlerInfos; intent = new NamedTransitionIntent({ name: handlerInfos[handlerInfos.length - 1].name, contexts: [], queryParams: queryParams }); } else if (name.charAt(0) === '/') { log(router, "Attempting URL transition to " + name); intent = new URLTransitionIntent({ url: name }); } else { log(router, "Attempting transition to " + name); intent = new NamedTransitionIntent({ name: args[0], contexts: slice.call(args, 1), queryParams: queryParams }); } return router.transitionByIntent(intent, isIntermediate); } function handlerInfosEqual(handlerInfos, otherHandlerInfos) { if (handlerInfos.length !== otherHandlerInfos.length) { return false; } for (var i = 0, len = handlerInfos.length; i < len; ++i) { if (handlerInfos[i] !== otherHandlerInfos[i]) { return false; } } return true; } function finalizeQueryParamChange(router, resolvedHandlers, newQueryParams, transition) { // We fire a finalizeQueryParamChange event which // gives the new route hierarchy a chance to tell // us which query params it's consuming and what // their final values are. If a query param is // no longer consumed in the final route hierarchy, // its serialized segment will be removed // from the URL. for (var k in newQueryParams) { if (newQueryParams.hasOwnProperty(k) && newQueryParams[k] === null) { delete newQueryParams[k]; } } var finalQueryParamsArray = []; trigger(router, resolvedHandlers, true, ['finalizeQueryParamChange', newQueryParams, finalQueryParamsArray, transition]); if (transition) { transition._visibleQueryParams = {}; } var finalQueryParams = {}; for (var i = 0, len = finalQueryParamsArray.length; i < len; ++i) { var qp = finalQueryParamsArray[i]; finalQueryParams[qp.key] = qp.value; if (transition && qp.visible !== false) { transition._visibleQueryParams[qp.key] = qp.value; } } return finalQueryParams; } function notifyExistingHandlers(router, newState, newTransition) { var oldHandlers = router.state.handlerInfos, changing = [], leavingIndex = null, leaving, leavingChecker, i, oldHandlerLen, oldHandler, newHandler; oldHandlerLen = oldHandlers.length; for (i = 0; i < oldHandlerLen; i++) { oldHandler = oldHandlers[i]; newHandler = newState.handlerInfos[i]; if (!newHandler || oldHandler.name !== newHandler.name) { leavingIndex = i; break; } if (!newHandler.isResolved) { changing.push(oldHandler); } } if (leavingIndex !== null) { leaving = oldHandlers.slice(leavingIndex, oldHandlerLen); leavingChecker = function(name) { for (var h = 0, len = leaving.length; h < len; h++) { if (leaving[h].name === name) { return true; } } return false; }; } trigger(router, oldHandlers, true, ['willTransition', newTransition]); if (router.willTransition) { router.willTransition(oldHandlers, newState.handlerInfos, newTransition); } } __exports__["default"] = Router; }); define("router/transition-intent", ["./utils","exports"], function(__dependency1__, __exports__) { "use strict"; var merge = __dependency1__.merge; function TransitionIntent(props) { this.initialize(props); // TODO: wat this.data = this.data || {}; } TransitionIntent.prototype = { initialize: null, applyToState: null }; __exports__["default"] = TransitionIntent; }); define("router/transition-intent/named-transition-intent", ["../transition-intent","../transition-state","../handler-info/factory","../utils","exports"], function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __exports__) { "use strict"; var TransitionIntent = __dependency1__["default"]; var TransitionState = __dependency2__["default"]; var handlerInfoFactory = __dependency3__["default"]; var isParam = __dependency4__.isParam; var extractQueryParams = __dependency4__.extractQueryParams; var merge = __dependency4__.merge; var subclass = __dependency4__.subclass; __exports__["default"] = subclass(TransitionIntent, { name: null, pivotHandler: null, contexts: null, queryParams: null, initialize: function(props) { this.name = props.name; this.pivotHandler = props.pivotHandler; this.contexts = props.contexts || []; this.queryParams = props.queryParams; }, applyToState: function(oldState, recognizer, getHandler, isIntermediate) { var partitionedArgs = extractQueryParams([this.name].concat(this.contexts)), pureArgs = partitionedArgs[0], queryParams = partitionedArgs[1], handlers = recognizer.handlersFor(pureArgs[0]); var targetRouteName = handlers[handlers.length-1].handler; return this.applyToHandlers(oldState, handlers, getHandler, targetRouteName, isIntermediate); }, applyToHandlers: function(oldState, handlers, getHandler, targetRouteName, isIntermediate, checkingIfActive) { var i, len; var newState = new TransitionState(); var objects = this.contexts.slice(0); var invalidateIndex = handlers.length; // Pivot handlers are provided for refresh transitions if (this.pivotHandler) { for (i = 0, len = handlers.length; i < len; ++i) { if (getHandler(handlers[i].handler) === this.pivotHandler) { invalidateIndex = i; break; } } } var pivotHandlerFound = !this.pivotHandler; for (i = handlers.length - 1; i >= 0; --i) { var result = handlers[i]; var name = result.handler; var handler = getHandler(name); var oldHandlerInfo = oldState.handlerInfos[i]; var newHandlerInfo = null; if (result.names.length > 0) { if (i >= invalidateIndex) { newHandlerInfo = this.createParamHandlerInfo(name, handler, result.names, objects, oldHandlerInfo); } else { newHandlerInfo = this.getHandlerInfoForDynamicSegment(name, handler, result.names, objects, oldHandlerInfo, targetRouteName, i); } } else { // This route has no dynamic segment. // Therefore treat as a param-based handlerInfo // with empty params. This will cause the `model` // hook to be called with empty params, which is desirable. newHandlerInfo = this.createParamHandlerInfo(name, handler, result.names, objects, oldHandlerInfo); } if (checkingIfActive) { // If we're performing an isActive check, we want to // serialize URL params with the provided context, but // ignore mismatches between old and new context. newHandlerInfo = newHandlerInfo.becomeResolved(null, newHandlerInfo.context); var oldContext = oldHandlerInfo && oldHandlerInfo.context; if (result.names.length > 0 && newHandlerInfo.context === oldContext) { // If contexts match in isActive test, assume params also match. // This allows for flexibility in not requiring that every last // handler provide a `serialize` method newHandlerInfo.params = oldHandlerInfo && oldHandlerInfo.params; } newHandlerInfo.context = oldContext; } var handlerToUse = oldHandlerInfo; if (i >= invalidateIndex || newHandlerInfo.shouldSupercede(oldHandlerInfo)) { invalidateIndex = Math.min(i, invalidateIndex); handlerToUse = newHandlerInfo; } if (isIntermediate && !checkingIfActive) { handlerToUse = handlerToUse.becomeResolved(null, handlerToUse.context); } newState.handlerInfos.unshift(handlerToUse); } if (objects.length > 0) { throw new Error("More context objects were passed than there are dynamic segments for the route: " + targetRouteName); } if (!isIntermediate) { this.invalidateChildren(newState.handlerInfos, invalidateIndex); } merge(newState.queryParams, this.queryParams || {}); return newState; }, invalidateChildren: function(handlerInfos, invalidateIndex) { for (var i = invalidateIndex, l = handlerInfos.length; i < l; ++i) { var handlerInfo = handlerInfos[i]; handlerInfos[i] = handlerInfos[i].getUnresolved(); } }, getHandlerInfoForDynamicSegment: function(name, handler, names, objects, oldHandlerInfo, targetRouteName, i) { var numNames = names.length; var objectToUse; if (objects.length > 0) { // Use the objects provided for this transition. objectToUse = objects[objects.length - 1]; if (isParam(objectToUse)) { return this.createParamHandlerInfo(name, handler, names, objects, oldHandlerInfo); } else { objects.pop(); } } else if (oldHandlerInfo && oldHandlerInfo.name === name) { // Reuse the matching oldHandlerInfo return oldHandlerInfo; } else { if (this.preTransitionState) { var preTransitionHandlerInfo = this.preTransitionState.handlerInfos[i]; objectToUse = preTransitionHandlerInfo && preTransitionHandlerInfo.context; } else { // Ideally we should throw this error to provide maximal // information to the user that not enough context objects // were provided, but this proves too cumbersome in Ember // in cases where inner template helpers are evaluated // before parent helpers un-render, in which cases this // error somewhat prematurely fires. //throw new Error("Not enough context objects were provided to complete a transition to " + targetRouteName + ". Specifically, the " + name + " route needs an object that can be serialized into its dynamic URL segments [" + names.join(', ') + "]"); return oldHandlerInfo; } } return handlerInfoFactory('object', { name: name, handler: handler, context: objectToUse, names: names }); }, createParamHandlerInfo: function(name, handler, names, objects, oldHandlerInfo) { var params = {}; // Soak up all the provided string/numbers var numNames = names.length; while (numNames--) { // Only use old params if the names match with the new handler var oldParams = (oldHandlerInfo && name === oldHandlerInfo.name && oldHandlerInfo.params) || {}; var peek = objects[objects.length - 1]; var paramName = names[numNames]; if (isParam(peek)) { params[paramName] = "" + objects.pop(); } else { // If we're here, this means only some of the params // were string/number params, so try and use a param // value from a previous handler. if (oldParams.hasOwnProperty(paramName)) { params[paramName] = oldParams[paramName]; } else { throw new Error("You didn't provide enough string/numeric parameters to satisfy all of the dynamic segments for route " + name); } } } return handlerInfoFactory('param', { name: name, handler: handler, params: params }); } }); }); define("router/transition-intent/url-transition-intent", ["../transition-intent","../transition-state","../handler-info/factory","../utils","./../unrecognized-url-error","exports"], function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __exports__) { "use strict"; var TransitionIntent = __dependency1__["default"]; var TransitionState = __dependency2__["default"]; var handlerInfoFactory = __dependency3__["default"]; var oCreate = __dependency4__.oCreate; var merge = __dependency4__.merge; var subclass = __dependency4__.subclass; var UnrecognizedURLError = __dependency5__["default"]; __exports__["default"] = subclass(TransitionIntent, { url: null, initialize: function(props) { this.url = props.url; }, applyToState: function(oldState, recognizer, getHandler) { var newState = new TransitionState(); var results = recognizer.recognize(this.url), queryParams = {}, i, len; if (!results) { throw new UnrecognizedURLError(this.url); } var statesDiffer = false; for (i = 0, len = results.length; i < len; ++i) { var result = results[i]; var name = result.handler; var handler = getHandler(name); if (handler.inaccessibleByURL) { throw new UnrecognizedURLError(this.url); } var newHandlerInfo = handlerInfoFactory('param', { name: name, handler: handler, params: result.params }); var oldHandlerInfo = oldState.handlerInfos[i]; if (statesDiffer || newHandlerInfo.shouldSupercede(oldHandlerInfo)) { statesDiffer = true; newState.handlerInfos[i] = newHandlerInfo; } else { newState.handlerInfos[i] = oldHandlerInfo; } } merge(newState.queryParams, results.queryParams); return newState; } }); }); define("router/transition-state", ["./handler-info","./utils","rsvp/promise","exports"], function(__dependency1__, __dependency2__, __dependency3__, __exports__) { "use strict"; var ResolvedHandlerInfo = __dependency1__.ResolvedHandlerInfo; var forEach = __dependency2__.forEach; var promiseLabel = __dependency2__.promiseLabel; var callHook = __dependency2__.callHook; var Promise = __dependency3__["default"]; function TransitionState(other) { this.handlerInfos = []; this.queryParams = {}; this.params = {}; } TransitionState.prototype = { handlerInfos: null, queryParams: null, params: null, promiseLabel: function(label) { var targetName = ''; forEach(this.handlerInfos, function(handlerInfo) { if (targetName !== '') { targetName += '.'; } targetName += handlerInfo.name; }); return promiseLabel("'" + targetName + "': " + label); }, resolve: function(shouldContinue, payload) { var self = this; // First, calculate params for this state. This is useful // information to provide to the various route hooks. var params = this.params; forEach(this.handlerInfos, function(handlerInfo) { params[handlerInfo.name] = handlerInfo.params || {}; }); payload = payload || {}; payload.resolveIndex = 0; var currentState = this; var wasAborted = false; // The prelude RSVP.resolve() asyncs us into the promise land. return Promise.resolve(null, this.promiseLabel("Start transition")) .then(resolveOneHandlerInfo, null, this.promiseLabel('Resolve handler'))['catch'](handleError, this.promiseLabel('Handle error')); function innerShouldContinue() { return Promise.resolve(shouldContinue(), currentState.promiseLabel("Check if should continue"))['catch'](function(reason) { // We distinguish between errors that occurred // during resolution (e.g. beforeModel/model/afterModel), // and aborts due to a rejecting promise from shouldContinue(). wasAborted = true; return Promise.reject(reason); }, currentState.promiseLabel("Handle abort")); } function handleError(error) { // This is the only possible // reject value of TransitionState#resolve var handlerInfos = currentState.handlerInfos; var errorHandlerIndex = payload.resolveIndex >= handlerInfos.length ? handlerInfos.length - 1 : payload.resolveIndex; return Promise.reject({ error: error, handlerWithError: currentState.handlerInfos[errorHandlerIndex].handler, wasAborted: wasAborted, state: currentState }); } function proceed(resolvedHandlerInfo) { var wasAlreadyResolved = currentState.handlerInfos[payload.resolveIndex].isResolved; // Swap the previously unresolved handlerInfo with // the resolved handlerInfo currentState.handlerInfos[payload.resolveIndex++] = resolvedHandlerInfo; if (!wasAlreadyResolved) { // Call the redirect hook. The reason we call it here // vs. afterModel is so that redirects into child // routes don't re-run the model hooks for this // already-resolved route. var handler = resolvedHandlerInfo.handler; callHook(handler, 'redirect', resolvedHandlerInfo.context, payload); } // Proceed after ensuring that the redirect hook // didn't abort this transition by transitioning elsewhere. return innerShouldContinue().then(resolveOneHandlerInfo, null, currentState.promiseLabel('Resolve handler')); } function resolveOneHandlerInfo() { if (payload.resolveIndex === currentState.handlerInfos.length) { // This is is the only possible // fulfill value of TransitionState#resolve return { error: null, state: currentState }; } var handlerInfo = currentState.handlerInfos[payload.resolveIndex]; return handlerInfo.resolve(innerShouldContinue, payload) .then(proceed, null, currentState.promiseLabel('Proceed')); } } }; __exports__["default"] = TransitionState; }); define("router/transition", ["rsvp/promise","./handler-info","./utils","exports"], function(__dependency1__, __dependency2__, __dependency3__, __exports__) { "use strict"; var Promise = __dependency1__["default"]; var ResolvedHandlerInfo = __dependency2__.ResolvedHandlerInfo; var trigger = __dependency3__.trigger; var slice = __dependency3__.slice; var log = __dependency3__.log; var promiseLabel = __dependency3__.promiseLabel; /** @private A Transition is a thennable (a promise-like object) that represents an attempt to transition to another route. It can be aborted, either explicitly via `abort` or by attempting another transition while a previous one is still underway. An aborted transition can also be `retry()`d later. */ function Transition(router, intent, state, error) { var transition = this; this.state = state || router.state; this.intent = intent; this.router = router; this.data = this.intent && this.intent.data || {}; this.resolvedModels = {}; this.queryParams = {}; if (error) { this.promise = Promise.reject(error); this.error = error; return; } if (state) { this.params = state.params; this.queryParams = state.queryParams; this.handlerInfos = state.handlerInfos; var len = state.handlerInfos.length; if (len) { this.targetName = state.handlerInfos[len-1].name; } for (var i = 0; i < len; ++i) { var handlerInfo = state.handlerInfos[i]; // TODO: this all seems hacky if (!handlerInfo.isResolved) { break; } this.pivotHandler = handlerInfo.handler; } this.sequence = Transition.currentSequence++; this.promise = state.resolve(checkForAbort, this)['catch'](function(result) { if (result.wasAborted || transition.isAborted) { return Promise.reject(logAbort(transition)); } else { transition.trigger('error', result.error, transition, result.handlerWithError); transition.abort(); return Promise.reject(result.error); } }, promiseLabel('Handle Abort')); } else { this.promise = Promise.resolve(this.state); this.params = {}; } function checkForAbort() { if (transition.isAborted) { return Promise.reject(undefined, promiseLabel("Transition aborted - reject")); } } } Transition.currentSequence = 0; Transition.prototype = { targetName: null, urlMethod: 'update', intent: null, params: null, pivotHandler: null, resolveIndex: 0, handlerInfos: null, resolvedModels: null, isActive: true, state: null, queryParamsOnly: false, isTransition: true, isExiting: function(handler) { var handlerInfos = this.handlerInfos; for (var i = 0, len = handlerInfos.length; i < len; ++i) { var handlerInfo = handlerInfos[i]; if (handlerInfo.name === handler || handlerInfo.handler === handler) { return false; } } return true; }, /** @public The Transition's internal promise. Calling `.then` on this property is that same as calling `.then` on the Transition object itself, but this property is exposed for when you want to pass around a Transition's promise, but not the Transition object itself, since Transition object can be externally `abort`ed, while the promise cannot. */ promise: null, /** @public Custom state can be stored on a Transition's `data` object. This can be useful for decorating a Transition within an earlier hook and shared with a later hook. Properties set on `data` will be copied to new transitions generated by calling `retry` on this transition. */ data: null, /** @public A standard promise hook that resolves if the transition succeeds and rejects if it fails/redirects/aborts. Forwards to the internal `promise` property which you can use in situations where you want to pass around a thennable, but not the Transition itself. @param {Function} onFulfilled @param {Function} onRejected @param {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} */ then: function(onFulfilled, onRejected, label) { return this.promise.then(onFulfilled, onRejected, label); }, /** @public Forwards to the internal `promise` property which you can use in situations where you want to pass around a thennable, but not the Transition itself. @method catch @param {Function} onRejection @param {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} */ "catch": function(onRejection, label) { return this.promise["catch"](onRejection, label); }, /** @public Forwards to the internal `promise` property which you can use in situations where you want to pass around a thennable, but not the Transition itself. @method finally @param {Function} callback @param {String} label optional string for labeling the promise. Useful for tooling. @return {Promise} */ "finally": function(callback, label) { return this.promise["finally"](callback, label); }, /** @public Aborts the Transition. Note you can also implicitly abort a transition by initiating another transition while a previous one is underway. */ abort: function() { if (this.isAborted) { return this; } log(this.router, this.sequence, this.targetName + ": transition was aborted"); this.intent.preTransitionState = this.router.state; this.isAborted = true; this.isActive = false; this.router.activeTransition = null; return this; }, /** @public Retries a previously-aborted transition (making sure to abort the transition if it's still active). Returns a new transition that represents the new attempt to transition. */ retry: function() { // TODO: add tests for merged state retry()s this.abort(); return this.router.transitionByIntent(this.intent, false); }, /** @public Sets the URL-changing method to be employed at the end of a successful transition. By default, a new Transition will just use `updateURL`, but passing 'replace' to this method will cause the URL to update using 'replaceWith' instead. Omitting a parameter will disable the URL change, allowing for transitions that don't update the URL at completion (this is also used for handleURL, since the URL has already changed before the transition took place). @param {String} method the type of URL-changing method to use at the end of a transition. Accepted values are 'replace', falsy values, or any other non-falsy value (which is interpreted as an updateURL transition). @return {Transition} this transition */ method: function(method) { this.urlMethod = method; return this; }, /** @public Fires an event on the current list of resolved/resolving handlers within this transition. Useful for firing events on route hierarchies that haven't fully been entered yet. Note: This method is also aliased as `send` @param {Boolean} [ignoreFailure=false] a boolean specifying whether unhandled events throw an error @param {String} name the name of the event to fire */ trigger: function (ignoreFailure) { var args = slice.call(arguments); if (typeof ignoreFailure === 'boolean') { args.shift(); } else { // Throw errors on unhandled trigger events by default ignoreFailure = false; } trigger(this.router, this.state.handlerInfos.slice(0, this.resolveIndex + 1), ignoreFailure, args); }, /** @public Transitions are aborted and their promises rejected when redirects occur; this method returns a promise that will follow any redirects that occur and fulfill with the value fulfilled by any redirecting transitions that occur. @return {Promise} a promise that fulfills with the same value that the final redirecting transition fulfills with */ followRedirects: function() { var router = this.router; return this.promise['catch'](function(reason) { if (router.activeTransition) { return router.activeTransition.followRedirects(); } return Promise.reject(reason); }); }, toString: function() { return "Transition (sequence " + this.sequence + ")"; }, /** @private */ log: function(message) { log(this.router, this.sequence, message); } }; // Alias 'trigger' as 'send' Transition.prototype.send = Transition.prototype.trigger; /** @private Logs and returns a TransitionAborted error. */ function logAbort(transition) { log(transition.router, transition.sequence, "detected abort."); return new TransitionAborted(); } function TransitionAborted(message) { this.message = (message || "TransitionAborted"); this.name = "TransitionAborted"; } __exports__.Transition = Transition; __exports__.logAbort = logAbort; __exports__.TransitionAborted = TransitionAborted; }); define("router/unrecognized-url-error", ["./utils","exports"], function(__dependency1__, __exports__) { "use strict"; var oCreate = __dependency1__.oCreate; /** Promise reject reasons passed to promise rejection handlers for failed transitions. */ function UnrecognizedURLError(message) { this.message = (message || "UnrecognizedURLError"); this.name = "UnrecognizedURLError"; Error.call(this); } UnrecognizedURLError.prototype = oCreate(Error.prototype); __exports__["default"] = UnrecognizedURLError; }); define("router/utils", ["exports"], function(__exports__) { "use strict"; var slice = Array.prototype.slice; var _isArray; if (!Array.isArray) { _isArray = function (x) { return Object.prototype.toString.call(x) === "[object Array]"; }; } else { _isArray = Array.isArray; } var isArray = _isArray; __exports__.isArray = isArray; function merge(hash, other) { for (var prop in other) { if (other.hasOwnProperty(prop)) { hash[prop] = other[prop]; } } } var oCreate = Object.create || function(proto) { function F() {} F.prototype = proto; return new F(); }; __exports__.oCreate = oCreate; /** @private Extracts query params from the end of an array **/ function extractQueryParams(array) { var len = (array && array.length), head, queryParams; if(len && len > 0 && array[len - 1] && array[len - 1].hasOwnProperty('queryParams')) { queryParams = array[len - 1].queryParams; head = slice.call(array, 0, len - 1); return [head, queryParams]; } else { return [array, null]; } } __exports__.extractQueryParams = extractQueryParams;/** @private Coerces query param properties and array elements into strings. **/ function coerceQueryParamsToString(queryParams) { for (var key in queryParams) { if (typeof queryParams[key] === 'number') { queryParams[key] = '' + queryParams[key]; } else if (isArray(queryParams[key])) { for (var i = 0, l = queryParams[key].length; i < l; i++) { queryParams[key][i] = '' + queryParams[key][i]; } } } } /** @private */ function log(router, sequence, msg) { if (!router.log) { return; } if (arguments.length === 3) { router.log("Transition #" + sequence + ": " + msg); } else { msg = sequence; router.log(msg); } } __exports__.log = log;function bind(context, fn) { var boundArgs = arguments; return function(value) { var args = slice.call(boundArgs, 2); args.push(value); return fn.apply(context, args); }; } __exports__.bind = bind;function isParam(object) { return (typeof object === "string" || object instanceof String || typeof object === "number" || object instanceof Number); } function forEach(array, callback) { for (var i=0, l=array.length; i<l && false !== callback(array[i]); i++) { } } __exports__.forEach = forEach;function trigger(router, handlerInfos, ignoreFailure, args) { if (router.triggerEvent) { router.triggerEvent(handlerInfos, ignoreFailure, args); return; } var name = args.shift(); if (!handlerInfos) { if (ignoreFailure) { return; } throw new Error("Could not trigger event '" + name + "'. There are no active handlers"); } var eventWasHandled = false; for (var i=handlerInfos.length-1; i>=0; i--) { var handlerInfo = handlerInfos[i], handler = handlerInfo.handler; if (handler.events && handler.events[name]) { if (handler.events[name].apply(handler, args) === true) { eventWasHandled = true; } else { return; } } } if (!eventWasHandled && !ignoreFailure) { throw new Error("Nothing handled the event '" + name + "'."); } } __exports__.trigger = trigger;function getChangelist(oldObject, newObject) { var key; var results = { all: {}, changed: {}, removed: {} }; merge(results.all, newObject); var didChange = false; coerceQueryParamsToString(oldObject); coerceQueryParamsToString(newObject); // Calculate removals for (key in oldObject) { if (oldObject.hasOwnProperty(key)) { if (!newObject.hasOwnProperty(key)) { didChange = true; results.removed[key] = oldObject[key]; } } } // Calculate changes for (key in newObject) { if (newObject.hasOwnProperty(key)) { if (isArray(oldObject[key]) && isArray(newObject[key])) { if (oldObject[key].length !== newObject[key].length) { results.changed[key] = newObject[key]; didChange = true; } else { for (var i = 0, l = oldObject[key].length; i < l; i++) { if (oldObject[key][i] !== newObject[key][i]) { results.changed[key] = newObject[key]; didChange = true; } } } } else { if (oldObject[key] !== newObject[key]) { results.changed[key] = newObject[key]; didChange = true; } } } } return didChange && results; } __exports__.getChangelist = getChangelist;function promiseLabel(label) { return 'Router: ' + label; } __exports__.promiseLabel = promiseLabel;function subclass(parentConstructor, proto) { function C(props) { parentConstructor.call(this, props || {}); } C.prototype = oCreate(parentConstructor.prototype); merge(C.prototype, proto); return C; } __exports__.subclass = subclass;function resolveHook(obj, hookName) { if (!obj) { return; } var underscored = "_" + hookName; return obj[underscored] && underscored || obj[hookName] && hookName; } function callHook(obj, _hookName, arg1, arg2) { var hookName = resolveHook(obj, _hookName); return hookName && obj[hookName].call(obj, arg1, arg2); } function applyHook(obj, _hookName, args) { var hookName = resolveHook(obj, _hookName); if (hookName) { if (args.length === 0) { return obj[hookName].call(obj); } else if (args.length === 1) { return obj[hookName].call(obj, args[0]); } else if (args.length === 2) { return obj[hookName].call(obj, args[0], args[1]); } else { return obj[hookName].apply(obj, args); } } } __exports__.merge = merge; __exports__.slice = slice; __exports__.isParam = isParam; __exports__.coerceQueryParamsToString = coerceQueryParamsToString; __exports__.callHook = callHook; __exports__.resolveHook = resolveHook; __exports__.applyHook = applyHook; }); define("router", ["./router/router","exports"], function(__dependency1__, __exports__) { "use strict"; var Router = __dependency1__["default"]; __exports__["default"] = Router; });define("route-recognizer", [], function() { return {"default": commonObj.RouteRecognizer}; }); define("rsvp", [], function() { return commonObj.RSVP;}); define("rsvp/promise", [], function() { return {"default": commonObj.RSVP.Promise}; }); module.exports = requireModule('router').default; <|start_filename|>example/PPRouter/react-example/src/router.js<|end_filename|> import RouterFactory from "../../index" import React from "react" var Router = RouterFactory(); class RootComp extends React.Component { render() { return <div> <h1><a href="/">Router Example APP</a> ({this.props.data || 0})</h1> <a href="/items">Items</a> {this.props.children} </div> } } class ItemsComp extends React.Component { render() { var items = this.props.data.map(item => <li key={item.id}><a href={'/items/' + item.id}>{item.name}</a></li>); return <div> <ul>{items}</ul> {this.props.children} </div> } } class ItemComp extends React.Component { render() { return <div> <label>ID: {this.props.data.id}</label> <h5>name: {this.props.data.name}</h5> <p>{this.props.data.description}</p> {this.props.children} </div> } } Router(function(Router){ Router("/items", function(Router){ Router('/:id').component(React.createElement.bind(React, ItemComp)).then(getItem); }).component(React.createElement.bind(React, ItemsComp)).then(getItems); }).component(React.createElement.bind(React, RootComp)) function getItems(){ return new Promise(function(resolve, reject){ setTimeout(function(){ resolve(Items); }, 100); }) } function getItem(data, context){ return Items.reduce(function(result, item){ if(result) return result; if(item.id == context.params.id) return item; }, null); } function count(){ return new Promise(function(resolve, reject){ setTimeout(function(){ resolve(Items.length); }, 100); }) } var Items = [ { id:1, name: "Item1", description: "The Item Description" }, { id:2, name: "Item2", description: "The Item2 Description" }, { id:3, name: "Item3", description: "The Item3 Description" } ]; export var Router = Router; <|start_filename|>src/linkProcessors/cacheProcessor.js<|end_filename|> let Context = require('../Context'), debug = require('debug')('PP:runner'); module.exports = function catchProcessor(PromisePipe){ return { name: 'cacheProcessor', predicate: function isCache(link) { return link.isCache; }, handler: function isCacheHandler(link, context, data, executingChain, chain, Pipe) { var toNextEnv = getNameNextEnv(PromisePipe.env, context); if (!toNextEnv) { return executingChain.then(link._handler); } let range = rangeChain(chain[getChainIndexById(link._id, chain) + 1]._id, chain); Context.passChains(context, passChains(range[0], range[1], chain)); function cacherFunc(data, context){ var handler = {}; var cacheResult = new Promise(function(resolve, reject){ handler.reject=reject; handler.resolve=resolve; }); var result = link._handler.call(this, data, context, cacheResult); if(!result) { return { res: function(cacheResult){ return handler.resolve(cacheResult); }, data:data } } else { return { res:result, data: data }; } } return executingChain.then(cacherFunc).then(function (cacheResult) { function fillCache(response){ debug(`link ${link._id} on ${PromisePipe.env} PUT in cache result from ${toNextEnv}`) cacheResult.res(response.data); return response; } if(typeof(cacheResult.res) == "function"){ debug(`- cache: link ${link._id} executed on ${PromisePipe.env} now send execution to ${toNextEnv}`) var msg = PromisePipe.createTransitionMessage(cacheResult.data, context, Pipe._id, chain[range[0]]._id, chain[range[1]]._id, context._pipecallId); return PromisePipe.TransactionHandler.createTransaction(msg) .send(PromisePipe.envTransitions[context._env][toNextEnv]) .then(context.updateContextAfterTransition) .then(fillCache) .then(handleRejectAfterTransition) } else { return cacheResult.res; } }); } }; /** * Return filtered list for passing functions * @param {Number} first * @param {Number} last * @return {Array} */ function passChains (first, last, sequence) { return sequence.map(function (el) { return el._id; }).slice(first, last + 1); } /** * Return lastChain index * @param {Number} first * @return {Number} */ function lastChain (first, sequence) { var index = getIndexOfNextEnvAppearance(first, PromisePipe.env, sequence); return index === -1 ? (sequence.length - 1) : (index - 1); } /** * Get chain by index * @param {String} id * @param {Array} sequence */ function getChainIndexById(id, sequence){ return sequence.map(function(el){ return el._id; }).indexOf(id); } /** * Get index of next env appearance * @param {Number} fromIndex * @param {String} env * @return {Number} */ function getIndexOfNextEnvAppearance(fromIndex, env, sequence){ return sequence.map(function(el){ return el._env; }).indexOf(env, fromIndex); } /** * Return tuple of chained indexes * @param {Number} id * @return {Tuple} */ function rangeChain (id, sequence) { var first = getChainIndexById(id, sequence); return [first, lastChain(first, sequence)]; } function getNameNextEnv(env, context) { if (!PromisePipe.envTransitions[context._env]) { return null; } return Object.keys(PromisePipe.envTransitions[context._env]).reduce(function (nextEnv, name) { if (nextEnv) { return nextEnv; } if (name === env) { return nextEnv; } if (name !== env) { return name; } }, null); } } function handleRejectAfterTransition(message){ return new Promise(function(resolve, reject){ if(message.unhandledFail) return reject(message.data); resolve(message.data); }) } <|start_filename|>example/auction/src/components/RootComp.js<|end_filename|> import React from "react" class RootComp extends React.Component { constructor(props) { super(props); this.state = { me: {}, items: props.data || [] } if(this.props.context.client){ var client = this.props.context.client; this.state.me = client.MeStore.get() client.MeStore.on('change', (user)=>{ this.setState({me:user}); }) client.ItemsStore.fill(props.data); client.ItemsStore.on('change', (items)=>{ this.setState({items:items}); }) } } componentWillUnmount (){ if(this.props.context.client){ var client = this.props.context.client; client.ItemsStore.removeAllListeners('change') client.MeStore.removeAllListeners('change') } } logout(e){ e.preventDefault(); this.props.context.logout(null, this.props.context); } render() { var data = this.state.items; var content; if(this.props.children && this.props.children[0]) { content = this.props.children; } else { content = <ul className="list-unstyled auction-list"> {data.map((item)=>{ return <li className="row"> <div className="col-md-2"><img src={'/images/' + item.img}/></div> <div className="col-md-8"> <h3><a href={'/item/' + item.id}>name: {item.name}</a></h3> <p> {item.description} </p> </div> <div className="col-md-2 text-right"> <label className="bid">bid: {item.bids && item.bids[0]?item.bids[0].bid:item.startBid}&euro;</label> <div className="by">{item.bids && item.bids[0]?(' by ' + item.bids[0].user.name):''}</div> </div> </li> })} </ul>; } var loggedInUser; if(this.state.me.name){ loggedInUser = [<li> <a href={"/users/" + this.state.me.id}>{this.state.me.name}</a> </li>, <li> <a className="btn btn-default" onClick={this.logout.bind(this)}>Logout</a> </li>]; } else { loggedInUser = <li><a href="/login">Login</a></li>; } return <div> <nav className="navbar navbar-default"> <div className="container-fluid"> <div className="navbar-header"> <a className="navbar-brand" href="/">Open Auction</a> </div> <ul className="nav navbar-nav navbar-right"> {loggedInUser} </ul> </div> </nav> {content} </div> } } export default RootComp <|start_filename|>src/PipeLink.js<|end_filename|> let Context = require('./Context.js'); let debug = require('debug')('PP:pagelink'); module.exports = class PipeLink { constructor(fn, ID) { this._originalHandler = fn; this._handler = fn; this._id = ID; this.name = fn.name; this._context = undefined; } setEnv(env) { this._env = env; return this; } setCatch() { this.isCatch = true; return this; } setCache() { this.isCache = true; return this; } mixContext(context) { const handler = this._handler; this.context = context; this._handler = function() { let args = [].slice.call(arguments); args[1] = context; return handler.apply(context, args); } return this; } static getNewLink(fn, ID) { return new PipeLink(fn, ID); } static getCleanupLink(ID) { let link = new PipeLink(cleanUpLink, ID); link.name = 'cleanUpLink'; return link; } static getDebugLink(ID) { let link = new PipeLink(cleanUpLink, ID); link.name = 'debugLink'; return link; } static cloneLink(link) { let newLink = new PipeLink(link._originalHandler); newLink.name = link.name; newLink._env = link._env; newLink._id = link._id; newLink.isCatch = link.isCatch; newLink.isCache = link.isCache; return newLink; } } function cleanUpLink(data, context) { Context.cleanUp(context); return data; } function debugLink(data, context) { console.log("PRINT DEBUG"); return data; } <|start_filename|>example/webworker/main.js<|end_filename|> var work = require('webworkify'); var connectors = require('../connectors/WorkerDuplexStream.js') var logic = require('./logic.js') ENV = 'CLIENT'; var w = work(require('./worker.js')); logic.pipe.stream('client','worker').connector(connectors.ClientWorkerStream(w)) module.exports = logic; <|start_filename|>example/PPRouter/example/server.js<|end_filename|> var express = require('express'); var app = express(); import {Router} from "./src/router" import ExpressAppAdapter from "../adapters/ExpressAdapter.js" function layout(html, renderData){ var stateString = JSON.stringify(renderData); return `<html> <head> </head> <body> <div id="content">${html}</div> <script type="text/javascript" src="/bundle.js"></script> <script type="text/javascript"> require('app')(${stateString}); </script> </body> </html>`; } app.use(express.static("./")) Router.use(ExpressAppAdapter(app, layout)); app.listen(3000); <|start_filename|>example/PPRouter/react-example/src/app.js<|end_filename|> import React from "react" import {Router} from "./router" import HistoryApiAdapter from "../../adapters/HistoryApiAdapter" function mount(data){ React.render(data, document.getElementById('content')); } var FrontendAdapter = HistoryApiAdapter(mount); Router.use(FrontendAdapter); document.getElementById('content').onclick = function(e){ e.preventDefault() e.stopPropagation(); if(e.target.nodeType == 1 && e.target.href && e.target.href.indexOf(document.location.origin) == 0 && document.location.pathname !== e.target.pathname) {//is a link Router.router.transitionTo(e.target.pathname) } } module.exports = function(state){ mount(FrontendAdapter.renderer(Router.prepareRenderData(state))); } <|start_filename|>example/connectors/WorkerDuplexStream.js<|end_filename|> function Stream(worker){ return { send: function(message){ worker.postMessage(message); }, listen: function(handler){ worker.addEventListener('message', function (ev) { handler(ev.data); }); } } } module.exports = { ClientWorkerStream: Stream, WorkerClientStream: Stream } <|start_filename|>example/auction/src/components/UserComp.js<|end_filename|> import React from "react" class UserComp extends React.Component { constructor(props) { super(props); this.state = { user: props.data && props.data[0] }; } render() { return <div> <h2>{this.state.user.id}: {this.state.user.name}</h2> <p>login: {this.state.user.login}</p> </div> } } export default UserComp <|start_filename|>src/TransactionController.js<|end_filename|> var Promise = Promise || require('es6-promise').Promise, debug = require('debug')('PP:transactions'); module.exports = function TransactionController(options){ if(typeof(debug) === "undefined") debug = function(){}; //for tests sake options = options || {}; var timeout = options.timeout || 2000; var transactions = {}; return { createTransaction: function createTransaction (message){ message._transactionId = Math.ceil(Math.random() * Math.pow(10, 16)); debug(`create transaction with tId ${message._transactionId}`); return { send: function sendTransaction(handler){ debug(`send message with tId ${message._transactionId}`); return new Promise(function(resolve, reject){ //save transaction Resolvers transactions[message._transactionId] = { resolve: resolve, timeoutId: setTimeout(reject.bind(this, "message took more than " + timeout), timeout) } handler(message); }) } } }, processTransaction: function processTransaction(transactionMessage){ debug(`process ${!!transactions[transactionMessage._transactionId]?'existing':'nonexisting'} response with tId ${transactionMessage._transactionId} `); if(transactions[transactionMessage._transactionId]){ var id = transactionMessage._transactionId; delete transactionMessage._transactionId; transactions[id].resolve(transactionMessage); clearTimeout(transactions[id].timeoutId); delete transactions[transactionMessage._transactionId] return true; } return false; } } } <|start_filename|>src/PromisePipe.js<|end_filename|> var PipeLink = require('./PipeLink'); var Context = require('./Context'); var gedID = require('./ID'); var chainRunner = require('./chainRunner'); var TransactionController = require('./TransactionController'); var debug = require('debug')('PP'); module.exports = function PromisePipeFactory(options = {}) { options.timeout = options.timeout || 2000; options.logger = options.logger || console; debug('PromisePipe create'); let ID = gedID(); function PromisePipe(sequence = [], opts) { if(!(sequence instanceof Array)) { opts = sequence; sequence = []; } function Pipe(data, context = {}) { //context.generatePipeCallId(); - check it should be automatically on first call //and it should start tracing Context.setEnv( Context.setPipeCallId( context, Math.ceil(Math.random() * Math.pow(10, 16)) ), PromisePipe.env); debug('Pipe run ', context._pipeCallId); //clone existing sequence for this pipe let chain = [].concat.apply([], sequence) .map(PipeLink.cloneLink) .map((link) => link.setEnv(link._env || PromisePipe.env)); //add debug chain if(PromisePipe.mode === 'DEBUG') { chain = chain.concat( PipeLink.getDebugLink(ID()) .setEnv(PromisePipe.env)); } //add cleanup context chain chain = chain.concat( PipeLink.getCleanupLink(ID()) .setEnv(PromisePipe.env)); //add context to all chains chain = chain.map((link) => link.mixContext(context)); //run the chain return executeChain(chain, Pipe, data, context); } Pipe._id = ID(); PromisePipe.pipes[Pipe._id] = { id: Pipe._id, sequence: sequence, name: opts && opts.name, description: opts && opts.description, Pipe: Pipe } Pipe.then = function then(fn, env) { let link = PipeLink.getNewLink(fn, ID()) .setEnv(env || fn._env); sequence.push(link); return Pipe; } Pipe.catch = function catchFn(fn, env) { let link = PipeLink.getNewLink(fn, ID()) .setEnv(env || fn._env) .setCatch(); sequence.push(link); return Pipe; } Pipe.cache = function cache(fn, env) { let link = PipeLink.getNewLink(fn, ID()) .setEnv(env || fn._env) .setCache(); sequence.push(link); return Pipe; } // join pipes Pipe.join = function(){ var sequences = [].map.call(arguments, function(pipe){ return pipe._getSequence(); }); var newSequence = sequence.concat.apply(sequence, sequences); return PromisePipe(newSequence); }; // get an array of pipes Pipe._getSequence = function(){ return sequence; }; Object.keys(PromisePipe.transformations).forEach(function addTransformations(name){ var customApi = PromisePipe.transformations[name]; const wrapper = typeof customApi === 'object' ? wrapObject : wrapPromise; customApi._name = name; Pipe[name] = wrapper(customApi, sequence, Pipe); }); return Pipe; } const { executeChain } = chainRunner(PromisePipe, options); PromisePipe.TransactionHandler = TransactionController(options); function wrapObject(customApi, sequence, thePipe){ return Object.keys(customApi).reduce(function(api, apiName){ if(apiName.charAt(0) === "_") return api; customApi[apiName]._env = customApi._env; customApi[apiName]._name = customApi._name +"."+ apiName; const wrapper = typeof customApi[apiName] === 'object' ? wrapObject : wrapPromise; api[apiName] = wrapper(customApi[apiName], sequence, thePipe); return api; }, {}); } function wrapPromise(customApi, sequence, thePipe){ return function wrapper() { const args = [].slice.call(arguments); function wrapperApiFunction(data, context) { return customApi.apply(thePipe, [data, context].concat(args)) } let link = PipeLink.getNewLink(wrapperApiFunction, ID()).setEnv(customApi._env); link.name = customApi._name; link.isCatch = customApi.isCatch; link.isCache = customApi.isCache; sequence.push(link); return thePipe; } } function addContextToLinks(context) { return function mapContextMixing(link) { return link.mixContext(context); } } // PromisePipe is a singleton // that knows about all pipes and you can get a pipe by ID's PromisePipe.pipes = {}; PromisePipe._mode = 'PROD'; /** * DEBUG/TEST/PROD * */ PromisePipe.setMode = function(mode){ PromisePipe._mode = mode; }; /* * setting up env for pipe */ PromisePipe.setEnv = function(env){ PromisePipe.env = env; }; PromisePipe.transformations = {}; /* * add new API for PromisePipe */ PromisePipe.use = function use(name, handler = ()=>{}, options = {}) { if(!options._env) { options._env = PromisePipe.env; } PromisePipe.transformations[name] = handler; Object.keys(options).forEach(function(optname){ PromisePipe.transformations[name][optname] = options[optname]; }); } PromisePipe.envTransitions = {}; // Inside transition you describe how to send message from one // env to another within a Pipe call PromisePipe.envTransition = function(from, to, transition){ if(!PromisePipe.envTransitions[from]) { PromisePipe.envTransitions[from] = {}; } PromisePipe.envTransitions[from][to] = transition; }; // the ENV is a client by default PromisePipe.setEnv('client'); /* * Is setting up function to be executed inside specific ENV * usage: * var doOnServer = PromisePipe.in('server'); * PromisePipe().then(doOnServer(fn)); * or * PromisePipe().then(PromisePipe.in('worker').do(fn)); */ PromisePipe.in = function(env){ if(!env) throw new Error('You should explicitly specify env'); var result = function makeEnv(fn){ var ret = fn.bind(null); ret._env = env; return ret; }; result.do = function doIn(fn){ var ret = fn.bind(null); ret._env = env; return ret; }; return result; }; // when you pass a message within a pipe to other env // you should PromisePipe.execTransitionMessage = function execTransitionMessage(message){ if(PromisePipe.TransactionHandler.processTransaction(message)) return {then: function(){}} debug(`execute message for ${message.call} of pipe: ${message.pipe}`); var context = message.context; context._env = PromisePipe.env; delete context._passChains; //get back contexts non enumerables Context.setPipeCallId(context, message.call); //TODO:augmentContext(context, '_trace', message._trace); var sequence = PromisePipe.pipes[message.pipe].sequence; let chain = [].concat.apply([], sequence) .map(PipeLink.cloneLink) .map((link) => link.setEnv(link._env || PromisePipe.env)); var ids = chain.map(function(el){ return el._id; }); //Check that this is bounded chain nothing is passed through var firstChainIndex = ids.indexOf(message.chains[0]); //someone is trying to hack the Pipe if(firstChainIndex > 0 && sequence[firstChainIndex]._env === sequence[firstChainIndex - 1]._env) { debug("Non-consistent pipe call, message is trying to omit chains"); return Promise.reject({error: "Non-consistent pipe call, message is trying to omit chains"}).catch(unhandledCatch); } var newChain = chain.slice(firstChainIndex, ids.indexOf(message.chains[1]) + 1); newChain = newChain.map((link) => link.mixContext(context)); //catch inside env function unhandledCatch(data){ message.unhandledFail = data; return data; } return executeChain(newChain, PromisePipe.pipes[message.pipe].Pipe, message.data, context).catch(unhandledCatch); }; PromisePipe.createTransitionMessage = function createTransitionMessage(data, context, pipeId, chainId, envBackChainId, callId){ var contextToSend = JSON.parse(JSON.stringify(context)); delete contextToSend[context._env] return { data: data, context: contextToSend, pipe: pipeId, chains: [chainId, envBackChainId], call: callId, _trace: context._trace }; }; PromisePipe.localContext = function(context){ return { execTransitionMessage: function(message){ var origContext = message.context; context.__proto__ = origContext; message.context = context; return PromisePipe.execTransitionMessage(message).then(function(data){ message.context = origContext; return data; }); } }; }; PromisePipe.stream = function(from, to, processor){ return { connector: function(strm){ //set transition PromisePipe.envTransition(from, to, function(message){ strm.send(message); }); strm.listen(function(message){ var context = message.context; var data = message.data; function end(data){ message.context = context; message.data = data; strm.send(message); } if(processor){ function executor(data, context){ message.data = data; message.context = context; return PromisePipe.execTransitionMessage(message); } var localContext = {}; localContext.__proto__= context; return processor(data, localContext, executor, end); } return PromisePipe.execTransitionMessage(message).then(end); }); } }; }; PromisePipe.api = require('./RemoteAPIHandlers')(PromisePipe); return PromisePipe; } <|start_filename|>example/simple-todo/logic.js<|end_filename|> var PromisePipe = require('../../src/PromisePipe')(); var Promise = require('es6-promise').Promise; PromisePipe.setMode('DEBUG'); var ENV = 'CLIENT'; //set up server if(typeof(window) !== 'object'){ PromisePipe.setEnv('server'); ENV = 'SERVER'; } var returnItems = doOnServer(function returnItems(data, context){ return context.todolist; }) var doneItem = doOnServer(function doneItem(data, context){ data.done = !data.done; return data; }) var addItem = doOnServer(function addItem(data, context){ var nextId = context.todolist.length>0?(context.todolist[context.todolist.length - 1].id + 1):0; var item = { id: nextId, name: data, done: false } context.todolist.push(item); return data; }) var removeById = doOnServer(function removeById(data, context){ var resId = null; context.todolist.forEach(function(item, i){ if(item.id == data) resId = i; }); var old = context.todolist[resId]; context.todolist.splice(resId,1); return old; }) var getById = doOnServer(function getById(data, context){ var resId = null; context.todolist.forEach(function(item, i){ if(item.id == data) resId = i; }); return context.todolist[resId]; }) var clearDone = doOnServer(function clearDone(data, context){ context.todolist.forEach(function(item, i){ if(item.done) context.todolist.splice(i,1); }); return context.todolist; }) module.exports = { PromisePipe: PromisePipe, addItem: PromisePipe() .then(addItem) .then(returnItems) .then(buildHtml) .then(renderItems), removeItem: PromisePipe() .then(removeById) .then(returnItems) .then(buildHtml) .then(renderItems), getItems: PromisePipe() .then(returnItems) .then(buildHtml) .then(renderItems), doneItem: PromisePipe() .then(getById) .then(doneItem) .then(returnItems) .then(buildHtml) .then(renderItems), clearDoneItems: PromisePipe() .then(clearDone) .then(returnItems) .then(buildHtml) .then(renderItems) } function buildHtml(data){ var result = ""; data = data || []; result+="<ul>"; result+=data.map(function(item, i){ var name = item.name; if(item.done) name = "<strike>"+name + "</strike>"; return "<li>"+name+"<button onclick='main.doneItem("+item.id+")'>+</button><button onclick='main.removeItem("+item.id+")'>x</button></li>"; }).join(''); result+="</ul>"; return result; } function renderItems(data){ document.getElementById('todolist').innerHTML = data; return data; } function doOnServer(fn){ fn._env = 'server'; return fn } <|start_filename|>src/linkProcessors/catchProcessor.js<|end_filename|> module.exports = function catchProcessor(PromisePipe){ return { name: 'catchProcessor', predicate: function isCatch(link) { return !!link.isCatch; }, handler: function isCatchHandler(link, context, data, executingChain, chain, Pipe) { return executingChain.catch(link._handler); } }; } <|start_filename|>example/mongotodo/client.js<|end_filename|> var logic = require('./logic'); var connectors = require('../connectors/SessionSocketIODuplexStream') var PromisePipe = logic.PromisePipe; var socket = io.connect(document.location.toString()); PromisePipe.stream('client','server').connector(connectors.SIOClientServerStream(socket)) module.exports = logic; <|start_filename|>example/webworker/logic.js<|end_filename|> var PromisePipe = require('../../src/PromisePipe')(); PromisePipe.setMode('DEBUG'); var Promise = require('es6-promise').Promise; //set up server //((2+5-6+10)*2)^3-2-6 = 10640 module.exports = PromisePipe() .then(plus(5)) .then(minus(6)) .then(doInWorker(plus(10))) .then(doInWorker(multipy(2))) .then(pow(3)) .then(doInWorker(minus(2))) .then(minus(6)) module.exports.pipe = PromisePipe; function plus(a){ return function plus(data, context){ return doAsyncStuff("add "+a+" to "+data, function(){ return data + a; }) } } function minus(a){ return function minus(data, context){ return doAsyncStuff("subtract "+a+" of "+data, function(){ return data - a; }); } } function doInWorker(fn){ fn._env = 'worker'; return fn } function prepare(data, context){ if(!context.stack) context.stack = []; return data; } function multipy(a){ return function multipy(data, context){ return doAsyncStuff("multipy "+data+" by "+a, function(){ return data * a; }); } } function pow(a){ return function pow(data, context){ return doAsyncStuff("power "+data+" by "+a, function(){ return Math.pow(data, a); }); } } function doAsyncStuff(text, fn){ console.log(text, ENV); return new Promise(function(res, rej){ var result = fn.call(null); setTimeout(function(){ console.log("=", result); res(result); }, 1000); }) } <|start_filename|>tests/error.PromisePipe.spec.js<|end_filename|> var expect = require('chai').expect; var sinon = require('sinon'); var Promise = require('es6-promise').Promise; var expect = require('chai').expect; describe('PromisePipe with 3 functions when called', function(){ var hook; var PromisePipe = require('../src/PromisePipe')(); var context = {}; var data1 = 1; var data2 = 2; var data3 = 3; var fn1 = sinon.stub(); var fn2 = sinon.stub(); var fn3 = sinon.stub(); var finish = sinon.spy(); var finish1 = sinon.spy(); //if runninng with data1 //fn1.withArgs(data1, context).throws(data2); fn2.withArgs(data2, context).returns(data3); fn3.withArgs(data3, context).returns(data1); var pipe = PromisePipe() .then(function test(){ return ff() }) .then(fn2) .then(fn3) before(function(done){ hook = captureStream(process.stdout); pipe(data1, context).then(finish); done() }) it('should end with final function', function(){ sinon.assert.notCalled(fn2); sinon.assert.notCalled(fn3); expect(/Failed inside test/.test(hook.captured())).to.be.ok; expect(/ReferenceError: ff is not defined/.test(hook.captured())).to.be.ok; expect(/error.PromisePipe.spec.js:/.test(hook.captured())).to.be.ok; hook.unhook(); }); }); describe('PromisePipe with custom logger', function () { var hook; var logger = { log: sinon.stub(), }; var PromisePipe = require('../src/PromisePipe')({ logger: logger }); var context = {}; var data1 = 1; var data2 = 2; var data3 = 3; var fn1 = sinon.stub(); var fn2 = sinon.stub(); var fn3 = sinon.stub(); var finish = sinon.spy(); var finish1 = sinon.spy(); //if runninng with data1 //fn1.withArgs(data1, context).throws(data2); fn2.withArgs(data2, context).returns(data3); fn3.withArgs(data3, context).returns(data1); var pipe = PromisePipe() .then(function test(){ return ff() }) .then(fn2) .then(fn3); before(function(done){ hook = captureStream(process.stdout); pipe(data1, context).then(finish); done() }) after(function () { hook.unhook(); }); it('should end with final function', function(){ sinon.assert.notCalled(fn2); sinon.assert.notCalled(fn3); expect(logger.log.callCount).to.be.eql(3); expect(/Failed inside test/.test(logger.log.firstCall.args[0])).to.be.ok; expect(/ReferenceError: ff is not defined/.test(logger.log.secondCall.args[0])).to.be.ok; expect(/error.PromisePipe.spec.js:/.test(logger.log.thirdCall.args[0])).to.be.ok; expect(hook.captured()).to.be.eql(''); }); }); function captureStream(stream){ var oldWrite = stream.write; var buf = ''; stream.write = function(chunk, encoding, callback){ buf += chunk.toString(); // chunk is a String or Buffer oldWrite.apply(stream, arguments); } return { unhook: function unhook(){ stream.write = oldWrite; }, captured: function(){ return buf; } }; } <|start_filename|>example/auction/server.js<|end_filename|> import {Router} from "./src/router" import ExpressAppAdapter from "../PPRouter/adapters/ExpressAdapter.js" import React from "react" var express = require('express'); var app = express(); var server = require('http').Server(app); var io = require('socket.io')(server); var cookieParser = require('cookie-parser'); var expressSession = require('express-session'); var myCookieParser = cookieParser('secret'); var RedisStore = require('connect-redis')(expressSession); var sessionStore = new RedisStore({ host: "localhost", port: 6379 }); app.use(myCookieParser); app.use(expressSession({ secret: 'secret', store: sessionStore })); var SessionSockets = require('session.socket.io') , sessionSockets = new SessionSockets(io, sessionStore, myCookieParser); var connectors = require('./connector/SessionSocketConnector') //serve static app.use(express.static("./")) //serve routes Router.use(ExpressAppAdapter(app, layout)); server.listen(process.env.PORT || 3000) console.log("check localhost:" + process.env.PORT || 3000); var PromisePipe = Router.PromisePipe; //setup server-client stream with session PromisePipe.stream('server','client').connector(connectors.SIOServerClientStream(sessionSockets)) function layout(html, renderData){ var stateString = JSON.stringify(renderData); var html = React.renderToString(html); return `<html> <head> <link rel="stylesheet" href="/css/bootstrap.min.css"> <link rel="stylesheet" href="/css/index.css"> <script src="/socket.io/socket.io.js"></script> </head> <body> <div class="container"> <div id="content">${html}</div> </div> <script type="text/javascript" src="/bundle.js"></script> <script type="text/javascript"> require('client')(${stateString}); </script> </body> </html>`; } <|start_filename|>example/webworker/worker.js<|end_filename|> var logic = require('./logic.js') var connectors = require('../connectors/WorkerDuplexStream.js') module.exports = function(self){ logic.pipe.setEnv('worker'); ENV = 'WORKER'; logic.pipe.stream('worker','client').connector(connectors.WorkerClientStream(self)) } <|start_filename|>package.json<|end_filename|> { "name": "promise-pipe", "version": "0.1.9", "description": "##install", "main": "src/PromisePipe.js", "scripts": { "test": "node node_modules/mocha/bin/mocha ./tests/**/*.spec.js", "standalone": "node node_modules/browserify/bin/cmd.js -s promisepipe -e src/PromisePipe.js -o ./promise-pipe.js" }, "repository": { "type": "git", "url": "git://github.com/edjafarov/PromisePipe.git" }, "author": "", "license": "ISC", "bugs": { "url": "https://github.com/edjafarov/PromisePipe/issues" }, "homepage": "https://github.com/edjafarov/PromisePipe", "dependencies": { "debug": "^2.2.0", "es6-promise": "~2.0.1", "json-stringify-safe": "^5.0.1", "stacktrace-js": "^0.6.4" }, "devDependencies": { "browserify": "^11.0.1", "chai": "^2.3.0", "es6-promise": "~2.0.1", "mocha": "~2.1.0", "sinon": "~1.12.2" } } <|start_filename|>example/simple/client.js<|end_filename|> var logic = require('./logic'); var PromisePipe = logic.PromisePipe; var socket = io.connect('http://localhost:3000'); var connectors = require('../connectors/SocketIODuplexStream') PromisePipe.stream('client','server').connector(connectors.SIOClientServerStream(socket)) //var connectors = require('../connectors/HTTPDuplexStream') //PromisePipe.stream('client','server').connector(connectors.HTTPClientServerStream()) module.exports = logic; <|start_filename|>src/linkProcessors/passLinksProcessor.js<|end_filename|> let Context = require('../Context'); const systemEnvs = ['both', 'inherit', 'cache']; module.exports = function passLinksProcessor(PromisePipe){ const processor = { name: 'passLinksProcessor', predicate: function isNextEnv(link, context) { return isLinkForOtherEnv(link, context) && shouldLinkBeSkipped(link, context); }, handler: function passLinksHandler(link, context, data, executingChain, chain, Pipe) { return executingChain.then(function (data) { return data; }) } }; return processor; } function isLinkForOtherEnv(link, context) { return link._env !== context._env; } function shouldLinkBeSkipped(link, context) { if (context._passChains && !!~context._passChains.indexOf(link._id)) return true; return false; } <|start_filename|>tests/cache.PromisePipe.spec.js<|end_filename|> var EventEmitter = require('events').EventEmitter; var sinon = require('sinon'); var Promise = require('es6-promise').Promise; var expect = require('chai').expect; describe('PromisePipe when comes to chains from other env', function(){ var PromisePipe = require('../src/PromisePipe')(); var PromisePipeServer = require('../src/PromisePipe')(); PromisePipeServer.setEnv('server'); var context = {}; var context1 = {}; var context2 = {}; var data1 = 1; var data2 = 2; var fn1 = sinon.stub(); var fn2 = sinon.stub(); var fn3 = sinon.stub(); var fn4 = sinon.stub(); var fn5 = sinon.stub(); fn1.withArgs(data1).returns(data2); fn2.withArgs(data2).returns(data1); fn3.withArgs(data1).returns(data2); fn4.withArgs(data2).returns(data1); fn5.withArgs(data1).returns(data2); var cache = {}; var cacher = function(data, context, result){ if(!cache['id:' + data]){ cache['id:' + data] = result; } else { return cache['id:' + data]; } } var serverSocketMock = new EventEmitter(); var clientSocketMock = new EventEmitter(); function sendToClient(message){ clientSocketMock.emit('message', JSON.stringify(message)); } function sendToServer(message){ serverSocketMock.emit('message', JSON.stringify(message)); } PromisePipe.envTransition('client', 'server', function(message){ sendToServer(message); }); clientSocketMock.on('message', function(message){ message = JSON.parse(message); PromisePipe.execTransitionMessage(message); }); serverSocketMock.on('message', function(message){ message = JSON.parse(message); PromisePipeServer.execTransitionMessage(message).then(function(data){ message.data = data; sendToClient(message); }); }); fn2._env = 'server'; fn3._env = 'server'; fn4._env = 'server'; var finish = sinon.spy(); var pipe = PromisePipe() .then(fn1) .cache(cacher) .then(fn2) .then(fn3) .then(fn4) .then(fn5); var pipeServer = PromisePipeServer() .then(fn1) .cache(cacher) .then(fn2) .then(fn3) .then(fn4) .then(fn5); describe("should work and cached, pass all chains", function(){ before(function(done){ pipe(data1, context2).then(finish); done() }) it('should not fail', function(){ sinon.assert.calledOnce(fn1); sinon.assert.calledOnce(fn2); sinon.assert.calledOnce(fn3); sinon.assert.calledOnce(fn4); sinon.assert.calledOnce(fn5); sinon.assert.calledOnce(finish); sinon.assert.calledWithExactly(finish, data2); }) describe("should work and cached, return server result from cache", function(){ before(function(done){ pipe(data1, context2).then(finish); done() }) it('should not fail', function(){ sinon.assert.calledTwice(fn1); sinon.assert.calledOnce(fn2); sinon.assert.calledOnce(fn3); sinon.assert.calledOnce(fn4); sinon.assert.calledTwice(fn5); sinon.assert.calledTwice(finish); sinon.assert.calledWithExactly(finish, data2); }) }) }) }) describe('PromisePipe when are server chains cached', function(){ var PromisePipe = require('../src/PromisePipe')(); var PromisePipeServer = require('../src/PromisePipe')(); PromisePipeServer.setEnv('server'); var context = {}; var context1 = {}; var context2 = {}; var data1 = 1; var data2 = 2; var fn1 = sinon.stub(); var fn2 = sinon.stub(); var fn3 = sinon.stub(); var fn3f = function(data, context){ return new Promise(function(resolve, reject){ setTimeout(function(){ resolve(fn3(data, context)) }, 50); }) } var fn4 = sinon.stub(); var fn5 = sinon.stub(); fn1.withArgs(data1).returns(data2); fn2.withArgs(data2).returns(data1); fn3.withArgs(data1).returns(data2); fn4.withArgs(data2).returns(data1); fn5.withArgs(data1).returns(data2); var cache = {}; var cacher = function(data, context, result){ if(!cache['id:' + data]){ cache['id:' + data] = result; } else { return cache['id:' + data]; } } var serverSocketMock = new EventEmitter(); var clientSocketMock = new EventEmitter(); function sendToClient(message){ clientSocketMock.emit('message', JSON.stringify(message)); } function sendToServer(message){ serverSocketMock.emit('message', JSON.stringify(message)); } PromisePipe.envTransition('client', 'server', function(message){ sendToServer(message); }); clientSocketMock.on('message', function(message){ message = JSON.parse(message); PromisePipe.execTransitionMessage(message); }); serverSocketMock.on('message', function(message){ message = JSON.parse(message); PromisePipeServer.execTransitionMessage(message).then(function(data){ message.data = data; sendToClient(message); }); }); fn2._env = 'server'; fn3f._env = 'server'; fn4._env = 'server'; var finish = sinon.spy(); var pipe = PromisePipe() .then(fn1) .cache(cacher) .then(fn2) .then(fn3f) .then(fn4) .then(fn5); var pipeServer = PromisePipeServer() .then(fn1) .cache(cacher) .then(fn2) .then(fn3f) .then(fn4) .then(fn5); describe("and run pipe twice in parralel", function(){ before(function(done){ pipe(data1, context2).then(finish); pipe(data1, context2).then(finish).then(function(){done()}); }) it('should pass server chains only once', function(){ sinon.assert.calledTwice(fn1); sinon.assert.calledOnce(fn2); sinon.assert.calledOnce(fn3); sinon.assert.calledOnce(fn4); sinon.assert.calledTwice(fn5); sinon.assert.calledTwice(finish); sinon.assert.calledWithExactly(finish, data2); }) }) }) <|start_filename|>example/simple-todo/server.js<|end_filename|> var main = require('./logic.js'); var express = require('express'); var app = express(); var server = require('http').Server(app); var io = require('socket.io')(server); server.listen(3000) var connectors = require('../connectors/SocketIODuplexStream'); console.log("check localhost:3000"); var PromisePipe = main.PromisePipe; app.use(express.static("./")) var todolist = [ { id: 0, name: "<NAME>", done: true }, { id: 1, name: "<NAME>", done: false } ] PromisePipe.stream('server','client', function(data, context, executor, end){ context.todolist = todolist; return executor(data, context).then(end); }).connector(connectors.SIOServerClientStream(io)) <|start_filename|>example/login/backend.js<|end_filename|> /* Мы используем фреймфорк express.js для реализации сервера */ var express = require('express') , app = express() , bodyParser = require('body-parser') , server = require('http').Server(app); /* Ожидается что промиспайпы получат уже распаршенные данные */ app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); /* Добавляем скрипт, общий для бекенда и фронтенда */ var pipe = require('./common.js') /* Подключаем скрипт HTTP коннектора промиспайпов */ , connectors = require('./node_modules/promise-pipe/example/connectors/HTTPDuplexStream') /* Получаем экземпляр промиспайпа, созданный в этом скрипте */ , PromisePipe = pipe.PromisePipe /* Указыаем какой транспорт используется при переходе с сервера на клиент */ PromisePipe.stream('server','client').connector(connectors.HTTPServerClientStream(app)); /* Раздача статики, что бы мы могли получить доступ к index.html */ app.use(express.static("./")); /* Запускаем сервер */ server.listen(3000); <|start_filename|>example/auction/src/PPconfig.js<|end_filename|> export default function(Router){ var PromisePipe = Router.PromisePipe; PromisePipe.use('map', function map(data, context, mapFunction){ if(!Array.isArray(data)) data = [data]; return data.map(mapFunction) }) PromisePipe.use('redirect', function map(data, context, url){ return Router.router.transitionTo(url, context); }) PromisePipe.use('emit', function map(data, context, evt){ return context.client.emit(evt, data); }) } <|start_filename|>example/auction/src/serverChains/chains.js<|end_filename|> var redis = require('redis'); var redisUrl = require('parse-redis-url')(redis); var options = redisUrl.parse(process.env.REDIS_URL); var client; var clientSub; function strongConnect(){ client = redis.createClient(options.port, options.host); clientSub = redis.createClient(options.port, options.host); client.on('error', function(err){ console.log("global redis error: " + err); strongConnect(); }); if(options.password){ client.auth(options.password, function(err){ console.log(err); }) clientSub.auth(options.password, function(err){ console.log(err); }) } if(!process.env.REDIS_URL){ client.select(options.database || 0, function(){}); clientSub.select(options.database || 0, function(){}); } } strongConnect() export var prepareTopIds = doOnServer((size = 5)=>doOnServer((data, context)=>{ return new Promise((resolve, reject)=>{ client.get('auction:items:index', (err, index)=>{ if(err) return reject(err); var result = Array.apply(null, {length: size}).map(Number.call, Number); //decremented array starting from last index by size return resolve(result.reduce((res)=>{ res.push(index--); return res; }, []).reverse()); }) }); })); export var getItemsByIds = doOnServer((data, context)=>{ if(!Array.isArray(data)) data = [data]; return data.reduce((sequence, id) =>{ return sequence.then((data)=>{ return new Promise((resolve, reject)=>{ client.hgetall('auction:items:' + id, (err, item)=>{ if(!item) item = {}; item.id = id; data.push(item) resolve(data); }); }) }); }, Promise.resolve([])); }); export var getUsersByIds = doOnServer((data, context)=>{ if(!Array.isArray(data)) data = [data]; return data.map((uid)=>{ return users.reduce((res, user)=>{ if(user.id == uid) return user; return res; }, null) }) }); export var addBidIds = doOnServer((data, context)=>{ return data.reduce((sequence, item) =>{ return sequence.then((arr)=>{ return new Promise((resolve, reject)=>{ client.get('auction:items:' + item.id + ':bids:index', (err, index)=>{ if(index){ var ids = Array.apply(null, {length: +index + 1}).map(Number.call, Number).slice(1).reverse(); //decremented array starting from last index by size return ids.reduce((bidSequence, bidId) => { return bidSequence.then((data)=>{ return new Promise((resolve, reject)=>{ client.hgetall('auction:items:' + item.id + ':bids:' + bidId, (err, bid)=>{ if(!bid) return resolve(data); bid.id = bidId; bid.user = users.reduce((res, user)=>{ if(user.id == bid.uid) return user; return res; }, null) data.push(bid) resolve(data); }) }) }) }, Promise.resolve([])) .then((bids)=>{ item.bids = bids; arr.push(item); resolve(arr); }) } item.bids = []; arr.push(item); resolve(arr); }); }) }); }, Promise.resolve([])); }); export var withCurrentUser = doOnServer(mock); export var makeABid = doOnServer((data, context)=>{ return new Promise((resolve, reject)=>{ client.incr('auction:items:' + data.id + ':bids:index', newBidId); function newBidId(err, id){ client.hmset('auction:items:' + data.id + ':bids:' + id, { bid: data.bid, uid: context.session.user.id }, bidSaved); } function bidSaved(){ resolve([data.id]) } }); }); export var broadcast = doOnServer((data, context)=>{ client.publish('item:update', JSON.stringify(data)); }); export var watch = doOnServer((data, context)=>{ var socket = context.socket; clientSub.subscribe('item:update'); clientSub.on("message", function(channel, data) { socket.emit(channel, JSON.parse(data)); }); }); export var verifyCredentials = doOnServer((data, context)=>{ return new Promise((resolve, reject)=>{ var result = users.reduce((res, user)=>{ if(data.login == user.login && data.pwd == user.password){ return user; } return res; }, null); if(!result) return reject("User or password is wrong"); resolve(result); }) }); export var putUserInSession = doOnServer((data, context)=>{ context.session.user = data; context.session.save(); return data; }); export var getCurrentUser = doOnServer((data, context)=>{ return context.session.user || {}; }); export var crearUserFromSession = doOnServer((data, context)=>{ delete context.session.user; context.session.save(); return {}; }); var users = [ { id:0, login: "user1", name: "Username1", password: "<PASSWORD>" }, { id:1, login: "user2", name: "Username2", password: "<PASSWORD>" } ] function doOnServer(fn){ fn._env = 'server'; return fn } function mock(data){ console.warn("SHOULD NOT BE HERE"); return data; } <|start_filename|>example/webworker/server.js<|end_filename|> var express = require('express'); var app = express(); var server = require('http').Server(app); var io = require('socket.io')(server); server.listen(3000) console.log("check localhost:3000"); app.use(function(req,res,next){ next(); }) app.use(express.static("./")) <|start_filename|>example/file-upload/logic.js<|end_filename|> var PromisePipe = require('../../src/PromisePipe')(); var Promise = require('es6-promise').Promise; PromisePipe.setMode('DEBUG'); var ENV = 'CLIENT'; //set up server if(typeof(window) !== 'object'){ PromisePipe.setEnv('server'); ENV = 'SERVER'; var fs = require('fs'); var path = require('path') } var doOnServer = PromisePipe.in('server') module.exports = { PromisePipe: PromisePipe, saveItem: PromisePipe() .then(getFormData) .then(doOnServer(saveFilesToFolder)) .then(buildImagesList) .then(render) } function getFormData(){ return { files: document.getElementById('files').files } } function saveFilesToFolder(data){ var filePromises = data.files.map(function(file){ return new Promise(function(resolve, reject){ var writer = fs.createWriteStream(file.name); file.stream.pipe(writer); writer.on('finish', resolve.bind(this, file.name)); writer.on('error', reject); }) }) return Promise.all(filePromises); } function buildImagesList(data){ var result = ""; data = data || []; result+="<ul>"; result+=data.map(function(name, i){ return "<li><img src='/"+name+"'/></li>"; }).join(''); result+="</ul>"; return result; } function render(data){ document.getElementById('app').innerHTML = data; return data; } <|start_filename|>tests/context.PromisePipe.spec.js<|end_filename|> var PromisePipe = require('../src/PromisePipe')(); PromisePipe.setMode('DEBUG'); var PromisePipeServer = require('../src/PromisePipe')(); PromisePipeServer.setMode('DEBUG'); var expect = require('chai').expect; PromisePipeServer.env = 'server'; var EventEmitter = require('events').EventEmitter; var sinon = require('sinon'); var Promise = require('es6-promise').Promise; var expect = require('chai').expect; describe('PromisePipe when comes to chains from other env', function(){ var context = {outerContext: true}; var context1 = {innerContext:true}; var data1 = 1; var fn1 = sinon.stub(); var fn2 = sinon.stub(); var fn3 = sinon.stub(); var fn4 = sinon.stub(); var fn5 = sinon.stub(); fn1.withArgs(data1).returns(data1); fn2.withArgs(data1).returns(data1); fn3.withArgs(data1).returns(data1); fn4.withArgs(data1).returns(data1); fn5.withArgs(data1).returns(data1); var serverSocketMock = new EventEmitter(); var clientSocketMock = new EventEmitter(); function sendToClient(message){ clientSocketMock.emit('message', JSON.stringify(message)); } function sendToServer(message){ serverSocketMock.emit('message', JSON.stringify(message)); } PromisePipe.envTransition('client', 'server', function(message){ sendToServer(message); }); clientSocketMock.on('message', function(message){ message = JSON.parse(message); PromisePipe.execTransitionMessage(message); }); serverSocketMock.on('message', function(message){ message = JSON.parse(message); PromisePipeServer.localContext(context1).execTransitionMessage(message).then(function(data){ message.data = data; sendToClient(message); }); }); fn2._env = 'server'; fn3._env = 'server'; fn4._env = 'server'; var finish = sinon.spy(); var pipe = PromisePipe() .then(fn1) .then(fn2) .then(fn3) .then(fn4) .then(fn5); var pipeServer = PromisePipeServer() .then(fn1) .then(fn2) .then(fn3) .then(fn4) .then(fn5); before(function(done){ pipe(data1, context).then(finish); done() }) it('the context1 should be isolated inside server', function(){ sinon.assert.calledOnce(fn1); expect(fn1.getCall(0).args[1]).to.have.property('outerContext', true); expect(fn1.getCall(0).args[1]).to.not.have.property('innerContext'); sinon.assert.calledOnce(fn2); expect(fn2.getCall(0).args[1]).to.have.property('outerContext', true); expect(fn2.getCall(0).args[1]).to.have.property('innerContext', true); sinon.assert.calledOnce(fn3); sinon.assert.calledOnce(fn4); expect(fn4.getCall(0).args[1]).to.have.property('outerContext', true); expect(fn4.getCall(0).args[1]).to.have.property('innerContext', true); sinon.assert.calledOnce(fn5); expect(fn5.getCall(0).args[1]).to.have.property('outerContext', true); expect(fn5.getCall(0).args[1]).to.not.have.property('innerContext'); sinon.assert.calledWithExactly(finish, data1); }) }) <|start_filename|>tests/api.PromisePipe.spec.js<|end_filename|> var sinon = require('sinon'); describe('PromisePipe when comes to chains from other env', function(){ var EventEmitter = require('events').EventEmitter; var messageBus = new EventEmitter(); var PromisePipeServer = require('../src/PromisePipe')(); var PromisePipeClient = require('../src/PromisePipe')(); var context = {}; var data1 = 1; var data2 = 2; var fn1 = sinon.stub(); var fn2 = sinon.stub(); var fn3 = sinon.stub(); var fn4 = sinon.stub(); var fn5 = sinon.stub(); var final1 = sinon.stub(); var final2 = sinon.stub(); fn1.withArgs(data1).returns(data2); fn2.withArgs(data2).returns(data1); fn3.withArgs(data1).returns(data2); fn4.withArgs(data2).returns(data1); fn5.withArgs(data1).returns(data2); PromisePipeServer({name: "MockName1"}).then(fn1) PromisePipeServer({name: "MockName2"}).then(fn4) var mockServerApi = { listen:function(handler){ messageBus.on('send-to-api', handler); },send:function(message){ messageBus.emit('send-back', message); } } var api = PromisePipeServer.api.provide(mockServerApi); var mockClientApi = { listen:function(handler){ messageBus.on('send-back', handler); }, send:function(message){ messageBus.emit('send-to-api', message); } } var PromieSRC = require('fs').readFileSync("node_modules/es6-promise/dist/es6-promise.js").toString(); var PromiseInject = "var PromiseObj = {};var module,define;(function(){\n" + PromieSRC + "}).bind(PromiseObj)();var Promise = PromiseObj.ES6Promise.Promise;\n" PromisePipeClient.use('remoteApi', new Function('connector', PromiseInject + "return " + api)()(mockClientApi)); var test1 = PromisePipeClient().remoteApi.MockName1().then(fn2) var test2 = PromisePipeClient().then(fn3).remoteApi.MockName2().then(fn5) before(function(done){ test1(data1).then(final1); test2(data1).then(final2); done() }) it('should pass first chain and call MockName1() from PromisePipeServer',function(){ sinon.assert.calledOnce(fn1); sinon.assert.calledOnce(fn2); sinon.assert.calledWithExactly(final1, data1); }) xit('should pass second chain and call MockName2() from PromisePipeServer',function(){ sinon.assert.calledOnce(fn3); sinon.assert.calledOnce(fn4); sinon.assert.calledOnce(fn5); sinon.assert.calledWithExactly(final2, data2); }) }) <|start_filename|>src/ID.js<|end_filename|> /* This should be pseudo random counter on purpose */ module.exports = function gedID() { let counter = 1234567890987; return function ID(){ counter++; return counter.toString(36).substr(-8); } } <|start_filename|>example/auction/src/components/LoginComp.js<|end_filename|> import React from "react" class LoginComp extends React.Component { constructor(props) { super(props); this.state = {login: '', pwd: '', err: ''}; if(this.props.context.client){ var client = this.props.context.client; client.on('login:fail', (err)=>{ this.setState({err:err}) }) } } handleLogin (newValue) { this.setState({login: newValue}); } handlePwd (newValue) { this.setState({pwd: newValue}); } handleSubmit (e){ e.preventDefault(); this.setState({err:''}) delete this.props.context._passChains this.props.context.login(this.state, this.props.context) } render() { var valueLinkLogin = { value: this.state.login, requestChange: this.handleLogin.bind(this) }; var valueLinkPwd = { value: this.state.pwd, requestChange: this.handlePwd.bind(this) }; var error; if(this.state.err){ error = <p className="alert alert-danger">{this.state.err}</p> } return <div> <h2 className="text-center">Login</h2> <form onSubmit={this.handleSubmit.bind(this)} className="col-md-4 col-md-offset-4"> {error} <div className="form-group"> <label for="exampleInputEmail1">Email address</label> <input type="text" className="form-control" placeholder="Login" valueLink={valueLinkLogin}/> </div> <div className="form-group"> <label for="exampleInputPassword1">Password</label> <input type="password" className="form-control" placeholder="Password" valueLink={valueLinkPwd}/> </div> <button type="submit" className="btn btn-default">Login</button> </form> </div> } } export default LoginComp <|start_filename|>example/connectors/HTTPDuplexStream.js<|end_filename|> module.exports = { HTTPClientServerStream: function Stream(fetchFn){ var fetchFn = fetchFn || fetch; var StreamHandler=null; return { send: function(message){ fetchFn("/promise-pipe-connector",{ method: 'post', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify(message) }).then(function(response){ return response.json(); }).then(function(message){ if(StreamHandler) return StreamHandler(message); return message; }); }, listen: function(handler){ StreamHandler = handler; } } }, //express app //highly experimental HTTPServerClientStream: function ServerClientStream(app){ var StreamHandler; app.use(function(req, res, next){ if(req.originalUrl == '/promise-pipe-connector' && req.method=='POST'){ var message = req.body; message._response = res; StreamHandler(message) } else { return next(); } }); return { send: function(message){ if(!message._response) throw Error("no response defined"); var res = message._response; message._response = undefined; res.json(message); }, listen: function(handler){ StreamHandler = handler; } } } } <|start_filename|>example/mongotodo-api/api.logic.js<|end_filename|> var PromisePipe = require('../../src/PromisePipe')(); PromisePipe.setMode('DEBUG'); var Promise = require('es6-promise').Promise; var MongoPipeApi = require('mongo-pipe-api'); var mongodbUrl = 'localhost:27017/test'; //set up server PromisePipe.setEnv('server'); ENV = 'SERVER'; mongodbUrl = process.env.MONGOHQ_URL || mongodbUrl; PromisePipe.use('db', MongoPipeApi(mongodbUrl, ['items']), {_env:"server"}); PromisePipe.use('log', function(data, context){ console.log(data) return data; }); var forUser = function forUser(data, context){ data = data || {}; data.uid = context.session.id; return data; } var byId = function byId(data, context){ return { _id: MongoPipeApi.ObjectId(data) }; }; var ensureItem = function(data){ if(typeof(data) == 'object' && data.name) return Promise.resolve(data); return Promise.reject({data:data, message: "data is not promer object"}); } var ensureId = function(data){ if(typeof(data) == 'string' && data.length > 0) return Promise.resolve(data); return Promise.reject({data:data, message: "data is not proper string ID"}); } var toggleModifyItem = function toggleModifyItem(data, context){ return { query:{ uid: context.session.id, _id:data[0]._id }, update:{ $set: { done: !data[0].done } } }; }; var toggleAllItems = function toggleAllItem(data, context){ return [ { uid: data.uid }, { $set: { done: data.done } }, { multi: true } ] }; var byDoneTrue = function byDoneTrue(data, context){ data.done = true; return data; }; module.exports = { PromisePipe: PromisePipe, addItem: PromisePipe({name: 'addItem'}) .then(ensureItem) .then(forUser) .db.insert.items(), getItems: PromisePipe({name: 'getItems'}) .then(forUser) .db.find.items(), removeItem: PromisePipe({name: 'removeItem'}) .then(ensureId) .then(byId) .then(forUser) .db.remove.items(), doneItem: PromisePipe({name: 'doneItem'}) .then(ensureId) .then(byId) .then(forUser) .db.findOne.items() .then(toggleModifyItem) .db.findAndModify.items(), doneAllItems: PromisePipe({name: 'doneAllItems'}) .then(forUser) .then(toggleAllItems) .db.update.items(), clearDoneItems: PromisePipe({name: 'clearDoneItems'}) .then(forUser) .then(byDoneTrue) .log() .db.remove.items() } <|start_filename|>example/auction/css/index.css<|end_filename|> img{ width: 100%; } .auction-list li{ margin-bottom: 20px; } .auction-list h3{ margin-top: 0; } .auction-list .bid, .currentBid{ font-size: 2.5em; color: #888; } <|start_filename|>example/auction/src/client.js<|end_filename|> import React from "react" import {Router} from "./router" var connectors = require('../connector/SessionSocketConnector') import HistoryApiAdapter from "../../PPRouter/adapters/HistoryApiAdapter" var EventEmitter = require('events').EventEmitter; var MeStore = require('./stores/MeStore'); var ItemStore = require('./stores/ItemStore'); var ItemsStore = require('./stores/ItemsStore'); var PromisePipe = Router.PromisePipe; PromisePipe.setMode("DEBUG"); PromisePipe.setEnv('client'); var socket = io.connect(document.location.origin); PromisePipe.stream('client','server').connector(connectors.SIOClientServerStream(socket)) function mount(data){ React.render(data, document.getElementById('content')); } var FrontendAdapter = HistoryApiAdapter(mount, document.getElementById('content')); Router.use(FrontendAdapter); var context = {client: new EventEmitter}; context.client.MeStore = MeStore.create(); context.client.MeStore.init(context.client) context.client.ItemStore = ItemStore.create(); context.client.ItemStore.init(context.client) context.client.ItemsStore = ItemsStore.create(); context.client.ItemsStore.init(context.client) socket.on('item:update', (data)=>{ context.client.emit('item:update', data[0]); }) context.login = Router.actions.login; context.logout = Router.actions.logout; context.makeABid = Router.actions.makeABid; Router.actions.getSession(null, context); Router.actions.watch(null, context); document.getElementById('content').onclick = function(e){ var a = e.target.href?e.target:upTo(e.target, "a"); if(a && a.nodeType == 1 && a.href && a.href.indexOf(document.location.origin) == 0) {//is a link e.preventDefault() e.stopPropagation(); if(document.location.pathname !== a.pathname) Router.router.transitionTo(a.pathname, context) } } // Find first ancestor of el with tagName // or undefined if not found function upTo(el, tagName) { tagName = tagName.toLowerCase(); while (el && el.parentNode) { el = el.parentNode; if (el.tagName && el.tagName.toLowerCase() == tagName) { return el; } } // Many DOM methods return null if they don't // find the element they are searching for // It would be OK to omit the following and just // return undefined return null; } module.exports = function(state){ mount(FrontendAdapter.renderer(Router.prepareRenderData(state, context))); } <|start_filename|>example/login/common.js<|end_filename|> "use strict"; /* Создаем переменую с промиспайпом и промисом */ var PromisePipe = require('promise-pipe')() /* Подключаем промисы es6 */ , Promise = require('es6-promise').Promise; /* Если в глобальном пространстве имен нет window, то будем считать, что все происходит на сервере. */ if(typeof(window) !== 'object'){ PromisePipe.setEnv('server'); } /* Часть промиспайпа, которая будет выполняться только на сервере */ function serverSide(fn){ fn._env = 'server'; return fn } /* Часть промиспайпа, которая будет выполняться только на клиенте.*/ /* Так как по умолчанию все происходит на клиенте, то эту функцию */ /* можно спокойно убрать, но мне кажется с ней — нагляднее. */ function clientSide(fn){ fn._env = 'client'; return fn } /* Логика */ /* Получив данные на сервере мы проверяем логин и пароль */ /* и выводим пользователю сообщение о результате. */ module.exports = PromisePipe() .then(serverSide(validateData)) .then(clientSide(success)) .catch(clientSide(fail)); module.exports.PromisePipe = PromisePipe; /* Проверка данных */ function validateData(data){ /* Создаем промис */ return new Promise(function(resolve, reject){ if( (data.password == "<PASSWORD>") &&(data.login == "Carmak") ){ /* Все верно, пользователь авторизирован */ resolve(data); }else{ /* Ошибка при вводе данных */ reject(new Error('Ошибка при вводе логина или пароля')); } }); } /* В случае успешной авторизации показываем сообщение */ function success(){ document.querySelector('.message_success').style.display = "block"; document.querySelector('.message_fail').style.display = "none"; } /* В случае провала авторизации показываем сообщение */ function fail(){ document.querySelector('.message_success').style.display = "none"; document.querySelector('.message_fail').style.display = "block"; } <|start_filename|>example/auction/src/router.js<|end_filename|> import RouterFactory from "../../PPRouter/index" import React from "react" import RootComp from "./components/RootComp" import ItemComp from "./components/ItemComp" import UserComp from "./components/UserComp" import LoginComp from "./components/LoginComp" var chain = require('./serverChains/chains'); var Router = RouterFactory(); //Router.PromisePipe.setMode('DEBUG'); if(typeof(window) !== 'object'){ Router.PromisePipe.setEnv('server'); } else { Router.PromisePipe.setEnv('client'); } require('./PPconfig')(Router); Router.actions = require('./actions')(Router.PromisePipe); Router(function(Router){ Router('/item/:id').component(Comp(ItemComp)) .then((data, context)=>[context.params.id]) .then(chain.getItemsByIds) .then(chain.addBidIds) Router('/login').component(Comp(LoginComp)) Router('/users/:id').component(Comp(UserComp)) .then((data, context)=>[context.params.id]) .then(chain.getUsersByIds) }).component(Comp(RootComp)) .then(chain.prepareTopIds()) .then(chain.getItemsByIds) .then(chain.addBidIds) //React createElement helper function Comp(classComponent){ return React.createElement.bind(React, classComponent) } export var Router = Router; <|start_filename|>example/auction/src/components/ItemComp.js<|end_filename|> import React from "react" class ItemComp extends React.Component { constructor(props) { super(props); var nextBid = this.props.data[0].bids[0]?this.props.data[0].bids[0].bid:this.props.data[0].startBid; nextBid = nextBid || 0 this.state = { me: {}, bid: +nextBid+10, item: props.data && props.data[0] }; if(this.props.context.client){ var client = this.props.context.client; this.state.me = client.MeStore.get() client.MeStore.on('change', (user)=>{ this.setState({me:user}); }) client.ItemStore.on('change', this.updateItem.bind(this )) } } componentWillUnmount (){ if(this.props.context.client){ var client = this.props.context.client; client.ItemStore.removeAllListeners('change') } } updateItem (item){ this.setState({item:item, bid: +item.bids[0].bid+10}); } makeABid(e){ e.preventDefault(); this.props.context.makeABid({ bid: this.state.bid, id: this.state.item.id }); } handleBid (newValue) { this.setState({bid: newValue}); } render() { var valueLinkBid = { value: this.state.bid, requestChange: this.handleBid.bind(this) }; var bids = this.state.item.bids || []; console.log(this.state) return <div className="row"> <div className="col-md-4"> <img src={"/images/" + this.state.item.img}/> </div> <div className="col-md-5"> <h2>{this.state.item.name}<small>start bid: {this.state.item.startBid||0}</small></h2> <p>{this.state.item.description}</p> </div> <div className="col-md-3"> <label className="currentBid">Bid: {this.state.item.bids[0]?this.state.item.bids[0].bid:this.state.item.startBid}&euro;</label> <form onSubmit={this.makeABid.bind(this)} className="form-inline"> <div class="form-group"><input type="bid" valueLink={valueLinkBid} className="form-control"/></div><br/> <input type="submit" value="Make A Bid" className="btn btn-primary" disabled={!this.state.me.login || (this.state.item.bids[0] && this.state.me.id == +this.state.item.bids[0].uid)}/> </form> <div>Bidders:</div> <ul className="list-unstyled"> {bids.map((bid)=><li><label><a href={"/users/" + bid.user.id}>{bid.user.name}</a></label>({bid.bid}&euro;)</li>)} </ul> </div> </div> } } export default ItemComp <|start_filename|>src/RemoteAPIHandlers.js<|end_filename|> module.exports = function(PromisePipe){ return { provide: function(connector, apiName){ connector.listen(function(message){ function end(data){ message.data = data; connector.send(message); } PromisePipe.pipes[message.id].Pipe(message.data, message.context || {}).catch(unhandledCatch).then(end); //catch inside env function unhandledCatch(data){ message.unhandledFail = data; return data; } }) return generateClientAPI(apiName, PromisePipe); } } } var TransactionController = require('./TransactionController'); function generateClientAPI(apiName, PromisePipe){ var result = [ TransactionController.toString(), "var TransactionHandler = TransactionController();\n", "connector.listen(TransactionHandler.processTransaction);\n", handleRejectAfterTransition.toString(), apiCall.toString() ].join("\n") var theApiHash = Object.keys(PromisePipe.pipes).map(function(item){ return PromisePipe.pipes[item]; }).reduce(oneChain, []); result += "\nreturn {"+theApiHash.join(",\n")+"}\n"; return "function " + (apiName||'initApi') + "(connector){\n"+result+"}" } function apiCall(id){ return function(data, context){ var message = { data: data, id: id } return TransactionHandler.createTransaction(message).send(connector.send).then(handleRejectAfterTransition); } } function handleRejectAfterTransition(message){ return new Promise(function(resolve, reject){ if(message.unhandledFail) return reject(message.data); resolve(message.data); }) } function oneChain(result, item){ result.push(item.name + ": apiCall('" + item.id + "')"); return result; } /** //EXPOSING PP({name: 'getItems', description: 'Get Items from collection'}).then().then(); PP({name: 'saveItems', description: 'Save Items from collection'}).then().then(); PP.api.provide(connector); //USAGE <script src="http://api.url.com/v0.1"></script>.... or var mySerivceApi = PP.api.get(apiPath); PP.use('api', mySerivceApi); PP().api.getItems().then(); PP().api.saveItems().then(); */ <|start_filename|>tests/PromisePipe.spec.js<|end_filename|> var PromisePipe = require('../src/PromisePipe')(); var sinon = require('sinon'); //var Promise = require('es6-promise').Promise; var expect = require('chai').expect; describe('PromisePipe with 3 functions when called', function(){ var context = {}; var data1 = 1; var data2 = 2; var data3 = 3; var fn1 = sinon.stub(); var fn2 = sinon.stub(); var fn3 = sinon.stub(); var finish = sinon.spy(); var finish1 = sinon.spy(); //if runninng with data1 fn1.withArgs(data1, context).returns(data2); fn2.withArgs(data2, context).returns(data3); fn3.withArgs(data3, context).returns(data1); //if runninng with data2 fn1.withArgs(data2, context).returns(data3); fn2.withArgs(data3, context).returns(data1); fn3.withArgs(data1, context).returns(data2); var pipe = PromisePipe() .then(fn1) .then(fn2) .then(fn3); before(function(done){ pipe(data1, context).then(finish); done() }) it('should pass first function', function(){ sinon.assert.calledOnce(fn1); sinon.assert.calledWithExactly(fn1, data1, context); }); it('should pass second function', function(){ sinon.assert.calledOnce(fn2); sinon.assert.calledWithExactly(fn2, data2, context); }) it('should pass third function', function(){ sinon.assert.calledOnce(fn3); sinon.assert.calledWithExactly(fn3, data3, context); }); it('should end with final function', function(){ sinon.assert.calledOnce(finish); sinon.assert.calledWithExactly(finish, data1); }); describe('the pipe it should be reusable, when calling it again', function(){ before(function(done){ pipe(data2, context).then(finish1); done() }) it('should pass a chain once again and all functions called again', function(){ sinon.assert.calledTwice(fn1); sinon.assert.calledTwice(fn2); sinon.assert.calledTwice(fn3); sinon.assert.calledWithExactly(fn1, data2, context); sinon.assert.calledWithExactly(fn2, data3, context); sinon.assert.calledWithExactly(fn3, data1, context); }) it('should pass its own finish1 function', function(){ sinon.assert.calledOnce(finish); sinon.assert.calledOnce(finish1); sinon.assert.calledWithExactly(finish1, data2); }) }) }); describe('PromisePipe simple error handling', function(){ var context = {}; var data1 = 1; var data2 = 2; var data3 = 3; var fn1 = sinon.stub(); var fn2 = sinon.stub(); var fn3 = sinon.stub(); var finish = sinon.spy(); //if runninng with data1 fn1.withArgs(data1, context).returns(data2); fn2.withArgs(data2, context).returns(data3); fn3.withArgs(data3, context).returns(data1); var pipe = PromisePipe() .then(function(data, context){ return new Promise(function(resolve, reject){ process.nextTick(function(){ reject(fn1(data, context)); }); }) }) .then(function(data, context){ return new Promise(function(resolve, reject){ process.nextTick(function(){ resolve(fn2(data, context)); }); }) }) .catch(fn3); before(function(done){ pipe(data1, context).then(finish); done() }) it('should not call fn2 after fn1 rejected', function(){ sinon.assert.notCalled(fn2); }) it('should go fn1, rejected and get to fn3 rightaway to handle error with catch', function(){ sinon.assert.calledOnce(fn1); sinon.assert.calledWithExactly(fn1, data1, context); sinon.assert.calledOnce(fn3); sinon.assert.calledWithExactly(fn3, data2, context); sinon.assert.calledOnce(finish); sinon.assert.calledWithExactly(finish, undefined); }); }); describe('PromisePipe with 3 functions if running async', function(){ var context = {}; var data1 = 1; var data2 = 2; var data3 = 3; var fn1 = sinon.stub(); var fn2 = sinon.stub(); var fn3 = sinon.stub(); var finish = sinon.spy(); var finish1 = sinon.spy(); //if runninng with data1 fn1.withArgs(data1, context).returns(data2); fn2.withArgs(data2, context).returns(data3); fn3.withArgs(data3, context).returns(data1); //if runninng with data2 fn1.withArgs(data2, context).returns(data3); fn2.withArgs(data3, context).returns(data1); fn3.withArgs(data1, context).returns(data2); var pipe = PromisePipe() .then(function(data, context){ return new Promise(function(resolve, reject){ process.nextTick(function(){ resolve(fn1(data, context)); }); }) }) .then(function(data, context){ return new Promise(function(resolve, reject){ process.nextTick(function(){ resolve(fn2(data, context)); }); }) }) .then(function(data, context){ return new Promise(function(resolve, reject){ process.nextTick(function(){ resolve(fn3(data, context)); }); }) }); before(function(done){ pipe(data1, context).then(finish); done() }) it('should pass a chain of items once', function(){ sinon.assert.calledOnce(fn1); sinon.assert.calledWithExactly(fn1, data1, context); sinon.assert.calledOnce(fn2); sinon.assert.calledWithExactly(fn2, data2, context); sinon.assert.calledOnce(fn3); sinon.assert.calledWithExactly(fn3, data3, context); sinon.assert.calledOnce(finish); sinon.assert.calledWithExactly(finish, data1); }); }); describe('PromisePipe', function(){ var pipe = PromisePipe(); var pipe1 = PromisePipe(); var pipe2; var context = {}; var data1 = 1; var data2 = 2; var data3 = 3; var data4 = 4; var data5 = 5; var fn1 = sinon.stub(); var fn2 = sinon.stub(); var finish = sinon.spy(); fn1.withArgs(data1, context).returns(data2); fn2.withArgs(data2, context).returns(data3); it('should return a promise', function(){ expect(pipe()).to.be.an.instanceof(Promise); }) describe('can be joined with other pipe', function(){ before(function(){ pipe.then(fn1) pipe1.then(fn2) pipe2 = pipe.join(pipe1); pipe2(data1, context).then(finish); }) it('should pass all functions', function(){ sinon.assert.calledOnce(fn1); sinon.assert.calledWithExactly(fn1, data1, context); sinon.assert.calledOnce(fn2); sinon.assert.calledWithExactly(fn2, data2, context); }) }) describe('can be extended with methods', function(){ var fn1 = sinon.stub(); var fn2 = sinon.stub(); var finish = sinon.spy(); var fn3 = sinon.stub(); fn1.withArgs(data1, context).returns(data2); fn2.withArgs(data2, context).returns(data3); fn3.withArgs(data2, context, data4).returns(data3); PromisePipe.use('mockMethod', fn3); var customPipe = PromisePipe() .then(fn1) .mockMethod(data4) .then(fn2) before(function(){ customPipe(data1, context).then(finish); }) it('should pass functions', function(){ sinon.assert.calledOnce(fn1); sinon.assert.calledWithExactly(fn1, data1, context); sinon.assert.calledOnce(fn3); sinon.assert.calledWithExactly(fn3, data2, context, data4); sinon.assert.calledOnce(fn2); sinon.assert.calledWithExactly(fn2, data3, context); }) }) describe('can be extended with hash of methods', function(){ var fn1 = sinon.stub(); var fn2 = sinon.stub(); var finish = sinon.spy(); var fn3 = sinon.stub(); var inner1 = sinon.stub(); var inner2 = sinon.stub(); var inner3 = sinon.stub(); fn1.withArgs(data1, context).returns(data2); fn2.withArgs(data2, context).returns(data3); inner1.withArgs(data2, context, data4).returns(data2); inner2.withArgs(data2, context, data5).returns(data2); inner3.withArgs(data2, context, data1).returns(data2); PromisePipe.use('withMethod', { method1: inner1, method2: inner2, method3: { innerMethod1: inner3 } }); var customPipe1 = PromisePipe() .then(fn1) .withMethod.method1(data4) .then(fn2) var customPipe2 = PromisePipe() .then(fn1) .withMethod.method2(data5) .then(fn2) var customPipe3 = PromisePipe() .then(fn1) .withMethod.method3.innerMethod1(data1) .then(fn2) before(function(){ customPipe1(data1, context).then(finish); customPipe2(data1, context).then(finish); customPipe3(data1, context).then(finish); }) it('should pass functions', function(){ sinon.assert.calledThrice(fn1); sinon.assert.calledWithExactly(fn1, data1, context); sinon.assert.calledOnce(inner1); sinon.assert.calledWithExactly(inner1, data2, context, data4); sinon.assert.calledOnce(inner2); sinon.assert.calledWithExactly(inner2, data2, context, data5); sinon.assert.calledOnce(inner3); sinon.assert.calledWithExactly(inner3, data2, context, data1); sinon.assert.calledThrice(fn2); sinon.assert.calledWithExactly(fn2, data2, context); }) }) }) describe('PromisePipe composition 2 functions, and 2nd will be separate PromisPipe', function(){ var context = {}; var data1 = 1; var data2 = 2; var data3 = 3; var fn1 = sinon.stub(); var fn2 = sinon.stub(); var fn3 = sinon.stub(); var finish = sinon.spy(); var finish1 = sinon.spy(); //if runninng with data1 fn1.withArgs(data1, context).returns(data2); fn2.withArgs(data2, context).returns(data3); fn3.withArgs(data3, context).returns(data1); //if runninng with data2 fn1.withArgs(data2, context).returns(data3); fn2.withArgs(data3, context).returns(data1); fn3.withArgs(data1, context).returns(data2); var innerPipe = PromisePipe() .then(fn2) var pipe = PromisePipe() .then(fn1) .then(innerPipe) .then(fn3); before(function(done){ pipe(data1, context).then(finish); done() }) it('should pass a chain of items once', function(){ sinon.assert.calledOnce(fn1); sinon.assert.calledWithExactly(fn1, data1, context); sinon.assert.calledOnce(fn2); sinon.assert.calledWithExactly(fn2, data2, context); sinon.assert.calledOnce(fn3); sinon.assert.calledWithExactly(fn3, data3, context); sinon.assert.calledOnce(finish); sinon.assert.calledWithExactly(finish, data1); }); describe('the pipe it should be reusable, when calling it again', function(){ before(function(done){ pipe(data2, context).then(finish1); done() }) it('should pass a chain once again and all functions called again', function(){ sinon.assert.calledTwice(fn1); sinon.assert.calledTwice(fn2); sinon.assert.calledTwice(fn3); sinon.assert.calledOnce(finish); sinon.assert.calledOnce(finish1); sinon.assert.calledWithExactly(fn1, data2, context); sinon.assert.calledWithExactly(fn2, data3, context); sinon.assert.calledWithExactly(fn3, data1, context); sinon.assert.calledWithExactly(finish1, data2); }) }) }); <|start_filename|>example/login/frontend.js<|end_filename|> (function () { "use strict"; /* Подключаем скрипт общий для бекенда и фронтенда */ var pipe = require('./common.js') /* Получаем экземпляр промиспайпа, созданный в этом скрипте */ , PromisePipe = pipe.PromisePipe /* Подключаем скрипт коннектора промиспайпов */ , connectors = require('./node_modules/promise-pipe/example/connectors/HTTPDuplexStream'); /* Указыаем какой транспорт используется */ PromisePipe.stream('client','server').connector(connectors.HTTPClientServerStream()); /* Получаем из DOM форум авторизации */ var form = document.querySelector('.login-form'); /* Перехватываем отправку формы */ form.addEventListener('submit', function (event) { /* Блокируем отправку формы */ event.preventDefault(); /* Получаем данные из формы */ var data = { login: document.querySelector('input[name="login"]').value.trim() , password: document.querySelector('input[name="password"]').value.trim() } /* Очищаем форму */ form.reset(); /* Передаем их в промиспайп */ pipe(data); }); })() <|start_filename|>src/run.js<|end_filename|> var PromisePipeFactory = require('./PromisePipe'); var PromisePipe = PromisePipeFactory(); PromisePipe.use('log', {a:function(data, context, variable){ console.log("LOG: ",context[variable]); return data; }}) var test = PromisePipe().then((data, c)=>{ console.log(data++) c.t=1; return data; }).log.a("t") .then((data, c)=>{ console.log(data++) f.x=2; return data; }).catch(function(e){ console.log(e,"<<<") }) var k ={}; //console.log(test) test(2, k).then((data) => { console.log(data, k, "<<") return data; }).catch((e) => { console.log(e,"!") }) PromisePipe().then().then().channel((data, context)=>{ this.emit() }, (data, context)=>{ this.on() }); //get prev, get This //serverN, client client send listen ser1 send listen ser2 send listen client-server ser1-ser2 client.send => ser1.listen => ser1.send => ser2.listen {channelOpen} => ser2.send => ser1.listen => ser1.send => client.listen ser2.send => ser1.listen => ser2.send => client.listen <|start_filename|>src/chainRunner.js<|end_filename|> let debug = require('debug')('PP:runner'), loggingCreator = require('./logging.js'); module.exports = function chainRunner(PromisePipe, options) { const systemLinksProcessors = [ require('./linkProcessors/cacheProcessor')(PromisePipe), require('./linkProcessors/catchProcessor')(PromisePipe), require('./linkProcessors/bothProcessor')(PromisePipe), require('./linkProcessors/passLinksProcessor')(PromisePipe), require('./linkProcessors/nextEnvProcessor')(PromisePipe) ]; const logging = loggingCreator(options); return { executeChain(chain, Pipe, data, context) { return chain.reduce((executingChain, link, idx) => { const processedLink = systemLinksProcessors.reduce(function processLink(result, linkProcessor, idx) { if (result) return result; if (linkProcessor.predicate(link, context)) { debug(`link ${link._id} will be handled by ${linkProcessor.name}`) return linkProcessor.handler(link, context, data, executingChain, chain, Pipe).catch(logging.enhance(link)); } return result; }, false); !processedLink && debug(`link ${link._id} is chained in ${PromisePipe.env}`) return processedLink || executingChain.then(link._handler).then(logInBetween).catch(logging.enhance(link)); }, Promise.resolve(data)); } } } function logInBetween(data){ debug(`data - `, data); return data; } <|start_filename|>tests/timeout.PromisePipe.spec.js<|end_filename|> var sinon = require('sinon'); var Promise = require('es6-promise').Promise; var expect = require('chai').expect; describe('PromisePipe when comes to chains from other env', function(){ var PromisePipe = require('../src/PromisePipe')({timeout: 30}); var PromisePipeServer = require('../src/PromisePipe')({timeout: 30}); PromisePipeServer.setEnv('server'); var context = {}; var data1 = 1; var data2 = 2; var fn1 = sinon.stub(); // var fn2 = sinon.stub(); var fn3 = sinon.stub(); var fn4 = sinon.stub(); var handler = sinon.stub(); var fn2 = function(data){ return new Promise(function(resolve, reject){ setTimeout(resolve, 60); }) } fn2._env = 'server'; fn3._env = 'server'; var finish = sinon.spy(); fn1.withArgs(data1, context).returns(data1); //fn2.withArgs(data1).returns(data2); fn3.withArgs(data2).returns(data2); fn4.withArgs(data1, context).returns(data1); fn4.withArgs(data2, context).returns(data2); var pipe = PromisePipe() .then(fn1) .then(fn2) .then(fn3) .then(fn4) .catch(handler); var pipeServer = PromisePipeServer() .then(fn1) .then(fn2) .then(fn3) .then(fn4) .catch(handler); describe('if the message taking more than timeout', function(){ before(function(done){ PromisePipe.envTransition('client', 'server', function(message){ var innerMsg = JSON.parse(JSON.stringify(message)); PromisePipeServer.execTransitionMessage(innerMsg).then(function(data){ var ininnerMsg = JSON.parse(JSON.stringify(innerMsg)); ininnerMsg.data = data; PromisePipe.execTransitionMessage(ininnerMsg); }); }); pipe(data1, context).then(function(){done()}); }); it('the error is thrown that message was timeouted', function(){ sinon.assert.calledOnce(fn1); sinon.assert.calledOnce(handler); expect(handler.lastCall.args[0]).to.equal('message took more than 30') }); }); }); <|start_filename|>example/mongotodo/logic.js<|end_filename|> var PromisePipe = require('../../src/PromisePipe')(); PromisePipe.setMode('DEBUG'); var Promise = require('es6-promise').Promise; var MongoPipeApi = require('mongo-pipe-api'); var mongodbUrl = 'localhost:27017/test'; var ENV = 'CLIENT'; //set up server if(typeof(window) !== 'object'){ PromisePipe.setEnv('server'); ENV = 'SERVER'; mongodbUrl = process.env.MONGOHQ_URL || mongodbUrl; } PromisePipe.use('db', MongoPipeApi(mongodbUrl, ['items']), {_env:"server"}); var prepareItem = doOnServer(function addItem(data, context){ var item = { uid: context.session.id, name: data, done: false } return item; }) var forMe = doOnServer(function forMe(data, context){ return { uid: context.session.id }; }); var toggleModifyItem = doOnServer(function toggleModifyItem(data, context){ return { query:{ uid: context.session.id, _id:data[0]._id }, update:{ $set: { done: !data[0].done } } }; }); var toggleAllItem = doOnServer(function toggleAllItem(data, context){ return [ { uid: context.session.id }, { $set: { done: data } }, { multi: true } ] }); var byId = doOnServer(function byId(data, context){ return { uid: context.session.id, _id: MongoPipeApi.ObjectId(data) }; }); var byDoneTrue = doOnServer(function byDoneTrue(data, context){ return { uid: context.session.id, done: true }; }); module.exports = { PromisePipe: PromisePipe, addItem: PromisePipe() .then(prepareItem) .db.insert.items() .then(forMe) .db.find.items() .then(buildHtml) .then(renderItems), removeItem: PromisePipe() .then(byId) .db.remove.items() .then(forMe) .db.find.items() .then(buildHtml) .then(renderItems), getItems: PromisePipe() .then(forMe) .db.find.items() .then(buildHtml) .then(renderItems), doneItem: PromisePipe() .then(byId) .db.findOne.items() .then(toggleModifyItem) .db.findAndModify.items() .then(forMe) .db.find.items() .then(buildHtml) .then(renderItems), doneAllItem: PromisePipe() .then(toggleAllItem) .db.update.items() .then(forMe) .db.find.items() .then(buildHtml) .then(renderItems), clearDoneItems: PromisePipe() .then(byDoneTrue) .db.remove.items() .then(forMe) .db.find.items() .then(buildHtml) .then(renderItems) } function buildHtml(data){ data = data || []; result = renderTodoApp(renderAppHeader() + renderAppMain("<ul id='todo-list'>" + data.map(function(item, i){ var result = '<input class="toggle" type="checkbox" ' +(item.done?'checked':'')+ ' onclick="main.doneItem(\''+item._id+'\')"></input>'; result+= "<label>" + item.name + "</label>"; result+='<button class="destroy" onclick="main.removeItem(\''+item._id+'\')"></button>'; result = '<div class="view">'+result+'</div>' result = '<li class="'+(item.done?'completed':'')+'">'+result+'</li>' return result; }).join('') + "</ul>" , data) + renderAppFooter(data)) + renderAppInfo(); return result; } function renderItems(data){ document.getElementById('todo-app').innerHTML = data; return data; } function renderAppHeader(){ return '<header id="header"><h1>todos</h1><input id="new-todo" placeholder="What needs to be done?" autofocus onkeyup="event.which == 13 && main.addItem(this.value);"></header>'; } function renderAppMain(wrap, items){ var allChecked = items.reduce(function(result, item){ if(!item.done) return false; return result; }, true); return '<section id="main"><input id="toggle-all" '+(allChecked?'checked':'')+' type="checkbox" onclick="main.doneAllItem(this.checked)"><label for="toggle-all">Mark all as complete</label>' + wrap + '</section>'; } function renderAppFooter(data){ return '<footer id="footer"><span id="todo-count">' +(data?data.length:0)+ ' items</span><button id="clear-completed" onclick="main.clearDoneItems()">Clear completed</button></footer>'; } function renderTodoApp(wrap){ return '<section id="todoapp">' + wrap + '</section>'; } function renderAppInfo(){ return '<div id="info"><p>Written by <a href="https://github.com/edjafarov"><NAME></a></p><p><a href="https://github.com/edjafarov/PromisePipe/tree/master/example/mongotodo">PromisePipe based MongoDb persistent TodoApp</a> is a part of <a href="http://todomvc.com">TodoMVC</a></p></div>' } function doOnServer(fn){ fn._env = 'server'; return fn } <|start_filename|>example/auction/src/serverChains/chains-mocks.js<|end_filename|> function mock(data){ console.warn("SHOULD NOT BE HERE"); return data; } mock._env = 'server'; console.log("MOOK"); export var prepareTopIds = function(){ return mock; }; prepareTopIds._env = 'server'; export var getItemsByIds = mock; export var addBidIds = mock; export var resolveBids = mock; export var withCurrentUser = mock; export var makeABid = mock; export var watch = mock; export var broadcast = mock; export var verifyCredentials = mock; export var getCurrentUser = mock; export var getUsersByIds = mock; export var putUserInSession = mock; export var crearUserFromSession = mock; <|start_filename|>example/login/package.json<|end_filename|> { "name": "promisepipe_example", "version": "1.0.0", "description": "Пример использования ПромисПайпов. Авторизация пользователя.", "main": "backend.js", "dependencies": { "body-parser": "^1.13.2", "browserify": "^11.0.0", "es6-promise": "^2.3.0", "express": "^4.13.1", "promise-pipe": "^0.1.5" }, "devDependencies": {}, "scripts": { "start": "node node_modules/browserify/bin/cmd.js -r ./frontend.js -o bundle.js;node backend.js" }, "author": "SilentImp <<EMAIL>>", "license": "ISC" } <|start_filename|>example/mongotodo-api/server.js<|end_filename|> var express = require('express'); var app = express(); var server = require('http').Server(app); app.use(express.static("./")) server.listen(process.env.PORT || 3000) console.log("check localhost:" + process.env.PORT || 3000); <|start_filename|>src/Context.js<|end_filename|> module.exports = { setEnv(context, env) { context._env = env; return context; }, setPipeCallId(context, id) { context._pipeCallId = id; return context; }, passChains(context, chains) { context._passChains = chains; }, cleanUp(context) { delete context._env; delete context._pipeCallId; return context; }, updateAfterTransition(message){ Object.keys(message.context).reduce(function(result, name){ if(name !== '_env') result[name] = message.context[name]; return result; }, context); return message; } } <|start_filename|>example/simple-todo/client.js<|end_filename|> var logic = require('./logic'); var connectors = require('../connectors/SocketIODuplexStream') var PromisePipe = logic.PromisePipe; var socket = io.connect('http://localhost:3000'); PromisePipe.stream('client','server').connector(connectors.SIOClientServerStream(socket)) module.exports = logic; <|start_filename|>example/auction/src/stores/MeStore.js<|end_filename|> var Store = require('./BasicStore'); module.exports = Store("MeStore", { item: {}, init: function(context){ context.on('me:success', this.updateMe.bind(this)); context.on('me:logout', this.clean.bind(this)); }, updateMe: function(data){ console.log("UPDATE") this.item = data; this.emit('change', data); }, clean: function(data){ this.item = {}; this.emit('change', data); }, get: function(){ return this.item; } }) <|start_filename|>example/simple/server.js<|end_filename|> var pipe = require('./logic.js'); var PromisePipe = pipe.PromisePipe; var express = require('express'); var bodyParser = require('body-parser') var app = express(); var server = require('http').Server(app); // parse application/json app.use(bodyParser.json()) var io = require('socket.io')(server); var connectors = require('../connectors/SocketIODuplexStream') PromisePipe.stream('server','client').connector(connectors.SIOServerClientStream(io)) //var connectors = require('../connectors/HTTPDuplexStream') //PromisePipe.stream('server','client').connector(connectors.HTTPServerClientStream(app)) app.use(function(req,res,next){ next(); }) app.use(express.static("./")) server.listen(3000) console.log("check localhost:3000"); <|start_filename|>example/auction/src/stores/ItemsStore.js<|end_filename|> var Store = require('./BasicStore'); module.exports = Store("ItemsStore", { items: [], init: function(context){ context.on('item:update', this.updateItem.bind(this)); context.on('items:update', this.updateItems.bind(this)); }, updateItems: function(data){ this.items = data; this.emit('change', this.items); }, updateItem: function(data){ this.items = this.items.reduce((res, item)=>{ if(+data.id == +item.id){ res.push(data) } else { res.push(item) } return res; }, []); this.emit('change', this.items); }, get: function(){ return this.item; }, fill: function(items){ if(!this.items[0]) this.items = items; } }) <|start_filename|>example/connectors/SocketIODuplexStream.js<|end_filename|> module.exports = { SIOClientServerStream: function Stream(socket){ return { send: function(message){ socket.emit('messageToServer', message); }, listen: function(handler){ socket.on('messageToClient', function (message) { handler(message); }); } } }, SIOServerClientStream: function ServerClientStream(io){ var StreamHandler=null; io.on('connection', function (socket) { socket.on('messageToServer', function (message) { message._socket = socket; if(StreamHandler) StreamHandler(message); }); }); return { send: function(message){ var socket = message._socket; message._socket = undefined; if(!socket) throw new Error("Socket is nod defined in the message"); socket.emit('messageToClient', message); }, listen: function(handler){ StreamHandler = handler; } } } } <|start_filename|>src/linkProcessors/bothProcessor.js<|end_filename|> let Context = require('../Context'), debug = require('debug')('PP:runner'); module.exports = function catchProcessor(PromisePipe){ return { name: 'bothProcessor', predicate: function isBoth(link) { return link._env === 'both'; }, handler: function isBothHandler(link, context, data, executingChain, chain, Pipe) { var toNextEnv = getNameNextEnv(PromisePipe.env, context); if (!toNextEnv) { return executingChain.then(link._handler); } let range = rangeChain(link._id, chain); Context.passChains(context, passChains(range[0], range[1], chain)); return executingChain.then((data)=> { return Promise.resolve(data).then(link._handler).then(()=>{ debug(`link ${link._id} executed on ${PromisePipe.env} now send execution to ${toNextEnv}`) var msg = PromisePipe.createTransitionMessage(data, context, Pipe._id, link._id, chain[range[1]]._id, context._pipecallId); return PromisePipe.TransactionHandler.createTransaction(msg) .send(PromisePipe.envTransitions[context._env][toNextEnv]) .then(context.updateAfterTransition) .then(handleRejectAfterTransition); }) }); } }; /** * Return filtered list for passing functions * @param {Number} first * @param {Number} last * @return {Array} */ function passChains (first, last, sequence) { return sequence.map(function (el) { return el._id; }).slice(first, last + 1); } /** * Return lastChain index * @param {Number} first * @return {Number} */ function lastChain (first, sequence) { var index = getIndexOfNextEnvAppearance(first, PromisePipe.env, sequence); return index === -1 ? (sequence.length - 1) : (index - 1); } /** * Get chain by index * @param {String} id * @param {Array} sequence */ function getChainIndexById(id, sequence){ return sequence.map(function(el){ return el._id; }).indexOf(id); } /** * Get index of next env appearance * @param {Number} fromIndex * @param {String} env * @return {Number} */ function getIndexOfNextEnvAppearance(fromIndex, env, sequence){ return sequence.map(function(el){ return el._env; }).indexOf(env, fromIndex); } /** * Return tuple of chained indexes * @param {Number} id * @return {Tuple} */ function rangeChain (id, sequence) { var first = getChainIndexById(id, sequence); return [first, lastChain(first, sequence)]; } function getNameNextEnv(env, context) { if (!PromisePipe.envTransitions[context._env]) { return null; } return Object.keys(PromisePipe.envTransitions[context._env]).reduce(function (nextEnv, name) { if (nextEnv) { return nextEnv; } if (name === env) { return nextEnv; } if (name !== env) { return name; } }, null); } } function handleRejectAfterTransition(message){ return new Promise(function(resolve, reject){ if(message.unhandledFail) return reject(message.data); resolve(message.data); }) } <|start_filename|>src/logging.js<|end_filename|> var stackTrace = require('stacktrace-js'); module.exports = function({ logger }) { //it shows error in options.logger and passes it down return { enhance: function enhance(link) { return function errorEnhancer(data){ //is plain Error and was not yet caught if(data instanceof Error && !data.caughtOnChainId){ data.caughtOnChainId = link._id; var trace = stackTrace({e: data}); if(link.name) { logger.log('Failed inside ' + link.name); } logger.log(data.toString()); logger.log(trace.join('\n')); } return Promise.reject(data); } } } } <|start_filename|>example/mongotodo-api/client.js<|end_filename|> var PromisePipe = require('../../src/PromisePipe')(); PromisePipe.setMode('DEBUG'); var Promise = require('es6-promise').Promise; var ENV = 'CLIENT'; //set up server PromisePipe.use('api', exampleAPI); PromisePipe.use('and', function(){ return {}; }); var prepareItem = function prepareItem(data, context){ var item = { name: data, done: false } return data; return item; } module.exports = { PromisePipe: PromisePipe, getItems: PromisePipe() .api.getItems() .then(buildHtml) .then(renderItems), addItem: PromisePipe() .then(prepareItem) .api.addItem() .and() .api.getItems() .then(buildHtml) .then(renderItems), removeItem: PromisePipe() .api.removeItem() .and() .api.getItems() .then(buildHtml) .then(renderItems), doneItem: PromisePipe() .api.doneItem() .and() .api.getItems() .then(buildHtml) .then(renderItems), doneAllItem: PromisePipe() .then(function(data){ return { done: data } }) .api.doneAllItems() .and() .api.getItems() .then(buildHtml) .then(renderItems), clearDoneItems: PromisePipe() .api.clearDoneItems() .and() .api.getItems() .then(buildHtml) .then(renderItems), } function buildHtml(data){ data = data || []; result = renderTodoApp(renderAppHeader() + renderAppMain("<ul id='todo-list'>" + data.map(function(item, i){ var result = '<input class="toggle" type="checkbox" ' +(item.done?'checked':'')+ ' onclick="main.doneItem(\''+item._id+'\')"></input>'; result+= "<label>" + item.name + "</label>"; result+='<button class="destroy" onclick="main.removeItem(\''+item._id+'\')"></button>'; result = '<div class="view">'+result+'</div>' result = '<li class="'+(item.done?'completed':'')+'">'+result+'</li>' return result; }).join('') + "</ul>" , data) + renderAppFooter(data)) + renderAppInfo(); return result; } function renderItems(data){ document.getElementById('todo-app').innerHTML = data; return data; } function renderAppHeader(){ return '<header id="header"><h1>todos</h1><input id="new-todo" placeholder="What needs to be done?" autofocus onkeyup="event.which == 13 && main.addItem(this.value);"></header>'; } function renderAppMain(wrap, items){ var allChecked = items.reduce(function(result, item){ if(!item.done) return false; return result; }, true); return '<section id="main"><input id="toggle-all" '+(allChecked?'checked':'')+' type="checkbox" onclick="main.doneAllItem(this.checked)"><label for="toggle-all">Mark all as complete</label>' + wrap + '</section>'; } function renderAppFooter(data){ return '<footer id="footer"><span id="todo-count">' +(data?data.length:0)+ ' items</span><button id="clear-completed" onclick="main.clearDoneItems()">Clear completed</button></footer>'; } function renderTodoApp(wrap){ return '<section id="todoapp">' + wrap + '</section>'; } function renderAppInfo(){ return '<div id="info"><p>Written by <a href="https://github.com/edjafarov"><NAME></a></p><p><a href="https://github.com/edjafarov/PromisePipe/tree/master/example/mongotodo">PromisePipe based MongoDb persistent TodoApp</a> is a part of <a href="http://todomvc.com">TodoMVC</a></p></div>' } <|start_filename|>tests/security.PromisePipe.spec.js<|end_filename|> var sinon = require('sinon'); var Promise = require('es6-promise').Promise; var expect = require('chai').expect; describe('PromisePipe when comes to chains from other env', function(){ var PromisePipe = require('../src/PromisePipe')(); var PromisePipeServer = require('../src/PromisePipe')(); PromisePipeServer.setEnv('server'); var context = {}; var data1 = 1; var data2 = 2; var fn1 = sinon.stub(); var fn2 = sinon.stub(); var fn3 = sinon.stub(); var fn4 = sinon.stub(); var catchFn = sinon.stub(); fn2._env = 'server'; fn3._env = 'server'; var finish = sinon.spy(); fn1.withArgs(data1, context).returns(data1); fn2.withArgs(data1).returns(data2); fn3.withArgs(data2).returns(data2); fn4.withArgs(data1, context).returns(data1); fn4.withArgs(data2, context).returns(data2); var pipe = PromisePipe() .then(fn1) .then(fn2) .then(fn3) .then(fn4) .catch(catchFn); var pipeServer = PromisePipeServer() .then(fn1) .then(fn2) .then(fn3) .then(fn4) .catch(catchFn); describe('create transition message should create message consumable with execTransitionMessage', function(){ before(function(done){ PromisePipe.envTransition('client', 'server', function(message){ var innerMsg = JSON.parse(JSON.stringify(message)); innerMsg.chains = [innerMsg.chains[1],innerMsg.chains[1]]; PromisePipeServer.execTransitionMessage(innerMsg).then(function(data){ var ininnerMsg = JSON.parse(JSON.stringify(innerMsg)); ininnerMsg.data = data; PromisePipe.execTransitionMessage(ininnerMsg); }) }) pipe(data1, context).then(finish); done() }) it('should not allow omit execution of some chains', function(){ sinon.assert.calledOnce(fn1); sinon.assert.calledOnce(catchFn); expect(catchFn.getCall(0).args[0]).to.have.property('error','Non-consistent pipe call, message is trying to omit chains') }) }) }) <|start_filename|>example/PPRouter/adapters/ExpressAdapter.js<|end_filename|> function ExpressAppAdapter(app, layout){ layout = layout || function(html){return html}; var adapter = { //renderData is a hash of data, params, and component // per resolved part of url renderer: function(renderData){ var renderArr = Object.keys(renderData).map(function(mask){ return { mask: mask, context: renderData[mask].context, component: renderData[mask].component, params: renderData[mask].params, data: renderData[mask].data } }) function renderComp(renderArr){ var partial = renderArr.shift(); if(renderArr.length > 0) partial.params.children = [renderComp(renderArr)]; partial.params.mask = partial.mask; partial.params.data = partial.data; partial.params.context = partial.context; if(!partial.component) { var result = partial.data || ''; if(partial.params.children && partial.params.children[0]) result +=partial.params.children[0]; return result; } return partial.component(partial.params) } return renderComp(renderArr); } }; app.use(function(req, res, next){ if(req.method == 'GET'){ adapter.handleURL(req.originalUrl, req.context).then(function(data){ res.send(layout(adapter.renderer(data.renderData), data.renderData) || ""); data.handler.router.reset(); res.end(); }).catch(function(e){ if(e.name == 'UnrecognizedURLError') return next(); console.log(e); }); return; } next(); }) return adapter; } module.exports = ExpressAppAdapter; <|start_filename|>src/linkProcessors/nextEnvProcessor.js<|end_filename|> let Context = require('../Context'), PipeLink = require('../PipeLink'), debug = require('debug')('PP:runner');; const systemEnvs = ['both', 'inherit', 'cache']; module.exports = function nextEnvProcessor(PromisePipe){ const processor = { name: 'nextEnvProcessor', predicate: function isNextEnv(link, context) { return isLinkForOtherEnv(link, context) && !shouldLinkBeSkipped(link, context); }, handler: function nextEnvHandler(link, context, data, executingChain, chain, Pipe) { const sequence = Pipe._getSequence() .map(PipeLink.cloneLink) .map((link) => link.setEnv(link._env || PromisePipe.env)); let range = rangeChain(link._id, sequence); Context.passChains(context, passChains(range[0], range[1], sequence)); if (!isValidTransition(link, context)) { throw Error('there is no transition ' + context._env + ' to ' + link._env); } return executingChain.then(function (data) { var msg = PromisePipe.createTransitionMessage(data, context, Pipe._id, link._id, sequence[range[1]]._id, context._pipecallId); debug(`links ${context._passChains.join(',')} send execution to ${link._env}`) var result = PromisePipe.TransactionHandler.createTransaction(msg) .send(PromisePipe.envTransitions[context._env][link._env]) .then(context.updateAfterTransition) .then(handleRejectAfterTransition); //TODO: add logging? return result; }); } }; /** * Check env of system behavoir * @param {String} env Env for checking * @return {Boolean} */ function isSystemTransition (env) { return !!~systemEnvs.indexOf(env); } /** * Check valid is transition */ function isValidTransition (link, context) { var isValid = true; if (!(PromisePipe.envTransitions[context._env] && PromisePipe.envTransitions[context._env][link._env])) { if (!isSystemTransition(link._env)) { isValid = false; } } return isValid; } /** * Return filtered list for passing functions * @param {Number} first * @param {Number} last * @return {Array} */ function passChains (first, last, sequence) { return sequence.map(function (el) { return el._id; }).slice(first, last + 1); } /** * Return lastChain index * @param {Number} first * @return {Number} */ function lastChain (first, sequence) { var index = getIndexOfNextEnvAppearance(first, PromisePipe.env, sequence); return index === -1 ? (sequence.length - 1) : (index - 1); } /** * Get chain by index * @param {String} id * @param {Array} sequence */ function getChainIndexById(id, sequence){ return sequence.map(function(el){ return el._id; }).indexOf(id); } /** * Get index of next env appearance * @param {Number} fromIndex * @param {String} env * @return {Number} */ function getIndexOfNextEnvAppearance(fromIndex, env, sequence){ return sequence.map(function(el){ return el._env; }).indexOf(env, fromIndex); } /** * Return tuple of chained indexes * @param {Number} id * @return {Tuple} */ function rangeChain (id, sequence) { var first = getChainIndexById(id, sequence); return [first, lastChain(first, sequence)]; } return processor; } function handleRejectAfterTransition(message){ return new Promise(function(resolve, reject){ if(message.unhandledFail) return reject(message.data); resolve(message.data); }) } function isLinkForOtherEnv(link, context) { return link._env !== context._env; } function shouldLinkBeSkipped(link, context) { if (context._passChains && !!~context._passChains.indexOf(link._id)) return true; return false; } <|start_filename|>example/auction/src/stores/ItemStore.js<|end_filename|> var Store = require('./BasicStore'); module.exports = Store("ItemStore", { item: {}, init: function(context){ context.on('item:update', this.updateItem.bind(this)); }, updateItem: function(data){ this.item = data; this.emit('change', this.item); }, get: function(){ return this.item; } }) <|start_filename|>example/file-upload/client.js<|end_filename|> var logic = require('./logic'); var connector = require('http-connector')(); var PromisePipe = logic.PromisePipe; PromisePipe.stream('client','server').connector(connector.HTTPClientServerStream()) module.exports = logic; <|start_filename|>example/simple/logic.js<|end_filename|> var PromisePipe = require('../../src/PromisePipe')(); PromisePipe.setMode("DEBUG"); var Promise = require('es6-promise').Promise; var ENV = 'CLIENT'; //set up server if(typeof(window) !== 'object'){ PromisePipe.setEnv('server'); ENV = 'SERVER'; } //((2+5+6+10)*2)^3-2-6 = 10640 module.exports = PromisePipe() .then(plus(5)) .then(minus(6)) .then(doOnServer(plus(10))) .then(doOnServer(multipy(2))) .then(doOnServer(minus(2))) .then(minus(6)) module.exports.PromisePipe = PromisePipe; function plus(a){ return function plus(data, context){ return doAsyncStuff("add "+a+" to "+data, function(){ return data + a; }) } } function minus(a){ return function minus(data, context){ return doAsyncStuff("subtract "+a+" of "+data, function(){ return data - a; }); } } function doOnServer(fn){ fn._env = 'server'; return fn } function prepare(data, context){ if(!context.stack) context.stack = []; return data; } function multipy(a){ return function multipy(data, context){ return doAsyncStuff("multipy "+data+" by "+a, function(){ return data * a; }); } } function pow(a){ return function pow(data, context){ return doAsyncStuff("power "+data+" by "+a, function(){ return Math.pow(data, a); }); } } function doAsyncStuff(text, fn){ console.log(text); return new Promise(function(res, rej){ var result = fn.call(null); setTimeout(function(){ console.log("=", result); res(result); }, 1000); }) } <|start_filename|>example/mongotodo/server.js<|end_filename|> var main = require('./logic.js'); var express = require('express'); var app = express(); var server = require('http').Server(app); var io = require('socket.io')(server); var cookieParser = require('cookie-parser'); var expressSession = require('express-session'); var MongoStore = require('connect-mongo')(expressSession); var connectors = require('../connectors/SessionSocketIODuplexStream') var myCookieParser = cookieParser('secret'); var sessionStore = new MongoStore({ url: process.env.MONGOHQ_URL || "mongodb://localhost:27017/test" }); server.listen(process.env.PORT || 3000) console.log("check localhost:" + process.env.PORT || 3000); var PromisePipe = main.PromisePipe; app.use(myCookieParser); app.use(expressSession({ secret: 'secret', store: sessionStore })); app.use(express.static("./")) var SessionSockets = require('session.socket.io') , sessionSockets = new SessionSockets(io, sessionStore, myCookieParser); PromisePipe.stream('server','client').connector(connectors.SIOServerClientStream(sessionSockets)) <|start_filename|>tests/multiple-transitions.PromisePipe.spec.js<|end_filename|> var EventEmitter = require('events').EventEmitter; var sinon = require('sinon'); var Promise = require('es6-promise').Promise; var expect = require('chai').expect; describe('PromisePipe when comes to chains from other env', function(){ var PromisePipe = require('../src/PromisePipe')(); var PromisePipeServer = require('../src/PromisePipe')(); var PromisePipeWorker = require('../src/PromisePipe')(); PromisePipeServer.setEnv('server'); PromisePipeWorker.setEnv('worker'); var context = {}; var context1 = {}; var context2 = {}; var data1 = 1; var data2 = 2; var fn1 = sinon.stub(); var fn2 = sinon.stub(); var fn3 = sinon.stub(); var fn4 = sinon.stub(); var fn5 = sinon.stub(); fn1.withArgs(data1).returns(data1); fn2.withArgs(data1).returns(data1); fn3.withArgs(data1).returns(data1); fn4.withArgs(data1).returns(data1); fn5.withArgs(data1).returns(data1); var serverSocketMock = new EventEmitter(); var clientSocketMock = new EventEmitter(); var workerSocketMock = new EventEmitter(); function sendToClient(message){ clientSocketMock.emit('message', JSON.stringify(message)); } function sendToServer(message){ serverSocketMock.emit('message', JSON.stringify(message)); } function sendToWorker(message){ workerSocketMock.emit('message', JSON.stringify(message)); } PromisePipe.envTransition('client', 'server', function(message){ sendToServer(message); }); PromisePipeServer.envTransition('server', 'worker', function(message){ sendToWorker(message); //return PromisePipeServer.promiseMessage(message); }); clientSocketMock.on('message', function(message){ message = JSON.parse(message); PromisePipe.execTransitionMessage(message); }); serverSocketMock.on('message', function(message){ message = JSON.parse(message); PromisePipeServer.execTransitionMessage(message).then(function(data){ message.data = data; sendToClient(message); }); }); workerSocketMock.on('message', function(message){ message = JSON.parse(message); PromisePipeWorker.execTransitionMessage(message).then(function(data){ message.data = data; sendToServer(message); }); }); fn2._env = 'server'; fn3._env = 'worker'; fn4._env = 'server'; var finish = sinon.spy(); var pipe = PromisePipe() .then(fn1) .then(fn2) .then(fn3) .then(fn4) .then(fn5); var pipeServer = PromisePipeServer() .then(fn1) .then(fn2) .then(fn3) .then(fn4) .then(fn5); var pipeWorker = PromisePipeWorker() .then(fn1) .then(fn2) .then(fn3) .then(fn4) .then(fn5); before(function(done){ pipe(data1, context).then(finish); done() }) it('should not fail', function(){ sinon.assert.calledOnce(fn1); sinon.assert.calledOnce(fn2); sinon.assert.calledOnce(fn3); sinon.assert.calledOnce(fn4); sinon.assert.calledOnce(fn5); sinon.assert.calledWithExactly(finish, data1); }) describe("server should also work fine", function(){ before(function(done){ pipeServer(data1, context1).then(finish); done() }) it('should not fail', function(){ sinon.assert.calledTwice(fn1); sinon.assert.calledTwice(fn2); sinon.assert.calledTwice(fn3); sinon.assert.calledTwice(fn4); sinon.assert.calledTwice(fn5); sinon.assert.calledWithExactly(finish, data1); }) }) }) describe('PromisePipe when comes to chains from other env', function(){ var PromisePipe = require('../src/PromisePipe')(); var PromisePipeServer = require('../src/PromisePipe')(); var PromisePipeWorker = require('../src/PromisePipe')(); PromisePipeServer.setEnv('server'); PromisePipeWorker.setEnv('worker'); var context = {}; var context1 = {}; var context2 = {}; var data1 = 1; var data2 = 2; var fn1 = sinon.stub(); var fn2 = sinon.stub(); var fn3 = sinon.stub(); var fn4 = sinon.stub(); var fn5 = sinon.stub(); fn1.withArgs(data1).returns(data1); fn2.withArgs(data1).returns(data1); fn3.withArgs(data1).returns(data1); fn4.withArgs(data1).returns(data1); fn5.withArgs(data1).returns(data1); var serverSocketMock = new EventEmitter(); var clientSocketMock = new EventEmitter(); var workerSocketMock = new EventEmitter(); function sendToClient(message){ clientSocketMock.emit('message', JSON.stringify(message)); } function sendToServer(message){ serverSocketMock.emit('message', JSON.stringify(message)); } function sendToWorker(message){ workerSocketMock.emit('message', JSON.stringify(message)); } PromisePipe.envTransition('client', 'server', function(message){ sendToServer(message); }); PromisePipeServer.envTransition('server', 'worker', function(message){ sendToWorker(message); //return PromisePipeServer.promiseMessage(message); }); clientSocketMock.on('message', function(message){ message = JSON.parse(message); PromisePipe.execTransitionMessage(message); }); serverSocketMock.on('message', function(message){ message = JSON.parse(message); PromisePipeServer.execTransitionMessage(message).then(function(data){ message.data = data; sendToClient(message); }); }); workerSocketMock.on('message', function(message){ message = JSON.parse(message); PromisePipeWorker.execTransitionMessage(message).then(function(data){ message.data = data; sendToServer(message); }); }); fn2._env = 'server'; fn3._env = 'worker'; fn4._env = 'worker'; fn5._env = 'worker'; var finish = sinon.spy(); var pipe = PromisePipe() .then(fn1) .then(fn2) .then(fn3) .then(fn4) .then(fn5); var pipeServer = PromisePipeServer() .then(fn1) .then(fn2) .then(fn3) .then(fn4) .then(fn5); var pipeWorker = PromisePipeWorker() .then(fn1) .then(fn2) .then(fn3) .then(fn4) .then(fn5); describe("should work if pseudo nested", function(){ before(function(done){ pipe(data1, context2).then(finish); done() }) it('should not fail', function(){ sinon.assert.calledOnce(fn1); sinon.assert.calledOnce(fn2); sinon.assert.calledOnce(fn3); sinon.assert.calledOnce(fn4); sinon.assert.calledOnce(fn5); sinon.assert.calledOnce(finish); sinon.assert.calledWithExactly(finish, data1); }) }) }) xdescribe('PromisePipe can find its way through complex nested transition #22', function(){ /* It is more complicated than I thought the nested chain do not know about capabilities of outer chain thus some protocol is required that will predict behavior of execution and will build a path or something */ var PromisePipe = require('../src/PromisePipe')(); var PromisePipeServer = require('../src/PromisePipe')(); var PromisePipeWorker1 = require('../src/PromisePipe')(); var PromisePipeWorker2 = require('../src/PromisePipe')(); PromisePipeServer.setEnv('server'); PromisePipeWorker1.setEnv('worker1'); PromisePipeWorker2.setEnv('worker2'); var context = {}; var context1 = {}; var context2 = {}; var data1 = 1; var data2 = 2; var fn1 = sinon.stub(); var fn2 = sinon.stub(); var fn3 = sinon.stub(); var fn4 = sinon.stub(); var fn5 = sinon.stub(); fn1.withArgs(data1).returns(data1); fn2.withArgs(data1).returns(data1); fn3.withArgs(data1).returns(data1); fn4.withArgs(data1).returns(data1); fn5.withArgs(data1).returns(data1); var serverSocketMock = new EventEmitter(); var clientSocketMock = new EventEmitter(); var worker1SocketMock = new EventEmitter(); var worker2SocketMock = new EventEmitter(); function sendToClient(message){ clientSocketMock.emit('message', JSON.stringify(message)); } function sendToServer(message){ serverSocketMock.emit('message', JSON.stringify(message)); } function sendToWorker1(message){ worker1SocketMock.emit('message', JSON.stringify(message)); } function sendToWorker2(message){ worker2SocketMock.emit('message', JSON.stringify(message)); } PromisePipe.envTransition('client', 'server', function(message){ sendToServer(message); }); PromisePipeServer.envTransition('server', 'worker1', function(message){ sendToWorker1(message); //return PromisePipeServer.promiseMessage(message); }); PromisePipeWorker1.envTransition('worker1', 'worker2', 'server'); PromisePipeServer.envTransition('server', 'worker2', function(message){ sendToWorker2(message); //return PromisePipeServer.promiseMessage(message); }); clientSocketMock.on('message', function(message){ message = JSON.parse(message); PromisePipe.execTransitionMessage(message); }); serverSocketMock.on('message', function(message){ message = JSON.parse(message); PromisePipeServer.execTransitionMessage(message).then(function(data){ message.data = data; sendToClient(message); }); }); worker1SocketMock.on('message', function(message){ message = JSON.parse(message); PromisePipeWorker1.execTransitionMessage(message).then(function(data){ message.data = data; sendToServer(message); }); }); worker2SocketMock.on('message', function(message){ message = JSON.parse(message); PromisePipeWorker2.execTransitionMessage(message).then(function(data){ message.data = data; sendToServer(message); }); }); fn2._env = 'server'; fn3._env = 'worker1'; fn4._env = 'worker2'; fn5._env = 'client'; var finish = sinon.spy(); var pipe = PromisePipe() .then(fn1) .then(fn2) .then(fn3) .then(fn4) .then(fn5); var pipeServer = PromisePipeServer() .then(fn1) .then(fn2) .then(fn3) .then(fn4) .then(fn5); var pipeWorker1 = PromisePipeWorker1() .then(fn1) .then(fn2) .then(fn3) .then(fn4) .then(fn5); var pipeWorker2 = PromisePipeWorker2() .then(fn1) .then(fn2) .then(fn3) .then(fn4) .then(fn5); describe("should work if pseudo nested", function(){ before(function(done){ pipe(data1, context2).then(finish); done() }) it('should not fail', function(){ sinon.assert.calledOnce(fn1); sinon.assert.calledOnce(fn2); sinon.assert.calledOnce(fn3); sinon.assert.calledOnce(fn4); sinon.assert.calledOnce(fn5); sinon.assert.calledOnce(finish); sinon.assert.calledWithExactly(finish, data1); }) }) }) <|start_filename|>tests/transitions.PromisePipe.spec.js<|end_filename|> var sinon = require('sinon'); var Promise = require('es6-promise').Promise; var expect = require('chai').expect; describe('PromisePipe when comes to chains from other env', function(){ var PromisePipe = require('../src/PromisePipe')(); var PromisePipeServer = require('../src/PromisePipe')(); PromisePipeServer.setEnv('server'); var context = {}; var data1 = 1; var data2 = 2; var fn1 = sinon.stub(); var fn2 = sinon.stub(); var fn3 = sinon.stub(); var fn4 = sinon.stub(); fn2._env = 'server'; fn3._env = 'server'; var finish = sinon.spy(); fn1.withArgs(data1, context).returns(data1); fn2.withArgs(data1).returns(data2); fn3.withArgs(data2).returns(data2); fn4.withArgs(data1, context).returns(data1); fn4.withArgs(data2, context).returns(data2); var pipe = PromisePipe() .then(fn1) .then(fn2) .then(fn3) .then(fn4); var pipeServer = PromisePipeServer() .then(fn1) .then(fn2) .then(fn3) .then(fn4); describe('create transition message should create message consumable with execTransitionMessage', function(){ before(function(done){ PromisePipe.envTransition('client', 'server', function(message){ var innerMsg = JSON.parse(JSON.stringify(message)); PromisePipeServer.execTransitionMessage(innerMsg).then(function(data){ var ininnerMsg = JSON.parse(JSON.stringify(innerMsg)); ininnerMsg.data = data; PromisePipe.execTransitionMessage(ininnerMsg); }); }); pipe(data1, context).then(finish); done(); }); it('transition should create a message and pass it to server side, complete chain should pass', function(){ sinon.assert.calledOnce(fn2); sinon.assert.calledOnce(fn3); sinon.assert.calledOnce(fn1); sinon.assert.calledOnce(fn4); sinon.assert.calledWith(fn4, data2); sinon.assert.calledWithExactly(finish, data2); }); }); }); describe('PromisePipe when comes to chains from other env', function(){ var PromisePipe = require('../src/PromisePipe')(); var PromisePipeServer = require('../src/PromisePipe')(); PromisePipeServer.setEnv('server'); var context = {}; var data1 = 1; var data2 = 2; var fn1 = sinon.stub(); var fn2 = sinon.stub(); var fn3 = sinon.stub(); var fn4 = sinon.stub(); var fn5 = sinon.stub(); fn2._env = 'server'; fn3._env = 'server'; var finish = sinon.spy(); fn1.withArgs(data1, context).returns(data1); fn2.withArgs(data1).returns(Promise.reject("failTest")); fn3.withArgs(data2).returns(data2); fn4.withArgs(data1, context).returns(data1); fn4.withArgs(data2, context).returns(data2); var pipe = PromisePipe() .then(fn1) .then(fn2) .then(fn3) .then(fn4) .catch(fn5); var pipeServer = PromisePipeServer() .then(fn1) .then(fn2) .then(fn3) .then(fn4) .catch(fn5); describe('should fail back to client', function(){ before(function(done){ PromisePipe.envTransition('client', 'server', function(message){ var innerMsg = JSON.parse(JSON.stringify(message)); PromisePipeServer.execTransitionMessage(innerMsg).then(function(data){ var ininnerMsg = JSON.parse(JSON.stringify(innerMsg)); ininnerMsg.data = data; PromisePipe.execTransitionMessage(ininnerMsg); }) }) pipe(data1, context).then(finish); done() }) it('transition should be caught by client"s catch', function(){ sinon.assert.calledOnce(fn1); sinon.assert.calledOnce(fn2); sinon.assert.notCalled(fn3) sinon.assert.notCalled(fn4); sinon.assert.calledOnce(fn5); sinon.assert.calledWith(fn5, 'failTest'); }) }) }) describe('PromisePipe (#24 bug test)', function(){ var PromisePipe = require('../src/PromisePipe')(); var PromisePipeServer = require('../src/PromisePipe')(); var doOnServer = PromisePipe.in('server'); PromisePipeServer.setEnv('server'); var context = {}; var data1 = 1; var data2 = 2; var fn1 = sinon.stub(); var fn2 = sinon.stub(); var fn4 = sinon.stub(); var finish = sinon.spy(); fn1.withArgs(data1).returns(data1); fn2.withArgs(data1).returns(data2); fn2.withArgs(data2).returns(data1); fn4.withArgs(data1).returns(data1); var pipe = PromisePipe() .then(doOnServer(fn1)) .then(fn2) .then(doOnServer(fn2)) .then(fn4); var pipeServer = PromisePipeServer() .then(doOnServer(fn1)) .then(fn2) .then(doOnServer(fn2)) .then(fn4); describe('create transition message should create message consumable with execTransitionMessage', function(){ before(function(done){ PromisePipe.envTransition('client', 'server', function(message){ var innerMsg = JSON.parse(JSON.stringify(message)); PromisePipeServer.execTransitionMessage(innerMsg).then(function(data){ var ininnerMsg = JSON.parse(JSON.stringify(innerMsg)); ininnerMsg.data = data; PromisePipe.execTransitionMessage(ininnerMsg); }) }) pipe(data1, context).then(finish); done() }) it('transition should create a message and pass it to server side, complete chain should pass', function(){ sinon.assert.calledOnce(fn1); sinon.assert.calledTwice(fn2); sinon.assert.calledOnce(fn4); sinon.assert.calledWith(fn4, data1); sinon.assert.calledWithExactly(finish, data1); }) }) }) describe('PromisePipe', function(){ var PromisePipe = require('../src/PromisePipe')(); var PromisePipeServer = require('../src/PromisePipe')(); PromisePipeServer.setEnv('server'); var context = {}; var data1 = 1; var data2 = 2; var fn1 = sinon.stub(); var fn2 = sinon.stub(); var fn3 = sinon.stub(); var fn4 = sinon.stub(); function fn2(data) { console.log(data, "1212"); return data; } function fn3(data) { console.log(data, "1212"); return data; } fn2._env = 'both'; fn3._env = 'server'; var finish = sinon.spy(); fn1.withArgs(data1).returns(data1); fn2.withArgs(data1).returns(data2); fn3.withArgs(data2).returns(data2); fn4.withArgs(data1).returns(data1); fn4.withArgs(data2).returns(data2); var pipe = PromisePipe() .then(fn1) .then(fn2) .then(fn3) .then(fn4); var pipeServer = PromisePipeServer() .then(fn1) .then(fn2) .then(fn3) .then(fn4); describe('create transition message should create message consumable with execTransitionMessage', function(){ before(function(done){ PromisePipe.envTransition('client', 'server', function(message){ var innerMsg = JSON.parse(JSON.stringify(message)); PromisePipeServer.execTransitionMessage(innerMsg).then(function(data){ var ininnerMsg = JSON.parse(JSON.stringify(innerMsg)); ininnerMsg.data = data; PromisePipe.execTransitionMessage(ininnerMsg); }); }) pipe(data1, context).then(finish); done() }) it('transition should create a message and pass it to server side, complete chain should pass', function(){ sinon.assert.calledTwice(fn2); sinon.assert.calledOnce(fn3) sinon.assert.calledOnce(fn1); sinon.assert.calledOnce(fn4); sinon.assert.calledWith(fn4, data2); sinon.assert.calledWithExactly(finish, data2); }) }) })
edjafarov/PromiseStreams
<|start_filename|>src/botLikeTimeline.js<|end_filename|> 'use strict' const Client = require('instagram-private-api').V1; const delay = require('delay'); const chalk = require('chalk'); const _ = require('lodash'); const inquirer = require('inquirer'); const User = [ { type:'input', name:'username', message:'[>] Insert Username:', validate: function(value){ if(!value) return 'Can\'t Empty'; return true; } }, { type:'password', name:'password', message:'[>] Insert Password:', mask:'*', validate: function(value){ if(!value) return 'Can\'t Empty'; return true; } }, { type:'input', name:'sleep', message:'[>] Insert Sleep (MiliSeconds):', validate: function(value){ value = value.match(/[0-9]/); if (value) return true; return 'Delay is number'; } } ] const Login = async function(User){ /** Save Account **/ const Device = new Client.Device(User.username); const Storage = new Client.CookieMemoryStorage(); const session = new Client.Session(Device, Storage); try { await Client.Session.create(Device, Storage, User.username, User.password) const account = await session.getAccount(); return Promise.resolve({session,account}); } catch (err) { return Promise.reject(err); } } const Like = async function(session,media){ try { if (media.params.hasLiked) { return chalk`{bold.blue Already Liked}`; } await Client.Like.create(session, media.id); return chalk`{bold.green Success Like}`; } catch (err) { return chalk`{bold.red Failed Like}`; } } const Excute = async function(User, sleep){ try { console.log(chalk`\n{yellow [?] Try to Login . . .}`); const doLogin = await Login(User); console.log(chalk`{green [!] Login Succsess}, {yellow [?] Try Like All Media in Feed / Timeline . . .\n}`); const feed = new Client.Feed.Timeline(doLogin.session); var cursor; do { if (cursor) feed.setCursor(cursor); var media = await feed.get(1); media = _.chunk(media, 10); for (var i = 0; i < media.length; i++) { await Promise.all(media[i].map(async (media) => { const doLike = await Like(doLogin.session, media); console.log(chalk`[{bold.green Username:}] ${media.params.user.username}\n[{cyan ${media.id}}] => [${doLike}]`); })) await console.log(chalk`{yellow \n [#][>] Delay For ${sleep} MiliSeconds [<][#] \n}`); await delay(sleep); } } while(feed.isMoreAvailable()); } catch (err) { console.log(err); } } console.log(chalk` {bold.cyan —————————————————— [INFORMATION] ———————————————————— [?] {bold.green Bot Like Timeline} —————————————————— [THANKS TO] ———————————————————— [✓] CODE BY <NAME> CCOCOT (<EMAIL>) [✓] FIXING & TESTING BY SYNTAX (@officialputu_id) [✓] CCOCOT.CO | BC0DE.NET | NAONLAH.NET | WingkoColi [✓] SGB TEAM REBORN | Zerobyte.id | <EMAIL> —————————————————————————————————————————————————————} `); inquirer.prompt(User) .then(answers => { Excute({ username:answers.username, password:answers.password },answers.sleep); })
br1prdo/instagram
<|start_filename|>LeagueToolkit/app/style.css<|end_filename|> @font-face { font-family: "beaufort-bold"; src: url("assets/fonts/Beaufort-Bold.ttf"); } @font-face { font-family: "beaufort-regular"; src: url("assets/fonts/Beaufort-Regular.ttf"); } body { background: linear-gradient(to bottom, rgba(125, 185, 232, 0) -1%, rgba(50, 96, 122, 0) 65%, rgba(10, 49, 64, 0.8) 100%), url(https://i.4da.ms/Gch1r6.png); background-position: center; background-size: cover; background-attachment: fixed; /* font-family: 'Patua One', cursive; */ font-family: "beaufort-bold"; text-transform: uppercase; margin: 0 auto; /* text-align: center; */ position: fixed; width: 100%; user-select: none; } .option-name { font-size: 25px; color: #f0e6d2; margin-bottom: 10px; } .suboption-name { font-size: 16px; color: #cdbe91; margin-bottom: 5px; } .title { text-align: center; margin-top: 250px; margin-bottom: 50px; } h1 { color: #fff; font-weight: 100; font-size: 59px; margin-bottom: 5px; } hr { width: 350px; margin-top: 40px; margin-bottom: 40px; border: 1px solid #cdbe91; } .tier { width: 150px !important; } .division { width: 50px !important; margin-top: 3px; } .left { float: left; margin: 2px; } .center { text-align: center; } .center-area { display: block; margin-left: auto; margin-right: auto; margin-top: 3px; } .end { margin-bottom: 50px; } .controls { color: #fff; float: right; margin-right: 5px; margin-top: -70px; -webkit-app-region: no-drag; } .version { position: fixed; bottom: 15px; left: 15px; cursor: default; } .version-tag { margin: 0px; color: #a09b8c; opacity: 0.5; transition: opacity .1s ease-in-out; text-decoration: none; } .version-tag:hover { opacity: 1; color: #a09b8c; text-decoration: none; } .icon { font-size: 20px !important; } /* Style the buttons that are used to open the tab content */ .controls button { background-color: transparent; float: left; border: none; outline: none; cursor: pointer; padding: 4px 4px; transition: 0.3s; -webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none; font-size: 8px; margin-left: 10px; } /* Change background color of buttons on hover */ .controls button:hover { color: #f0e6d2; border: none; outline: none; cursor: pointer; -webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none; } /* Create an active/current tablink class */ .controls button.active { color: #f0e6d2; } .getstarted { margin-top: -10px; } /* SCROLL BAR */ ::-webkit-scrollbar { width: 7px; border-radius: 5px; } ::-webkit-scrollbar * { background: transparent; } ::-webkit-scrollbar-track-piece:start { background: transparent; } ::-webkit-scrollbar-track-piece:end { background: transparent; } ::-webkit-scrollbar-thumb { background: #9b722c; border-radius: 10px; } ::-webkit-scrollbar-thumb:hover { background: #d4b373; } /* BUTTONS */ button { display: inline-block; position: relative; font-family: 'beaufort-bold', cursive; /* font-family: 'Beaufort', 'Times New Roman', serif; */ text-transform: uppercase; color: #CDBE91; font-weight: 100; letter-spacing: 1px; white-space: nowrap; padding: 9px 21px; cursor: pointer; box-shadow: 0 0 1px 1px #010A13, inset 0 0 1px 1px #010A13; background: #1E2328; border: 2px solid transparent; border-image: linear-gradient(to top, #785B28 0%, #C89C3C 55%, #C8A355 71%, #C8AA6E 100%); border-image-slice: 1; transition: opacity 300ms linear; margin-top: 5px; transition: color 100ms linear; } button:hover { color: #F0E6D2; border: 2px solid transparent; border-image: linear-gradient(to top, rgb(78.4%, 61.2%, 23.5%) 0%, rgb(86.3%, 75.7%, 53.3%) 50%, rgb(88.2%, 78.8%, 59.6%) 71%, rgb(94.1%, 90.2%, 84.7%) 100%); border-image-slice: 1; box-shadow: 0px 0px 13px 0px rgba(205, 190, 145, 0.39); transition: color 100ms linear; /* filter: blur(4px); */ } button:active { color: #E4E1D8; border-image: linear-gradient(to top, #FFFFFF 0%, #FFFFFF 33%, #FFFFFF 66%, #FFFFFF 100%); border-image-slice: 1; color: #5C5B57; transition: color 100ms linear; animation: none; } button:focus { outline: 0; } button:after { transition: all 0.8s } /* TEXT FIELDS */ textarea { overflow: hidden; white-space: nowrap; resize: none; font-family: 'Open Sans', sans-serif; padding: 10px 10px; color: rgb(62.7%, 60.8%, 54.9%); display: block; box-sizing: border-box; border: 1px solid #785A28; background-color: rgba(0, 0, 0, 0.7); appearance: none; outline: none; box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.25) inset, 0 0 0 1px rgba(0, 0, 0, 0.25); } textarea:focus { background: linear-gradient(to bottom, rgba(7, 16, 25, 0.7), rgba(32, 39, 44, 0.7)); border-image: linear-gradient(to bottom, #785a28, #c8aa6e) 1 stretch; } textarea:disabled { color: rgba(230, 33, 66, 0.7) !important; border: 1px solid rgba(230, 33, 66, 0.7); } /* DROPDOWNS */ .dropdown { display: inline-block; position: relative; cursor: pointer; width: 200px; font-family: 'beaufort-bold', sans-serif; color: rgb(62.7%, 60.8%, 54.9%); ; letter-spacing: 0.025rem; outline: none; padding: 10px 14px; background-color: rgba(30, 35, 40, 0.5); border: 1px solid transparent; border-image: linear-gradient(to top, #695625 0%, #A9852D 23%, #B88D35 93%, #C8AA6E 100%) 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; -webkit-appearance: none; -moz-appearance: none; } .dropdown:active { background: rgba(30, 35, 40, 0.5); color: #463714; border: 1px solid #463714; } .dropdown:focus { background: linear-gradient(to top, rgba(88, 83, 66, 0.5), rgba(30, 35, 40, 0.5)); border: 1px solid transparent; border-image: linear-gradient(to top, #c89b3c, #f0e6d2) 1; } .dropdown option { position: relative; color: #cdbe91; cursor: pointer; padding: 9px; border-top: 1px solid #1f2123; text-overflow: ellipsis; white-space: nowrap; background: #010a13; -o-border-image: linear-gradient(0deg, #695625, #463714) 1; border-image: -webkit-linear-gradient(bottom, #695625, #463714) 1; border-image: linear-gradient(0deg, #695625, #463714) 1; font-size: 13px; height: 20px; } .dropdown option:hover { background-color: #fff; } .dropdown option:disabled { color: #756c53; } /* SECTIONS */ .sections { margin-bottom: 100px; } /* Style the tab */ .tab-container { position: fixed; top: 0px; margin: 0px auto; width: 100%; border-top: 2px solid #735828; border-bottom: 1px solid rgba(255, 255, 255, 0.4); height: 100px; background: linear-gradient(to bottom, rgba(0, 0, 0, 0.65) 0%, rgba(0, 0, 0, 0) 80%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */ -webkit-app-region: drag; } .tab { margin: 0px auto; margin-top: 20px; margin-left: 15px; overflow: hidden; } .selected { position: absolute; left: -10px; } /* Style the buttons that are used to open the tab content */ .tab button { background-color: transparent; float: left; border: none; outline: none; cursor: pointer; padding: 14px 16px; transition: 0.3s; -webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none; font-size: 16px; margin-left: 28px; -webkit-app-region: no-drag; } /* Change background color of buttons on hover */ .tab button:hover { color: #f0e6d2; } /* Create an active/current tablink class */ .tab button.active { color: #f0e6d2; } /* Style the tab content */ .tabcontent { display: none; border-top: none; margin-top: 115px; } .box { float: right; width: 950px; height: 593px; overflow-y: scroll; margin-right: 10px; } .info { position: absolute; margin-left: 35px; margin-top: 25px; } .float-left { float: left; margin-right: 5px; } .option { margin-bottom: 25px; } .summonericon { border-radius: 50%; width: 140px; height: 140px; display: block; margin-left: auto; margin-right: auto; } .icon-box { position: absolute; top: 23px; width: 248px; height: 140px; } .offset { margin-top: 25px !important; } .info-bp { text-align: center; margin-top: -10px; font-size: 15px; color: #f0e6d2; margin-bottom: 10px; } .info-status { display: block; margin-left: auto; margin-right: auto; } .info-name { text-align: center; margin-top: -165px; font-size: 25px; color: #f0e6d2; margin-bottom: 0px; } .level-badge { /* top: 155px; */ /* left: 88px; */ display: block; margin-left: auto; margin-right: auto } .level-level { margin: 0px; margin-top: -27px; text-align: center; font-size: 15px; color: #f0e6d2; /* margin-top: -204px; */ } .level-box { position: absolute; top: 155px; width: 246px; height: 25px; } /* CHECKBOXES */ .options { font-family: 'beaufort-bold'; text-transform: none; margin: 10px; margin-left: 0px; color: #a09b8c; } .options:hover { color: #ceccc4; } .warning { /* box-shadow: 0px 0px 13px -1px rgba(230,33,66,0.7); */ color: rgba(230, 33, 66, 0.7) !important; border: 1px solid rgba(230, 33, 66, 0.7); } .warning:hover { /* box-shadow: 0px 0px 13px -1px rgba(230,33,66,0.7); */ color: rgba(230, 33, 66, 0.7) !important; border: 1px solid rgba(230, 33, 66, 0.7); } .warning-sign { position: fixed; margin-top: 7px; margin-left: 5px; } <|start_filename|>LeagueToolkit/package.json<|end_filename|> { "name": "leaguetoolkit", "version": "0.4.1", "description": "A pack of enhancements for the new league client!", "main": "app.js", "scripts": { "package-win": "electron-packager . LeagueToolkit --overwrite --platform=win32 --arch=ia32 --prune=true --out=release-builds --icon=images/icon.ico", "test": "echo \"Error: no test specified\" && exit 1" }, "author": "4dams", "contributors": [ "PurgePJ <<EMAIL>>" ], "license": "MIT", "dependencies": { "electron": "^2.0.0", "electron-open-link-in-browser": "^1.0.2", "lcu-connector": "^1.0.2", "request": "^2.85.0" } } <|start_filename|>LeagueToolkit/app/browser.js<|end_filename|> // // Copyright (c) 2018 by 4dams. All Rights Reserved. // var currentVersion = "0.4.1"; var gameVersion; var repository = "https://github.com/4dams/LeagueToolkit"; const electron = require('electron') const { ipcRenderer } = electron var isActive var level; var icon; var summoner; var selectedTier = "UNRANKED" var selectedDivision = "V" var selectedLevel function tierChange() { tier = document.getElementById("tier").value selectedTier = tier } function divisionChange() { division = document.getElementById("division").value selectedDivision = division } function submitTierDivison() { if (selectedTier == "GOTCHA") { selectedDivision = ""; } else { division = document.getElementById("division").value; selectedDivision = division; } ipcRenderer.send('submitTierDivison', selectedTier, selectedDivision); } function submitLeagueName() { leagueName = document.getElementById("leagueName").value; ipcRenderer.send('submitLeagueName', leagueName); } let submitedLevel; function submitLevel() { level = document.getElementById("level").value; ipcRenderer.send('submitLevel', level); document.getElementById("profileLevel").innerHTML = level; } var bold_italics = { a: '\u{1d622}', b: '\u{1d623}', c: '\u{1d624}', d: '\u{1d625}', e: '\u{1d626}', f: '\u{1d627}', g: '\u{1d628}', h: '\u{1d629}', i: '\u{1d62a}', j: '\u{1d62b}', k: '\u{1d62c}', l: '\u{1d62d}', m: '\u{1d62e}', n: '\u{1d62f}', o: '\u{1d630}', p: '\u{1d631}', q: '\u{1d632}', r: '\u{1d633}', s: '\u{1d634}', t: '\u{1d635}', u: '\u{1d636}', v: '\u{1d637}', w: '\u{1d638}', x: '\u{1d639}', y: '\u{1d63a}', z: '\u{1d63b}', A: '\u{1d608}', B: '\u{1d609}', C: '\u{1d60a}', D: '\u{1d60b}', E: '\u{1d60c}', F: '\u{1d60d}', G: '\u{1d60e}', H: '\u{1d60f}', I: '\u{1d610}', J: '\u{1d611}', K: '\u{1d612}', L: '\u{1d613}', M: '\u{1d614}', N: '\u{1d615}', O: '\u{1d616}', P: '\u{1d617}', Q: '\u{1d618}', R: '\u{1d619}', S: '\u{1d61a}', T: '\u{1d61b}', U: '\u{1d61c}', V: '\u{1d61d}', W: '\u{1d61e}', X: '\u{1d61f}', Y: '\u{1d620}', Z: '\u{1d621}' } var italics = { a: '\u{1d622}', b: '\u{1d623}', c: '\u{1d624}', d: '\u{1d625}', e: '\u{1d626}', f: '\u{1d627}', g: '\u{1d628}', h: '\u{1d629}', i: '\u{1d62a}', j: '\u{1d62b}', k: '\u{1d62c}', l: '\u{1d62d}', m: '\u{1d62e}', n: '\u{1d62f}', o: '\u{1d630}', p: '\u{1d631}', q: '\u{1d632}', r: '\u{1d633}', s: '\u{1d634}', t: '\u{1d635}', u: '\u{1d636}', v: '\u{1d637}', w: '\u{1d638}', x: '\u{1d639}', y: '\u{1d63a}', z: '\u{1d63b}', A: '\u{1d608}', B: '\u{1d609}', C: '\u{1d60a}', D: '\u{1d60b}', E: '\u{1d60c}', F: '\u{1d60d}', G: '\u{1d60e}', H: '\u{1d60f}', I: '\u{1d610}', J: '\u{1d611}', K: '\u{1d612}', L: '\u{1d613}', M: '\u{1d614}', N: '\u{1d615}', O: '\u{1d616}', P: '\u{1d617}', Q: '\u{1d618}', R: '\u{1d619}', S: '\u{1d61a}', T: '\u{1d61b}', U: '\u{1d61c}', V: '\u{1d61d}', W: '\u{1d61e}', X: '\u{1d61f}', Y: '\u{1d620}', Z: '\u{1d621}' } var bold = { a: '\u{1d5ee}', b: '\u{1d5ef}', c: '\u{1d5f0}', d: '\u{1d5f1}', e: '\u{1d5f2}', f: '\u{1d5f3}', g: '\u{1d5f4}', h: '\u{1d5f5}', i: '\u{1d5f6}', j: '\u{1d5f7}', k: '\u{1d5f8}', l: '\u{1d5f9}', m: '\u{1d5fa}', n: '\u{1d5fb}', o: '\u{1d5fc}', p: '\u{1d5fd}', q: '\u{1d5fe}', r: '\u{1d5ff}', s: '\u{1d600}', t: '\u{1d601}', u: '\u{1d602}', v: '\u{1d603}', w: '\u{1d604}', x: '\u{1d605}', y: '\u{1d606}', z: '\u{1d607}', A: '\u{1d5d4}', B: '\u{1d5d5}', C: '\u{1d5d6}', D: '\u{1d5d7}', E: '\u{1d5d8}', F: '\u{1d5d9}', G: '\u{1d5da}', H: '\u{1d5db}', I: '\u{1d5dc}', J: '\u{1d5dd}', K: '\u{1d5de}', L: '\u{1d5df}', M: '\u{1d5e0}', N: '\u{1d5e1}', O: '\u{1d5e2}', P: '\u{1d5e3}', Q: '\u{1d5e4}', R: '\u{1d5e5}', S: '\u{1d5e6}', T: '\u{1d5e7}', U: '\u{1d5e8}', V: '\u{1d5e9}', W: '\u{1d5ea}', X: '\u{1d5eb}', Y: '\u{1d5ec}', Z: '\u{1d5ed}' } function submitStatus() { status = document.getElementById("status").value; let length = status.length; let result = new Array(length); let status_converted; if (document.getElementById("italics").checked && document.getElementById("bold").checked) { // 𝑎𝑏𝑐𝑑𝑒𝑓𝑔ℎ𝑖𝑗𝑘𝑙𝑚𝑛𝑜𝑝𝑞𝑟𝑠𝑡𝑢𝑣𝑤𝑥𝑦𝑧 𝐴𝐵𝐶𝐷𝐸𝐹𝐺𝐻𝐼𝐽𝐾𝐿𝑀𝑁𝑂𝑃𝑄𝑅𝑆𝑇𝑈𝑉𝑊𝑋𝑌𝑍 for (let i = 0; i < length; i++) { let c = status.charAt(i) let r = bold_italics[c] result[i] = r != undefined ? r : c } status_converted = result.join('') } else if (document.getElementById("italics").checked) { // 𝑎𝑏𝑐𝑑𝑒𝑓𝑔ℎ𝑖𝑗𝑘𝑙𝑚𝑛𝑜𝑝𝑞𝑟𝑠𝑡𝑢𝑣𝑤𝑥𝑦𝑧 𝐴𝐵𝐶𝐷𝐸𝐹𝐺𝐻𝐼𝐽𝐾𝐿𝑀𝑁𝑂𝑃𝑄𝑅𝑆𝑇𝑈𝑉𝑊𝑋𝑌𝑍 for (let i = 0; i < length; i++) { let c = status.charAt(i) let r = italics[c] result[i] = r != undefined ? r : c } status_converted = result.join('') } else if (document.getElementById("bold").checked) { // 𝗮𝗯𝗰𝗱𝗲𝗳𝗴𝗵𝗶𝗷𝗸𝗹𝗺𝗻𝗼𝗽𝗾𝗿𝘀𝘁𝘂𝘃𝘄𝘅𝘆𝘇 𝗔𝗕𝗖𝗗𝗘𝗙𝗚𝗛𝗜𝗝𝗞𝗟𝗠𝗡𝗢𝗣𝗤𝗥𝗦𝗧𝗨𝗩𝗪𝗫𝗬𝗭 for (let i = 0; i < length; i++) { let c = status.charAt(i) let r = bold[c] result[i] = r != undefined ? r : c } status_converted = result.join('') } else { status_converted = status } ipcRenderer.send('submitStatus', status_converted) } function submitAvailability() { availability = document.getElementById("availability").value ipcRenderer.send('submitAvailability', availability) } function submitSummoner() { summoner = document.getElementById("summoner").value; ipcRenderer.send('submitSummoner', summoner); document.getElementById("profileName").innerHTML = summoner; } function submitLobby() { queueId = document.getElementById("queueId").value lobbyMembers = document.getElementById("lobbyMembers").value.split(" ") if (lobbyMembers) { processedMembers = lobbyMembers } else { processedMembers = [] } ipcRenderer.send('submitLobby', queueId, processedMembers) } function submitIcon() { icon = document.getElementById("icon").value; ipcRenderer.send('submitIcon', icon); document.getElementById("profileSummonerIcon").src = "http://ddragon.leagueoflegends.com/cdn/" + gameVersion + "/img/profileicon/" + (icon) + ".png"; } function submitWinsLosses() { wins = document.getElementById("wins").value losses = document.getElementById("losses").value ipcRenderer.send('submitWinsLosses', wins, losses); } function eventReset() { ipcRenderer.send('reset'); } function exit_app() { ipcRenderer.send('exit_app'); } function minimize_app() { ipcRenderer.send('minimize_app'); } let clientIcon; async function profileUpdate() { let data; try { data = ipcRenderer.sendSync("profileUpdate"); if (!data) return; if (clientIcon) { if (clientIcon !== data.iconID) { document.getElementById("profileSummonerIcon").src = "http://ddragon.leagueoflegends.com/cdn/" + gameVersion + "/img/profileicon/" + data.iconID + ".png"; clientIcon = data.iconID; } } else { clientIcon = data.iconID; let rankedTier = data.rankedTier || document.getElementById("profileRankedTier").innerHTML || "Not logged in."; let leagueName = data.leagueName || document.getElementById("profileLeagueName").innerHTML || ""; let profileLevel = (data.level) || document.getElementById("profileWL").innerHTML || ""; document.getElementById("profileName").innerHTML = summoner || data.name; document.getElementById("profileRankedTier").innerHTML = rankedTier != "undefined" ? rankedTier : "Unranked"; document.getElementById("profileLeagueName").innerHTML = leagueName != "undefined" ? leagueName : "Unranked"; document.getElementById("profileLevel").innerHTML = level || profileLevel; document.getElementById("profileSummonerIcon").src = "http://ddragon.leagueoflegends.com/cdn/" + gameVersion + "/img/profileicon/" + (icon || data.iconID || "1") + ".png"; } } catch (e) { console.log("And error occured updating the profile information: " + e); } } /* SECTIONS */ function openTab(evt, tabName) { // Declare all variables var i, tabcontent, tablinks if (tabName == "Home") { document.getElementById("selected").style.marginLeft = "0px" } if (tabName == "Profile") { document.getElementById("selected").style.marginLeft = "120px" } if (tabName == "Champ Select") { document.getElementById("selected").style.marginLeft = "278px" } if (tabName == "Miscellaneous") { document.getElementById("selected").style.marginLeft = "473px" } // Get all elements with class="tabcontent" and hide them tabcontent = document.getElementsByClassName("tabcontent") for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none" } // Get all elements with class="tablinks" and remove the class "active" tablinks = document.getElementsByClassName("tablinks") for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", "") } // Show the current tab, and add an "active" class to the button that opened the tab document.getElementById(tabName).style.display = "block" evt.currentTarget.className += " active" } // Event listeners function autoUpdate() { isActive = true setTimeout(function() { setInterval(function() { if (!isActive) return profileUpdate() }, 5000) profileUpdate(); }, 2000) } window.addEventListener("load", autoUpdate, false) window.onfocus = function() { isActive = true } window.onblur = function() { isActive = false } function toggleAutoAccept(element) { if (element.checked) { ipcRenderer.send('autoAccept', true) } else { ipcRenderer.send('autoAccept', false) } } function toggleInvDecline(element) { if (element.checked) { ipcRenderer.send('invDecline', true) } else { ipcRenderer.send('invDecline', false) } } ipcRenderer.send('requestVersionCheck') setInterval(function() { ipcRenderer.send('requestVersionCheck') }, 30000) function openGithub() { ipcRenderer.send('openGitRepository'); } ipcRenderer.on('versions', (event, appVersion, leagueGameVersion) => { gameVersion = leagueGameVersion; let versionElement = document.getElementById("version-tag"); if (appVersion == currentVersion) { versionElement.innerHTML = "V" + currentVersion + " (latest)"; } else if (appVersion > currentVersion) { versionElement.innerHTML = "V" + currentVersion + " (update available)"; } else if (appVersion < currentVersion) { versionElement.innerHTML = "V" + currentVersion + " (beta)"; } }) function saveIgnored() { let ignored = document.getElementById("ignored").value let names = ignored.split(", ") ipcRenderer.send('saveIgnored', names) } setInterval(function() { if (level) { ipcRenderer.send('submitLevel', level); } }, 20000) <|start_filename|>LeagueToolkit/src/summoner.js<|end_filename|> class summoner { constructor(data, APIRoutes) { // Modules this.request = require("request"); // class data if (!this.IsJsonString(data)) return; data = JSON.parse(data) this.APIRoutes = APIRoutes; this.level = this.level || data.summonerLevel; this.name = this.name || data.displayName; this.ID = this.ID || data.summonerId; this.iconID = this.iconID || data.profileIconId; this.getRankedStats(); } compareRanks(r1, r2) { let highestRank; let leagues = { "BRONZE" : 1, "SILVER" : 2, "GOLD" : 3, "PLATINUM" : 4, "DIAMOND" : 5, "MASTER" : 6, "CHALLENGER" : 7 }; let league1 = leagues[r1.rankedTier], league2 = leagues[r2.rankedTier]; if (league1 > league2) { highestRank = r1; } else if (league2 > league1) { highestRank = r2; } else { // same league if (r1.division < r2.division) { // r1 is higher (diamond 1 higher than diamond 5) highestRank = r1; } else if (r1.division > r2.division) { highestRank = r2; } else { // same division if (r1.lp > r2.lp) { highestRank = r1; } else { highestRank = r2; } } } return highestRank; } getHighestRank(ranks) { let highestRank; for (let i = 0; i < ranks.length; i++) { let rankedData = ranks[i]; let division = rankedData.division; let leagueName = rankedData.leagueName; if (!highestRank) highestRank = rankedData; highestRank = this.compareRanks(highestRank, rankedData); } return highestRank; } receivedRankedStats(data) { let rankedData = this.getHighestRank(data.rankedData); if (rankedData) { // Checking if summoner is unranked this.division = this.returnRomanDivision(rankedData.division); this.wins = rankedData.wins; this.rankedTier = rankedData.rankedTier; this.leagueName = rankedData.leagueName; this.rankedQueue = rankedData.rankedQueue; this.lp = rankedData.lp; } } IsJsonString(str) { try { JSON.parse(str); } catch (e) { return false; } return true; } getProfileData() { let arr = { name: this.name, iconID: this.iconID, leagueName: this.leagueName, leagueWins: this.wins, rankedTier: this.rankedTier + " " + this.division, level: this.level } return arr } getRankedStats() { let rankedUrl = this.APIRoutes.Route("getRankedStats", this.ID); let body = { url: rankedUrl, "rejectUnauthorized": false, headers: { Authorization: this.APIRoutes.getAuth() } }; let callback = (error, response, body) => { if (!response) return; if (response.statusCode == 200) { body = JSON.parse(body); this.receivedRankedStats(body); } } this.request.get(body, callback); } returnRomanDivision(division) { division.toString(); if (division == "1") return "I"; if (division == "2") return "II"; if (division == "3") return "III"; if (division == "4") return "IV"; if (division == "5") return "V"; return ""; } reset() { console.log("Starting reset.") let url = this.APIRoutes.Route("reset"); let body = { url: url, "rejectUnauthorized": false, headers: { Authorization: this.APIRoutes.getAuth() }, json: { "availability": "chat", "icon": this.iconID, "id": this.ID, "lastSeenOnlineTimestamp": (new Date().getTime()).toString(), "lol": { "level": this.level.toString(), "mapId": "", "rankedLeagueDivision": this.returnRomanDivision(this.division), "rankedLeagueName": this.leagueName, "rankedLeagueQueue": this.rankerQueue, "rankedLeagueTier": this.rankedTier, "rankedLosses": "0", "rankedWins": this.wins.toString() }, "name": this.name // "statusMessage": "Most dedicated support player EUW!" } } let callback = function(error, response, body) { // console.log('error:', error); // console.log('statusCode:', response && response.statusCode); // console.log('body:', body); }; this.request.put(body, callback); } } module.exports = summoner; <|start_filename|>LeagueToolkit/app.js<|end_filename|> // // Copyright (c) 2018 by 4dams. All Rights Reserved. // var electron = require('electron') var url = require('url') var path = require('path') var request = require('request') var LCUConnector = require('lcu-connector') var connector = new LCUConnector() var APIClient = require("./src/routes") var Summoner = require("./src/summoner") var LocalSummoner var routes // Setting default settings var autoAccept_enabled = false var invDecline_enabled = false var ignoredDeclines = [] // Extracting some stuff from electron const { app, BrowserWindow, Menu, ipcMain } = electron // Defining global variables let mainWindow let addWindow var userAuth var passwordAuth var requestUrl var clientFound = false; function getLocalSummoner() { if (!routes) { console.log("League of Legends client not found."); } else { let url = routes.Route("localSummoner") let body = { url: url, "rejectUnauthorized": false, headers: { Authorization: routes.getAuth() } } let callback = function(error, response, body) { LocalSummoner = new Summoner(body, routes) } request.get(body, callback) } } connector.on('connect', (data) => { requestUrl = data.protocol + '://' + data.address + ':' + data.port routes = new APIClient(requestUrl, data.username, data.password) getLocalSummoner() userAuth = data.username passwordAuth = data.password console.log('Request base url set to: ' + routes.getAPIBase()) clientFound = true; }) // Listen for the app to be ready app.on('ready', function() { // Creating main window of the app mainWindow = new BrowserWindow({ width: 1280, height: 720, frame: false, resizable: false, movable: true, icon: path.join(__dirname, 'images/icon.png') }) // Load HTML file into the window mainWindow.loadURL(url.format({ pathname: path.join(__dirname, './app/index.html'), protocol: 'file:', slashes: true })) // Building Menu from template const mainMenu = Menu.buildFromTemplate(mainMenuTemplate) // Loading the menu to overwrite developer tools Menu.setApplicationMenu(mainMenu) }) // Menu template const mainMenuTemplate = [{ label: 'File', submenu: [] }] app.on('window-all-closed', () => { app.quit() }) ipcMain.on('reset', function() { LocalSummoner.reset() }) ipcMain.on('exit_app', function() { app.quit() }) ipcMain.on('minimize_app', function() { mainWindow.minimize() }) ipcMain.on('submitTierDivison', (event, tier, division) => { if (!routes) return; let url = routes.Route("submitTierDivison") let body = { url: url, "rejectUnauthorized": false, headers: { Authorization: routes.getAuth() }, json: { "lol": { "rankedLeagueTier": tier, "rankedLeagueDivision": division } } } request.put(body) }) ipcMain.on('submitLevel', (event, level) => { if (!routes) return; let url = routes.Route("submitLevel") let body = { url: url, "rejectUnauthorized": false, headers: { Authorization: routes.getAuth() }, json: { "lol": { "level": level.toString() } } } request.put(body) }) ipcMain.on('submitStatus', (event, status) => { if (!routes) return; let url = routes.Route("submitStatus") let body = { url: url, "rejectUnauthorized": false, headers: { Authorization: routes.getAuth() }, json: { "statusMessage": status } } request.put(body) }) ipcMain.on('submitLeagueName', (event, leagueName) => { if (!routes) return; let url = routes.Route("submitLeagueName") let body = { url: url, "rejectUnauthorized": false, headers: { Authorization: routes.getAuth() }, json: { "lol": { "rankedLeagueName": leagueName } } } request.put(body) }) ipcMain.on('submitAvailability', (event, availability) => { if (!routes) return; let url = routes.Route("submitAvailability") let body = { url: url, "rejectUnauthorized": false, headers: { Authorization: routes.getAuth() }, json: { "availability": availability } } request.put(body) }) ipcMain.on('submitIcon', (event, icon) => { if (!routes) return; let url = routes.Route("submitIcon") let body = { url: url, "rejectUnauthorized": false, headers: { Authorization: routes.getAuth() }, json: { "icon": icon } } request.put(body) }) ipcMain.on('submitSummoner', (event, name) => { if (!routes) return; let url = routes.Route("submitSummoner") let body = { url: url, "rejectUnauthorized": false, headers: { Authorization: routes.getAuth() }, json: { "name": name } } request.put(body, ) }) ipcMain.on('submitWinsLosses', (event, wins, losses) => { if (!routes) return; let url = routes.Route("submitWinsLosses") let body = { url: url, "rejectUnauthorized": false, headers: { Authorization: routes.getAuth() }, json: { "lol": { "rankedWins": wins.toString(), "rankedLosses": losses.toString() } } } request.put(body) }) ipcMain.on('profileUpdate', (event, wins, losses) => { getLocalSummoner() if (!LocalSummoner) return; event.returnValue = LocalSummoner.getProfileData() }) ipcMain.on('autoAccept', (event, int) => { if (int) { autoAccept_enabled = true } else { autoAccept_enabled = false } }) ipcMain.on('invDecline', (event, int) => { if (int) { invDecline_enabled = true } else { invDecline_enabled = false } }) function IsJsonString(str) { try { JSON.parse(str) } catch (e) { return false } return true } ipcMain.on('submitLobby', (event, queueId, members) => { if (!routes) return; let url = routes.Route("submitSummoner") let body = { url: url, "rejectUnauthorized": false, headers: { Authorization: routes.getAuth() }, json: { "lol": { "pty": "{\"partyId\":\"404debc0-91a0-4b62-9335-aae99e6d8b48\",\"queueId\":" + queueId + ",\"summoners\":" + members + "}", } } } request.put(body) }) var autoAccept = function() { setInterval(function() { if (!routes) return; let url = routes.Route("autoAccept") let body = { url: url, "rejectUnauthorized": false, headers: { Authorization: routes.getAuth() }, } let callback = function(error, response, body) { if (!body || !IsJsonString(body)) return var data = JSON.parse(body) if (data["state"] === "InProgress") { if (data["playerResponse"] === "None") { let acceptUrl = routes.Route("accept") let acceptBody = { url: acceptUrl, "rejectUnauthorized": false, headers: { Authorization: routes.getAuth() }, json: {} } let acceptCallback = function(error, response, body) {} if (autoAccept_enabled) { request.post(acceptBody, acceptCallback) } } } } request.get(body, callback) }, 1000) } function autoDecline() { setInterval(function() { if (!routes) return let url = routes.Route("invDecline") let body = { url: url, "rejectUnauthorized": false, headers: { Authorization: routes.getAuth() }, } let callback = function(error, response, body) { if (!body || !IsJsonString(body)) return var data = JSON.parse(body) if (data.length > 0) { if (typeof data[0].invitationId !== 'undefined') { if (!ignoredDeclines.includes(data[0].fromSummonerName)) { let declineUrl = routes.Route("invDecline") + "/" + data[0].invitationId + "/decline" let declineBody = { url: declineUrl, "rejectUnauthorized": false, headers: { Authorization: routes.getAuth() }, json: {} } if (invDecline_enabled) { request.post(declineBody) } } } } } request.get(body, callback) }, 500) } autoAccept() autoDecline() ipcMain.on('saveIgnored', (event, names) => { ignoredDeclines = names }) ipcMain.on('requestVersionCheck', (event) => { request('https://raw.githubusercontent.com/4dams/LeagueToolkit/master/LeagueToolkit/version.json', (error, response, body) => { var data = JSON.parse(body) event.sender.send('versions', data["toolkit-version"], data["game-version"]) }) }) var searchClient = setInterval(function() { if (clientFound) { clearInterval(searchClient); } connector.start(); }, 5000) connector.start();
4dams/LeagueToolkit
<|start_filename|>src/lib/wapi/functions/send-buttons.js<|end_filename|> /* NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM mMMMMMMMMMNNNmmNNNMMNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM mmNMMNMMMMNNNNNmmmddhdddNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM mddNMMNy:/odNmmddmmNNmdhhddmNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM NmmdNMNd:--+dNmmddhhddmmhsyhhmdmmNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM NmNmdNmy:.-oyNmmmhmdhho+sososyhhhddNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM NmmNdh+-`.:oyNNdmmdmmdo-://oysssyhhhdmNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM Nmmmoyyyo+osdNmdmmddNNhs+/::/+osyssydyhdNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM NNmhsymMMNmmmmdmdNNddNmsso+++////ossssyyhdmNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM mhhhmNNMNNNhssshhmmddmmssyooooso/::+oysshhhhmMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM mmdhdddNNdyoosyhdmddmmmsoooooyysyys/::/oyyhhhyMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM mdddhddmhsooshdmdmdhhyyyysso/ooo+syhhs/-/+shyhMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM dyyhdmd+ososhdmdmyyhhhhhhhyo++o/+///+ohhso++sdMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM dhdmNNdsossyhmdmsydhssssyhhs/++o/o+//:++yhhy+/hNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM mdmNNNNmhysshddyshdyyy/oss+s::/:://++///++++/::hmNNNNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM NNMNNNmmNNdymNNhshdshdyhdysh+sy+-:++osssosss++yNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM NmNNNmdNNmNmmmNmyyddyyhdhydyohys/-oo+osssysyyohNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM mmNNNhdNmmNNmNMMNhyyhhhdhyyhmmyh+-/s+sysssyyhyydNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM mNMMMhdNdmMNMMMMMNNmdhdddmhdmmNho/-osoyyo++oyddhhNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM NMMMNmhNdNMNMNMMNmNNNmmmdyoohmhoyo::hsooo++oooydhymMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMNNNhmNNMmmNMNNmmmmdmmdyhhoyddddoo++yoyysooossyhsmMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMNNNmmNNNmdNdNmmddhhhdNNhsmNssdooo/dso++osyyysoymMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMNNNNmNNNNNmddmmNhshNmmmNmNMdhNsh/ohho++/:++MMNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MNNNMMNNNNmmmhhhhdyosdNmdmMMhoNmhdmys+ooo++/+MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM mmNNNMMNNNNmddmdoodmMMNmmNNhssdmNMMMNdNd/osomMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM NmNdhMNmNNMNmdNddohmMMNNNmdmdddNMMMMMMMMmMNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM NmNhmMmmmmNNmdNyoNMNmNmdhyyyhdhoyNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM NmdmMmmddddNmmdys+hmMMMmmhysssyy++dMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM NmdNMMdmdddmmNNyshmNNNNNNNdhhs+yy//dMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM NmNMMMdmdddmmMNysdmNNMMMNhhNdhs+y+/:mMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM mmNMMNhmmddNNNMdyydmMMMNdyshNhyoss+:/MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM NmNMMddmmmmNMNMNdsymNNmdhhdNMNdhsss+:yMMMMMMMMMMMMMMMMNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMdhmmmmmNMNNMmshNMMMmmMMMMMmNdyo+//NMMMMMMMMMMMMMMMhNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMmhmmmmmmNMMNNMyshdhhhyhNMMMMMMdhso+sMMMMMMMMMMMMMMMhmMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMmdmmmmmmmNMMMmNm+ys++oyyNMMMMMMNmmyyoyNMMMMMMMMMMMMMddMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM NmmmmmmmmmmmNMNNmNNyyo+/oohNMMMMMMMMdhhsshmMMMMMMMMMMMyNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM mmNNNNNNmmmmNMMNmmddNmmdhhdmMMMMMMMMMNddhssshmmNNNmmdhdMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM NNNNNNNNNNNNNNNNmNNNNMMMMMNomMMMMMMMMMNNmdhhyyyyyyyhdmMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM Nd+oNMMMMMMMmodo++++++++++m..yNMMMMMNo+mNMMmhssshdNMMNhNMMMMMMMMMMMddMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MN+ /NMMMMMm: d` -ssssss+`d. `+mMMMMN. dNm+:+syso//hNN--yNMMMMMMMd+`yMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMN+ /NMMMm: oM` +NMMMMMNdN. /`.yNMMN. dh.omMMMMMNy.oM- `:hNMMMm+. yMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMN/ /NMm: oNy` :sssmMMMMN. dh-`/mMN. d-/NMMMMMMMMy`m- y/`/dmo..o: yMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMN/ /m: +NNy. /yyyNMMMMN. dNNo`.yN- d.oNMMMMMMMMd d- mNh-`.`+mN/ yMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMN/ . +NMMN- oNMMMMMNdN. dMMMd:`/. ds.dNMMMMMMm::M- dMMNy/dMMN/ yMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMN/ +NMMMN- /yyyyyys d. dMMMMNo` dNy-+ymmmho-+NN- dMMMMMMMMN/ yMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMNyNMMMMN+::::::::::m+/mMMMMMMd: dMMNho///+ymMMN+/mMMMMMMMMNs/hMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMNMMMMMMMMMMMMMMMMMMMMMMMMMMMMNsmMMMMMMMMMMMMMMNNNNMMNNNMMNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNMMMMMMMMMMMMMMNMMNMNMMMNMMNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNMMNMNMMMNMMNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNNNNMMNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM */ /** * Send buttons reply * @param {string} to the numberid <EMAIL> * @param {string} title the titulo * @param {string} subtitle the subtitle * @param {array} buttons arrays */ export async function sendButtons(to, title, buttons, subtitle) { if (typeof title != 'string' || title.length === 0) { return WAPI.scope(to, true, 404, 'It is necessary to write a title!'); } if (typeof subtitle != 'string' || subtitle.length === 0) { return WAPI.scope(to, true, 404, 'It is necessary to write a subtitle!'); } if (Array.isArray(buttons) && buttons.length > 0) { for (let index in buttons) { if (typeof buttons[index] !== 'function') { if (!buttons[index].buttonText) { return WAPI.scope(to, true, 404, 'passed object buttonText'); } if (typeof buttons[index].buttonText !== 'object') { return WAPI.scope(to, true, 404, 'passed object value in buttonText'); } if (!buttons[index].buttonText.displayText) { return WAPI.scope(to, true, 404, 'passed object displayText'); } if (typeof buttons[index].buttonText.displayText !== 'string') { return WAPI.scope( to, true, 404, 'passed string value in displayText' ); } if (!buttons[index].buttonId) { buttons[index].buttonId = `id${index}`; } if (!buttons[index].type) { buttons[index].type = 1; } } } } const chat = await WAPI.sendExist(to); if (chat && chat.status != 404 && chat.id) { const newMsgId = await window.WAPI.getNewMessageId(chat.id._serialized); const fromwWid = await Store.MaybeMeUser.getMaybeMeUser(); const message = { id: newMsgId, ack: 0, from: fromwWid, to: chat.id, local: !0, self: 'out', t: parseInt(new Date().getTime() / 1000), isNewMsg: !0, type: 'chat', body: title, caption: title, content: title, footer: subtitle, isDynamicReplyButtonsMsg: true, isForwarded: false, isFromTemplate: false, invis: true, fromMe: false }; var obj = { dynamicReplyButtons: buttons }; Object.assign(message, obj); var result = ( await Promise.all(window.Store.addAndSendMsgToChat(chat, message)) )[1]; if (result === 'success' || result === 'OK') { return WAPI.scope(newMsgId, false, result, null); } else { return WAPI.scope(newMsgId, true, result, null); } } else { return chat; } } <|start_filename|>src/lib/wapi/functions/set-profile-pic.js<|end_filename|> export async function setProfilePic(obj, id) { if (!id) { id = await Store.MaybeMeUser.getMaybeMeUser(); } let base64 = 'data:image/jpeg;base64,'; return await Store.Profile.sendSetPicture( id._serialized, base64 + obj.b, base64 + obj.a ); } <|start_filename|>src/lib/wapi/listeners/add-on-participants-change.js<|end_filename|> /* NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM mMMMMMMMMMNNNmmNNNMMNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM mmNMMNMMMMNNNNNmmmddhdddNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM mddNMMNy:/odNmmddmmNNmdhhddmNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM NmmdNMNd:--+dNmmddhhddmmhsyhhmdmmNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM NmNmdNmy:.-oyNmmmhmdhho+sososyhhhddNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM NmmNdh+-`.:oyNNdmmdmmdo-://oysssyhhhdmNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM Nmmmoyyyo+osdNmdmmddNNhs+/::/+osyssydyhdNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM NNmhsymMMNmmmmdmdNNddNmsso+++////ossssyyhdmNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM mhhhmNNMNNNhssshhmmddmmssyooooso/::+oysshhhhmMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM mmdhdddNNdyoosyhdmddmmmsoooooyysyys/::/oyyhhhyMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM mdddhddmhsooshdmdmdhhyyyysso/ooo+syhhs/-/+shyhMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM dyyhdmd+ososhdmdmyyhhhhhhhyo++o/+///+ohhso++sdMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM dhdmNNdsossyhmdmsydhssssyhhs/++o/o+//:++yhhy+/hNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM mdmNNNNmhysshddyshdyyy/oss+s::/:://++///++++/::hmNNNNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM NNMNNNmmNNdymNNhshdshdyhdysh+sy+-:++osssosss++yNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM NmNNNmdNNmNmmmNmyyddyyhdhydyohys/-oo+osssysyyohNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM mmNNNhdNmmNNmNMMNhyyhhhdhyyhmmyh+-/s+sysssyyhyydNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM mNMMMhdNdmMNMMMMMNNmdhdddmhdmmNho/-osoyyo++oyddhhNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM NMMMNmhNdNMNMNMMNmNNNmmmdyoohmhoyo::hsooo++oooydhymMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMNNNhmNNMmmNMNNmmmmdmmdyhhoyddddoo++yoyysooossyhsmMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMNNNmmNNNmdNdNmmddhhhdNNhsmNssdooo/dso++osyyysoymMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMNNNNmNNNNNmddmmNhshNmmmNmNMdhNsh/ohho++/:++MMNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MNNNMMNNNNmmmhhhhdyosdNmdmMMhoNmhdmys+ooo++/+MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM mmNNNMMNNNNmddmdoodmMMNmmNNhssdmNMMMNdNd/osomMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM NmNdhMNmNNMNmdNddohmMMNNNmdmdddNMMMMMMMMmMNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM NmNhmMmmmmNNmdNyoNMNmNmdhyyyhdhoyNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM NmdmMmmddddNmmdys+hmMMMmmhysssyy++dMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM NmdNMMdmdddmmNNyshmNNNNNNNdhhs+yy//dMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM NmNMMMdmdddmmMNysdmNNMMMNhhNdhs+y+/:mMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM mmNMMNhmmddNNNMdyydmMMMNdyshNhyoss+:/MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM NmNMMddmmmmNMNMNdsymNNmdhhdNMNdhsss+:yMMMMMMMMMMMMMMMMNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMdhmmmmmNMNNMmshNMMMmmMMMMMmNdyo+//NMMMMMMMMMMMMMMMhNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMmhmmmmmmNMMNNMyshdhhhyhNMMMMMMdhso+sMMMMMMMMMMMMMMMhmMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMmdmmmmmmmNMMMmNm+ys++oyyNMMMMMMNmmyyoyNMMMMMMMMMMMMMddMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM NmmmmmmmmmmmNMNNmNNyyo+/oohNMMMMMMMMdhhsshmMMMMMMMMMMMyNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM mmNNNNNNmmmmNMMNmmddNmmdhhdmMMMMMMMMMNddhssshmmNNNmmdhdMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM NNNNNNNNNNNNNNNNmNNNNMMMMMNomMMMMMMMMMNNmdhhyyyyyyyhdmMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM Nd+oNMMMMMMMmodo++++++++++m..yNMMMMMNo+mNMMmhssshdNMMNhNMMMMMMMMMMMddMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MN+ /NMMMMMm: d` -ssssss+`d. `+mMMMMN. dNm+:+syso//hNN--yNMMMMMMMd+`yMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMN+ /NMMMm: oM` +NMMMMMNdN. /`.yNMMN. dh.omMMMMMNy.oM- `:hNMMMm+. yMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMN/ /NMm: oNy` :sssmMMMMN. dh-`/mMN. d-/NMMMMMMMMy`m- y/`/dmo..o: yMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMN/ /m: +NNy. /yyyNMMMMN. dNNo`.yN- d.oNMMMMMMMMd d- mNh-`.`+mN/ yMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMN/ . +NMMN- oNMMMMMNdN. dMMMd:`/. ds.dNMMMMMMm::M- dMMNy/dMMN/ yMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMN/ +NMMMN- /yyyyyys d. dMMMMNo` dNy-+ymmmho-+NN- dMMMMMMMMN/ yMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMNyNMMMMN+::::::::::m+/mMMMMMMd: dMMNho///+ymMMN+/mMMMMMMMMNs/hMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMNMMMMMMMMMMMMMMMMMMMMMMMMMMMMNsmMMMMMMMMMMMMMMNNNNMMNNNMMNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNMMMMMMMMMMMMMMNMMNMNMMMNMMNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNMMNMNMMMNMMNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNNNNMMNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM */ let groupParticpiantsEvents = {}; /** * Registers on participants change listener */ export function addOnParticipantsChange() { /** * Registers a callback to participant changes on a certain, specific group * @param groupId - string - The id of the group that you want to attach the callback to. * @param callback - function - Callback function to be called when a message acknowledgement changes. The callback returns 3 variables * @returns {boolean} */ window.WAPI.onParticipantsChanged = async function (groupId, callback) { return await window.WAPI.waitForStore(['Chat', 'Msg'], () => { const subtypeEvents = [ 'invite', 'add', 'remove', 'leave', 'promote', 'demote' ]; const chat = window.Store.Chat.get(groupId); //attach all group Participants to the events object as 'add' const metadata = window.Store.GroupMetadata.default.get(groupId); if (!groupParticpiantsEvents[groupId]) { groupParticpiantsEvents[groupId] = {}; metadata.participants.forEach((participant) => { groupParticpiantsEvents[groupId][participant.id.toString()] = { subtype: 'add', from: metadata.owner }; }); } let i = 0; chat.on('change:groupMetadata.participants', (_) => chat.on('all', (x, y) => { const { isGroup, previewMessage } = y; if ( isGroup && x === 'change' && previewMessage && previewMessage.type === 'gp2' && subtypeEvents.includes(previewMessage.subtype) ) { const { subtype, from, recipients } = previewMessage; const rec = recipients[0].toString(); if ( groupParticpiantsEvents[groupId][rec] && groupParticpiantsEvents[groupId][recipients[0]].subtype == subtype ) { //ignore, this is a duplicate entry // console.log('duplicate event') } else { //ignore the first message if (i == 0) { //ignore it, plus 1, i++; } else { groupParticpiantsEvents[groupId][rec] = { subtype, from }; //fire the callback // // previewMessage.from.toString() // x removed y // x added y callback({ by: from.toString(), action: subtype, who: recipients }); chat.off('all', this); i = 0; } } } }) ); return true; }); }; } <|start_filename|>src/lib/wapi/functions/check-chat.js<|end_filename|> export async function checkChat(id) { try { if ( typeof id === 'string' && (id.includes('@g.us') || id.includes('@c.us') || id.includes('@broadcast')) ) { const chat = await Store.Chat.get(id); if (!!chat && chat.t) { return WAPI.scope( undefined, false, 200, null, WAPI._serializeChatObj(chat) ); } else { throw 404; } } else { throw 400; } } catch (e) { return WAPI.scope(undefined, true, e, 'Was not found'); } } <|start_filename|>src/lib/wapi/store/get-store.js<|end_filename|> const { storeObjects } = require('./store-objects'); export async function getStore(modules) { let foundCount = 0; let neededObjects = storeObjects; for (let idx in modules) { if (typeof modules[idx] === 'object' && modules[idx] !== null) { neededObjects.forEach((needObj) => { if (!needObj.conditions || needObj.foundedModule) return; let neededModule = needObj.conditions(modules[idx]); if (neededModule !== null) { foundCount++; needObj.foundedModule = neededModule; } }); if (foundCount == neededObjects.length) { break; } } } let neededStore = neededObjects.find((needObj) => needObj.id === 'Store'); window.Store = neededStore.foundedModule ? neededStore.foundedModule : {}; neededObjects.splice(neededObjects.indexOf(neededStore), 1); neededObjects.forEach((needObj) => { if (needObj.foundedModule) { window.Store[needObj.id] = needObj.foundedModule; } }); window.Store.sendMessage = function (e) { return window.Store.SendTextMsgToChat(this, ...arguments); }; window.Store.Chat.modelClass.prototype.sendMessage = function (e) { window.Store.SendTextMsgToChat(this, ...arguments); }; if (window.Store.MediaCollection) window.Store.MediaCollection.prototype.processFiles = window.Store.MediaCollection.prototype.processFiles || window.Store.MediaCollection.prototype.processAttachments; Store.Chat._findAndParse = Store.BusinessProfile._findAndParse; Store.Chat._find = Store.BusinessProfile._find; return window.Store; } <|start_filename|>.vscode/settings.json<|end_filename|> { "files.eol": "\n", "[javascript]": { "editor.defaultFormatter": "vscode.typescript-language-features" }, "[typescript]": { "editor.defaultFormatter": "vscode.typescript-language-features" }, "compile-hero.disable-compile-files-on-did-save-code": false }
iamatulsingh/venom
<|start_filename|>package.json<|end_filename|> { "name": "youtube-notion-apis", "version": "1.0.0", "description": "Experimenting with YouTube and Notion APIs", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+https://github.com/shiffman/YouTube-Notion-APIs.git" }, "author": "", "license": "ISC", "bugs": { "url": "https://github.com/shiffman/YouTube-Notion-APIs/issues" }, "homepage": "https://github.com/shiffman/YouTube-Notion-APIs#readme", "dependencies": { "@notionhq/client": "^0.1.8", "dotenv": "^10.0.0", "google-auth-library": "^7.1.0", "googleapis": "^74.2.0", "readline": "^1.3.0" } } <|start_filename|>index.js<|end_filename|> const { Client } = require('@notionhq/client'); require('dotenv').config(); const notion = new Client({ auth: process.env.NOTION_TOKEN, }); const { google } = require('googleapis'); go(); async function getVideos() { const results = await google.youtube('v3').search.list({ key: process.env.YOUTUBE_TOKEN, part: 'snippet', channelId: 'UCvjgXvBlbQiydffZU7m1_aw', maxResults: 10, order: 'date', }); const { data } = results; return data.items; } async function go() { console.log('retrieving latest 50 videos...'); const videos = await getVideos(); for (let video of videos) { console.log( `retrieving stats for ${video.id.videoId} ${video.snippet.title}` ); const info = await google.youtube('v3').videos.list({ key: process.env.YOUTUBE_TOKEN, part: 'statistics', id: video.id.videoId, }); const { statistics } = info.data.items[0]; console.log( `Adding to notion: ${video.id.videoId} ${video.snippet.title}` ); await addVideo(video, statistics); } } async function addVideo(video, statistics) { const { videoId } = video.id; const { title } = video.snippet; const response = await notion.pages.create({ parent: { database_id: process.env.DATABASE_ID, }, properties: { Video: { title: [ { text: { content: `${title} (${videoId})`, }, }, ], }, // 'Video Title': { // text: { content: title }, // }, Views: { number: Number(statistics.viewCount), }, Likes: { number: Number(statistics.likeCount), }, Dislikes: { number: Number(statistics.dislikeCount), }, Comments: { number: Number(statistics.commentCount), }, }, }); }
shiffman/YouTube-Notion-APIs
<|start_filename|>package.json<|end_filename|> { "name": "react-gallery-carousel", "version": "0.2.4", "description": "Mobile-friendly Carousel with batteries included (supporting touch, mouse emulation, lazy loading, thumbnails, fullscreen, RTL, keyboard navigation and customisations).", "author": "yifaneye", "license": "MIT", "repository": "yifaneye/react-gallery-carousel", "main": "dist/index.js", "module": "dist/index.modern.js", "source": "src/index.js", "engines": { "node": ">=14" }, "scripts": { "build": "microbundle-crl --no-compress --format modern,cjs", "start": "microbundle-crl watch --no-compress --format modern,cjs", "prepare": "run-s build", "test": "run-s test:unit test:lint test:build", "test:build": "run-s build", "test:lint": "eslint .", "test:unit": "cross-env CI=1 react-scripts test --env=jsdom", "test:watch": "react-scripts test --env=jsdom", "predeploy": "cd example && yarn install && yarn run build", "deploy": "gh-pages -d example/build" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0" }, "devDependencies": { "babel-eslint": "^10.0.3", "cross-env": "^7.0.2", "eslint": "^6.8.0", "eslint-config-prettier": "^6.7.0", "eslint-config-standard": "^14.1.0", "eslint-config-standard-react": "^9.2.0", "eslint-plugin-import": "^2.18.2", "eslint-plugin-node": "^11.0.0", "eslint-plugin-prettier": "^3.1.1", "eslint-plugin-promise": "^4.2.1", "eslint-plugin-react": "^7.17.0", "eslint-plugin-react-hooks": "^4.2.0", "eslint-plugin-standard": "^4.0.1", "gh-pages": "^2.2.0", "microbundle-crl": "^0.13.10", "node-sass": "^5.0.0", "npm-run-all": "^4.1.5", "prettier": "^2.0.4", "prop-types": "^15.7.2", "react": "^16.13.1", "react-dom": "^16.13.1", "react-scripts": "^3.4.1", "react-test-renderer": "^17.0.1" }, "files": [ "dist" ], "dependencies": {}, "jest": { "moduleNameMapper": { "\\.(jpg)$": "<rootDir>/__mocks__/fileMock.js", "\\.(png)$": "<rootDir>/__mocks__/fileMock.js", "\\.(css)$": "<rootDir>/__mocks__/fileMock.js" } }, "keywords": [ "carousel", "gallery", "lightbox", "slider", "slideshow", "swiper", "react", "component", "lazy load", "preload", "touch", "swipe", "pinch", "zoom", "mouse", "mouse emulation", "drag", "keyboard navigation", "accessibility", "a11y" ] }
yifaneye/react-gallery-carousel
<|start_filename|>Sources/SuperCombinators.h<|end_filename|> // // SuperCombinators.h // SuperCombinators // // Created by <NAME> on 17/02/2017. // // #import <Foundation/Foundation.h> //! Project version number for SuperCombinators. FOUNDATION_EXPORT double SuperCombinatorsVersionNumber; //! Project version string for SuperCombinators. FOUNDATION_EXPORT const unsigned char SuperCombinatorsVersionString[];
snipsco/SuperCombinators
<|start_filename|>util.go<|end_filename|> package scraper import ( "bytes" "errors" "fmt" "log" "net/url" "regexp" "strings" "github.com/PuerkitoBio/goquery" ) var templateRe = regexp.MustCompile(`\{\{\s*(\w+)\s*(:(\w+))?\s*\}\}`) func template(isurl bool, str string, vars map[string]string) (out string, err error) { out = templateRe.ReplaceAllStringFunc(str, func(key string) string { m := templateRe.FindStringSubmatch(key) k := m[1] value, ok := vars[k] //missing - apply defaults or error if !ok { if m[3] != "" { value = m[3] } else { err = errors.New("Missing param: " + k) } } //determine if we need to escape if isurl { queryi := strings.Index(str, "?") keyi := strings.Index(str, key) if queryi != -1 && keyi > queryi { value = url.QueryEscape(value) } } return value }) return } func checkSelector(s string) (err error) { defer func() { if r := recover(); r != nil { err = fmt.Errorf("%v", r) } }() doc, _ := goquery.NewDocumentFromReader(bytes.NewBufferString(`<html> <body> <h3>foo bar</h3> </body> </html>`)) doc.Find(s) return } func jsonerr(err error) []byte { return []byte(`{"error":"` + err.Error() + `"}`) } func logf(format string, args ...interface{}) { log.Printf("[scraper] "+format, args...) }
fsyangjie/scraper
<|start_filename|>Building Secure Applications with Cryptography/PBKDF2/Program.cs<|end_filename|> /* MIT License Copyright (c) 2020 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. */ using System; using System.Diagnostics; using System.Text; namespace Pluralsight.PBKDF2 { static class Program { static void Main() { const string passwordToHash = "<PASSWORD>"; Console.WriteLine("Password Based Key Derivation Function Demonstration in .NET"); Console.WriteLine("------------------------------------------------------------"); Console.WriteLine(); Console.WriteLine("PBKDF2 Hashes"); Console.WriteLine(); HashPassword(passwordToHash, 100); HashPassword(passwordToHash, 1000); HashPassword(passwordToHash, 10000); HashPassword(passwordToHash, 50000); HashPassword(passwordToHash, 100000); HashPassword(passwordToHash, 200000); HashPassword(passwordToHash, 500000); Console.ReadLine(); } private static void HashPassword(string passwordToHash, int numberOfRounds) { var sw = new Stopwatch(); sw.Start(); var hashedPassword = PBKDF2.HashPassword(Encoding.UTF8.GetBytes(passwordToHash), PBKDF2.GenerateSalt(), numberOfRounds); sw.Stop(); Console.WriteLine(); Console.WriteLine("Password to hash : " + passwordToHash); Console.WriteLine("Hashed Password : " + Convert.ToBase64String(hashedPassword)); Console.WriteLine("Iterations <" + numberOfRounds + "> Elapsed Time : " + sw.ElapsedMilliseconds + "ms"); } } } <|start_filename|>Building Secure Applications with Cryptography/ProofOfWorkTest/Program.cs<|end_filename|> namespace BlockChainCourse.ProofOfWorkTest { class Program { static void Main(string[] args) { ProofOfWork pow0 = new ProofOfWork("Mary had a little lamb", 0); ProofOfWork pow1 = new ProofOfWork("Mary had a little lamb", 1); ProofOfWork pow2 = new ProofOfWork("Mary had a little lamb", 2); ProofOfWork pow3 = new ProofOfWork("Mary had a little lamb", 3); ProofOfWork pow4 = new ProofOfWork("Mary had a little lamb", 4); ProofOfWork pow5 = new ProofOfWork("Mary had a little lamb", 5); ProofOfWork pow6 = new ProofOfWork("Mary had a little lamb", 6); pow0.CalculateProofOfWork(); pow1.CalculateProofOfWork(); pow2.CalculateProofOfWork(); pow3.CalculateProofOfWork(); pow4.CalculateProofOfWork(); pow5.CalculateProofOfWork(); pow6.CalculateProofOfWork(); } } } <|start_filename|>Building Secure Applications with Cryptography/DES/Program.cs<|end_filename|> /* MIT License Copyright (c) 2020 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. */ using System; using System.Text; namespace Pluralsight.DES { static class Program { static void Main(string[] args) { var des = new DesEncryption(); var key = des.GenerateRandomNumber(8); var iv = des.GenerateRandomNumber(8); const string original = "Text to encrypt"; var encrypted = des.Encrypt(Encoding.UTF8.GetBytes(original), key, iv); var decrypted = des.Decrypt(encrypted, key, iv); var decryptedMessage = Encoding.UTF8.GetString(decrypted); Console.WriteLine("DES Encryption Demonstration in .NET"); Console.WriteLine("------------------------------------"); Console.WriteLine(); Console.WriteLine("Original Text = " + original); Console.WriteLine("Encrypted Text = " + Convert.ToBase64String(encrypted)); Console.WriteLine("Decrypted Text = " + decryptedMessage); Console.ReadLine(); } } }
stephenhaunts/Building-Secure-Applications-with-Cryptography-in-.NET-Course-Source-Code
<|start_filename|>jfugue-sample/src/main/java/jf05_rhythms/IntroToRhythms.java<|end_filename|> package jf05_rhythms; import org.jfugue.player.Player; import org.jfugue.rhythm.Rhythm; /* Introduction to Rhythms One of my favorite parts of the JFugue API is the ability to create rhythms in a fun and easily understandable way.The letters are mapped to percussive instrument sounds,like"Acoustic Snare"and"Closed Hi Hat".JFugue comes with a default"rhythm set",which is a Map<Character, String>with entries like this:put('O',"[BASS_DRUM]i"). */ public class IntroToRhythms { public static void main(String[] args){ Rhythm rhythm = new Rhythm().addLayer("O..oO...O..oOO..") .addLayer("..S...S...S...S.") .addLayer("````````````````") .addLayer("...............+"); new Player().play(rhythm.getPattern() .repeat(2)); } } <|start_filename|>jfugue-sample/src/main/java/jf03_chordprogressions/AdvancedChordProgressions.java<|end_filename|> package jf03_chordprogressions; import org.jfugue.player.Player; import org.jfugue.theory.ChordProgression; /* Advanced Chord Progressions You can do some pretty cool things with chord progressions. The methods below use $ to indicate an index into either the chord progression (in which case, the index points to the nth chord), or a specific chord (in which case the index points to the nth note of the chord). Underscore means "the whole thing". If you change the indexes, make sure you don't introduce an ArrayOutOfBoundsException (for example, a major chord has only three notes, so trying to get the 4th index, $3 (remember that this is zero-based), would cause an error). */ public class AdvancedChordProgressions { public static void main(String[] args){ ChordProgression cp = new ChordProgression("I IV V"); Player player = new Player(); player.play(cp.eachChordAs("$0q $1q $2q Rq")); player.play(cp.allChordsAs("$0q $0q $0q $0q $1q $1q $2q $0q")); player.play(cp.allChordsAs("$0 $0 $0 $0 $1 $1 $2 $0") .eachChordAs("V0 $0s $1s $2s Rs V1 $_q")); } } <|start_filename|>jfugue-sample/src/main/java/jf09_realtimeexample/RealtimeExample.java<|end_filename|> package jf09_realtimeexample; import org.jfugue.pattern.Pattern; import org.jfugue.realtime.RealtimePlayer; import org.jfugue.theory.Note; import java.util.Random; import java.util.Scanner; import javax.sound.midi.MidiUnavailableException; /* Play Music in Realtime Create interactive musical programs using the RealtimePlayer. */ public class RealtimeExample { private static Pattern[] PATTERNS = new Pattern[]{new Pattern("Cmajq Dmajq Emajq"), new Pattern("V0 Ei Gi Di Ci V1 Gi Ci Fi Ei"), new Pattern("V0 Cmajq V1 Gmajq")}; public static void main(String[] args) throws MidiUnavailableException{ RealtimePlayer player = new RealtimePlayer(); Random random = new Random(); Scanner scanner = new Scanner(System.in); boolean quit = false; while(quit == false){ System.out.print("Enter a '+C' to start a note, " + "'-C' to stop a note, 'i' for a random instrument, " + "'p' for a pattern, or 'q' to quit: "); String entry = scanner.next(); if(entry.startsWith("+")){ player.startNote(new Note(entry.substring(1))); } else if(entry.startsWith("-")){ player.stopNote(new Note(entry.substring(1))); } else if(entry.equalsIgnoreCase("i")){ player.changeInstrument(random.nextInt(128)); } else if(entry.equalsIgnoreCase("p")){ player.play(PATTERNS[random.nextInt(PATTERNS.length)]); } else if(entry.equalsIgnoreCase("q")){ quit = true; } } scanner.close(); player.close(); } } <|start_filename|>jfugue-sample/src/main/java/jf07_seemidi/SeeMidi.java<|end_filename|> package jf07_seemidi; import org.jfugue.midi.MidiFileManager; import org.jfugue.pattern.Pattern; import java.io.File; import java.io.IOException; import javax.sound.midi.InvalidMidiDataException; /* See the Contents of a MIDI File in Human-Readable and Machine-Parseable Staccato Format Want to see the music in your MIDI file?Of course,you could load it in a sheet music tool. Here's how you can load it with JFugue. You'll get a Pattern of your music,which you can then pick apart in interesting ways(for example,count how many"C"notes there are... that's coming up in a few examples) */ public class SeeMidi { public static void main(String[] args) throws IOException, InvalidMidiDataException{ String fileName = "PUT YOUR MIDI FILENAME HERE"; Pattern pattern = MidiFileManager.loadPatternFromMidi(new File(fileName)); System.out.println(pattern); } } <|start_filename|>jfugue-sample/src/main/java/jf02_patterns/IntroToPatterns2.java<|end_filename|> package jf02_patterns; import org.jfugue.pattern.Pattern; import org.jfugue.player.Player; /* Introduction to Patterns, Part 2 Voice and instruments for a pattern can also be set through the API. In JFugue, methods that would normally return 'void' instead return the object itself, which allows you do chain commands together, as seen in this example. */ public class IntroToPatterns2 { public static void main(String[] args){ Pattern p1 = new Pattern("Eq Ch. | Eq Ch. | Dq Eq Dq Cq").setVoice(0) .setInstrument("Piano"); Pattern p2 = new Pattern("Rw | Rw | GmajQQQ CmajQ").setVoice(1) .setInstrument("Flute"); Player player = new Player(); player.play(p1, p2); } } <|start_filename|>jfugue-sample/src/main/java/jf05_rhythms/AdvancedRhythms.java<|end_filename|> package jf05_rhythms; import org.jfugue.player.Player; import org.jfugue.rhythm.Rhythm; /* Advanced Rhythms Through the Rhythm API, you can specify a variety of alternate layers that occur once or recur regularly. You can even create your own "RhythmAltLayerProvider" if you'd like to create a new behavior that does not already exist in the Rhythm API. */ public class AdvancedRhythms { public static void main(String[] args){ Rhythm rhythm = new Rhythm() // .addLayer("O..oO...O..oOO..") // This is Layer 0 .addLayer("..S...S...S...S.") .addLayer("````````````````").addLayer("...............+") // This is Layer 3 .addOneTimeAltLayer(3, 3, "...+...+...+...+") // Replace Layer 3 with this string on the 4th (count from 0) measure .setLength(4); // Set the length of the rhythm to 4 measures new Player().play(rhythm.getPattern() .repeat(2)); // Play 2 instances of the 4-measure-long rhythm } } <|start_filename|>jfugue-sample/src/main/java/jf06_trythis/TryThis.java<|end_filename|> package jf06_trythis; import org.jfugue.player.Player; import org.jfugue.rhythm.Rhythm; import org.jfugue.theory.ChordProgression; /* All That, in One Line of Code? Try this. The main line of code even fits within the 140-character limit of a tweet. */ public class TryThis { public static void main(String[] args){ new Player().play(new ChordProgression("I IV vi V").eachChordAs("$_i $_i Ri $_i"), new Rhythm().addLayer("..X...X...X...XO")); } } <|start_filename|>jfugue-sample/src/main/java/jf03_chordprogressions/IntroToChordProgressions.java<|end_filename|> package jf03_chordprogressions; import org.jfugue.player.Player; import org.jfugue.theory.Chord; import org.jfugue.theory.ChordProgression; import org.jfugue.theory.Note; /* Introduction to Chord Progressions It's easy to create a Chord Progression in JFugue. You can then play it, or you can see the notes that comprise the any of the chords in the progression. */ public class IntroToChordProgressions { public static void main(String[] args){ ChordProgression cp = new ChordProgression("I IV V"); Chord[] chords = cp.setKey("C") .getChords(); for(Chord chord : chords){ System.out.print("Chord " + chord + " has these notes: "); Note[] notes = chord.getNotes(); for(Note note : notes){ System.out.print(note + " "); } System.out.println(); } Player player = new Player(); player.play(cp); } } <|start_filename|>jfugue-sample/src/main/java/DummyClass.java<|end_filename|> /** * Created by ersin on 23/03/15 at 4:03 PM */ public class DummyClass {} <|start_filename|>jfugue-sample/src/main/java/jf11_replacementmapdemo/CarnaticReplacementMapDemo.java<|end_filename|> package jf11_replacementmapdemo; import org.jfugue.player.Player; import org.staccato.ReplacementMapPreprocessor; import org.staccato.maps.CarnaticReplacementMap; /* Use "Replacement Maps" to Create Carnatic Music JFugue's ReplacementMap capability lets you use your own symbols in a music string. JFugue comes with a CarnaticReplacementMap that maps Carnatic notes to microtone frequencies. */ public class CarnaticReplacementMapDemo { public static void main(String[] args){ ReplacementMapPreprocessor.getInstance() .setReplacementMap(new CarnaticReplacementMap()); Player player = new Player(); player.play("<S> <R1> <R2> <R3> <R4>"); } } <|start_filename|>jfugue-sample/src/main/java/jf11_replacementmapdemo/SolfegeReplacementMapDemo.java<|end_filename|> package jf11_replacementmapdemo; import org.jfugue.pattern.Pattern; import org.jfugue.player.Player; import org.staccato.ReplacementMapPreprocessor; import org.staccato.maps.SolfegeReplacementMap; /* Use"Replacement Maps"to Play Solfege JFugue comes with a SolfegeReplacementMap,which means you can program music using "Do Re Me Fa So La Ti Do."The ReplacementMapParser converts those solfege tones to C D E F G A B.Using Replacement Maps,which are simply Map<String,String>,you can create any kind of music in a pattern that will be converted to musical notes (or whatever you put in the values of your Map). */ public class SolfegeReplacementMapDemo { public static void main(String[] args){ ReplacementMapPreprocessor rmp = ReplacementMapPreprocessor.getInstance(); rmp.setReplacementMap(new SolfegeReplacementMap()) .setRequireAngleBrackets(false); Player player = new Player(); player.play(new Pattern("do re mi fa so la ti do")); // This will play "C D E F G A B" // This next example brings back the brackets so durations can be added rmp.setRequireAngleBrackets(true); player.play(new Pattern("<Do>q <Re>q <Mi>h | <Mi>q <Fa>q <So>h | <So>q <Fa>q <Mi>h | <Mi>q <Re>q <Do>h")); } } <|start_filename|>jfugue-sample/src/main/java/jf10_temporalexample/TemporalExample.java<|end_filename|> package jf10_temporalexample; import org.jfugue.devtools.DiagnosticParserListener; import org.jfugue.player.Player; import org.jfugue.temporal.TemporalPLP; import org.staccato.StaccatoParser; /* Anticipate Musical Events Before They Occur You might imagine creating new types of ParserListeners,like an AnimationParserListener, that depend on knowing about the musical events before they happen.For example,perhaps your animation is of a robot playing a drum or strumming a guitar.Before the note makes a sound,the animation needs to get its virtual hands in the right place,so you might want a notice 500ms earlier that a musical event is about to happen.To bend time with JFugue, use a combination of the TemporalPLP class and Player.delayPlay(). delayPlay() creates a new thread that first waits the specified amount of time before playing. If you do this, make sure to call delayPlay() before plp.parse(). */ public class TemporalExample { private static final String MUSIC = "C D E F G A B"; private static final long TEMPORAL_DELAY = 500; public static void main(String[] args){ // Part 1. Parse the original music StaccatoParser parser = new StaccatoParser(); TemporalPLP plp = new TemporalPLP(); parser.addParserListener(plp); parser.parse(MUSIC); // Part 2. Send the events from Part 1, and play the original music with a delay DiagnosticParserListener dpl = new DiagnosticParserListener(); // Or your AnimationParserListener! plp.addParserListener(dpl); new Player().delayPlay(TEMPORAL_DELAY, MUSIC); plp.parse(); } } <|start_filename|>jfugue-sample/src/main/java/jf01_helloworld/HelloWorld2.java<|end_filename|> package jf01_helloworld; import org.jfugue.player.Player; /* Playing multiple voices, multiple instruments, rests, chords, and durations This example uses the Staccato 'V' command for specifing voices, 'I' for specifying instruments (text within brackets is looked up in a dictionary and maps to MIDI instrument numbers), '|' (pipe) for indicating measures (optional), durations including 'q' for quarter duration, 'qqq' for three quarter notes (multiple durations can be listed together), and 'h' for half, 'w' for whole, and '.' for a dotted duration; 'R' for rest, and the chords G-Major and C-Major. Whitespace is not significant and can be used for visually pleasing or helpful spacing. */ public class HelloWorld2 { public static void main(String[] args){ Player player = new Player(); player.play("V0 I[Piano] Eq Ch. | Eq Ch. | Dq Eq Dq Cq V1 I[Flute] Rw | Rw | GmajQQQ CmajQ"); } } <|start_filename|>jfugue-sample/src/main/java/jf04_twelvebarblues/TwelveBarBlues.java<|end_filename|> package jf04_twelvebarblues; import org.jfugue.pattern.Pattern; import org.jfugue.player.Player; import org.jfugue.theory.ChordProgression; import java.io.IOException; /* Twelve-Bar Blues in Two Lines of Code Twelve-bar blues uses a I-IV-V chord progression. But really, it's the Major 7ths that you'd like to hear... and if you want to play each chord in arpeggio, you need a 6th in there as well. But creating a I7%6-IV7%6-V7%6 chord progression is messy. So, this code creates a I-IV-V progression, then distributes a 7%6 across each chord, then creates the twelve bars, and then each chord is played as an arpeggio with note dynamics (note on velocity - how hard you hit the note). Finally, the pattern is played with an Acoustic_Bass instrument at 110 BPM. With all of the method chaining, that is kinda done in one line of code. */ public class TwelveBarBlues { public static void main(String[] args) throws IOException{ Pattern pattern = new ChordProgression("I IV V").distribute("7%6") .allChordsAs("$0 $0 $0 $0 $1 $1 $0 $0 $2 $1 $0 $0") .eachChordAs("$0ia100 $1ia80 $2ia80 $3ia80 $4ia100 $3ia80 $2ia80 $1ia80") .getPattern() .setInstrument("Acoustic_Bass") .setTempo(100); new Player().play(pattern); } } <|start_filename|>jfugue-sample/src/main/java/jf08_parserdemo/ParserDemo2.java<|end_filename|> package jf08_parserdemo; import org.jfugue.midi.MidiParser; import org.jfugue.parser.ParserListenerAdapter; import org.jfugue.theory.Note; import java.io.File; import java.io.IOException; import javax.sound.midi.InvalidMidiDataException; import javax.sound.midi.MidiSystem; /* Create a Listener to Find Out About Music You can create a ParserListener to listen for any musical event that any parser is parsing. Here, we'll create a simple tool that counts how many "C" notes (of any octave) are played in any song. */ public class ParserDemo2 { public static void main(String[] args) throws InvalidMidiDataException, IOException{ String fileName = "PUT A MIDI FILE HERE"; MidiParser parser = new MidiParser(); // Remember, you can use any Parser! MyParserListener listener = new MyParserListener(); parser.addParserListener(listener); parser.parse(MidiSystem.getSequence(new File(fileName))); System.out.println("There are " + listener.counter + " 'C' notes in this music."); } } class MyParserListener extends ParserListenerAdapter { public int counter; @Override public void onNoteParsed(Note note){ // A "C" note is in the 0th position of an octave if(note.getPositionInOctave() == 0){ counter++; } } } <|start_filename|>jfugue-sample/src/main/java/jf08_parserdemo/ParserDemo.java<|end_filename|> package jf08_parserdemo; import org.jfugue.midi.MidiParser; import org.jfugue.pattern.Pattern; import org.jfugue.player.Player; import org.staccato.StaccatoParserListener; import java.io.File; import java.io.IOException; import javax.sound.midi.InvalidMidiDataException; import javax.sound.midi.MidiSystem; /* Connecting Any Parser to Any ParserListener You can use JFugue to convert between music formats. Most commonly,JFugue is used to turn Staccato music into MIDI sound. Alternatively,you can play with the MIDI,MusicXML,and LilyPond parsers and listeners.Or,you can easily create your own parser or listener, and it will instantly interoperate with the other existing formats. (And if you convert to Staccato,you can then play the Staccato music...and edit it!) */ public class ParserDemo { public static void main(String[] args) throws InvalidMidiDataException, IOException{ String fileName = "PUT A MIDI FILE HERE"; MidiParser parser = new MidiParser(); StaccatoParserListener listener = new StaccatoParserListener(); parser.addParserListener(listener); parser.parse(MidiSystem.getSequence(new File(fileName))); Pattern staccatoPattern = listener.getPattern(); System.out.println(staccatoPattern); Player player = new Player(); player.play(staccatoPattern); } }
dmkoelle/jfugue
<|start_filename|>index.js<|end_filename|> var net = require("net"); var Service, Characteristic, Accessory, uuid; var inherits = require('util').inherits; var extend = require('util')._extend; /* Register the plugin with homebridge */ module.exports = function (homebridge) { Service = homebridge.hap.Service; Characteristic = homebridge.hap.Characteristic; Accessory = homebridge.hap.Accessory; uuid = homebridge.hap.uuid; var acc = ItachAccessory.prototype; inherits(ItachAccessory, Accessory); ItachAccessory.prototype.parent = Accessory.prototype; for (var mn in acc) { ItachAccessory.prototype[mn] = acc[mn]; } homebridge.registerPlatform("homebridge-globalcache-itach", "GlobalCacheItach", ItachPlatform); //homebridge.registerAccessory("homebridge-globalcache-itach", "GlobalCacheItach", ItachAccessory); } function ItachPlatform(log, config) { this.log = log; this.devices = config.devices; } ItachPlatform.prototype.errors = { "001": "Invalid command. Command not found.", "002": "Invalid module address (does not exist).", "003": "Invalid connector address (does not exist).", "004": "Invalid ID value.", "005": "Invalid frequency value.", "006": "Invalid repeat value.", "007": "Invalid offset value.", "008": "Invalid pulse count.", "009": "Invalid pulse data.", "010": "Uneven amount of on off statements.", "011": "No carriage return found.", "012": "Repeat count exceeded.", "013": "IR command sent to input connector.", "014": "Blaster command sent to non-blaster connector.", "015": "No carriage return before buffer full.", "016": "No carriage return.", "017": "Bad command syntax.", "018": "Sensor command sent to non-input connector.", "019": "Repeated IR transmission failure.", "020": "Above designated IR on off pair limit.", "021": "Symbol odd boundary.", "022": "Undefined symbol.", "023": "Unknown option.", "024": "Invalid baud rate setting.", "025": "Invalid flow control setting.", "026": "Invalid parity setting.", "027": "Settings are locked." }; ItachAccessory.prototype.errors = ItachPlatform.prototype.errors; ItachPlatform.prototype.accessories = function (callback) { if (Array.isArray(this.devices)) { var devicesProcessed = 0; for (var l = 0; l < this.devices.length; l++) { if (this.devices[l].enableLearnLogging) { this.sendSocketCommand(l, 'get_IRL', function (index, result) { }, true); } var results = []; this.sendSocketCommand(l, 'getdevices', function (index, result) { var currentDeviceConfig = this.devices[index]; var ports = result.split('\r'); if (ports.length > 2) { for (var i = 1; i < ports.length - 2; i++) { var portDetails = ports[i].split(','); if (portDetails.length != 3) { this.log("Can't handle iTach port: " + ports[i]); continue; } var portCountAndType = portDetails[2].split(' '); if (portCountAndType.length != 2) { this.log("Can't handle iTach device subtype: " + portDetails[2]); continue; } var portCount = parseInt(portCountAndType[0].trim()); var portType = portCountAndType[1].toLowerCase().trim(); this.log('Found ' + portCount + ' ' + portType + " ports."); for (var j = 0; j < portCount; j++) { var disable = false; if (currentDeviceConfig.ports && currentDeviceConfig.ports.length > j) { disable = currentDeviceConfig.ports[j].disable; } if (!disable) { results.push(new ItachAccessory(this.log, portType, currentDeviceConfig, j)); } } } devicesProcessed++; if (devicesProcessed == this.devices.length) { if (results.length == 0) { this.log("WARNING: No Accessories were loaded."); } callback(results); } } else { throw new Error("Unexpected response in fetching devices from itach: " + result); } }.bind(this)); } } } /* Global Cache Accessories CC */ function ItachAccessory(log, deviceType, config, portIndex) { this.log = log; var portConfig = null; if (config.ports && config.ports.length > portIndex) { portConfig = config.ports[portIndex]; } this.name = config.name + " - " + (portIndex + 1); this.deviceType = deviceType; this.host = config.host; this.port = config.port; this.portIndex = portIndex; this.log("Configuring iTach accessory. Name: " + this.name + ", Type: " + this.deviceType + " at port: " + this.portIndex); this.toggleMode = false; this.commands = {}; var id = uuid.generate('itach.' + deviceType + "." + this.host + "." + portIndex); Accessory.call(this, this.name, id); this.uuid_base = id; if (portConfig) { this.name = portConfig.name ? portConfig.name : this.name; this.toggleMode = portConfig.toggleMode; } this.services = []; if (this.deviceType == "relay") { var service = null; if (this.toggleMode) { service = new Service.GarageDoorOpener(this.name); service .getCharacteristic(Characteristic.TargetDoorState) .on('get', this.getState.bind(this)) .on('set', this.setState.bind(this)); service.setCharacteristic(Characteristic.CurrentDoorState, Characteristic.CurrentDoorState.CLOSED); } else { service = new Service.Switch(this.name); service .getCharacteristic(Characteristic.On) .on('get', this.getState.bind(this)) .on('set', this.setState.bind(this)); } this.services.push(service); } else if (this.deviceType == "ir") { this.commands = config.ports[portIndex].commands; if (this.commands && this.commands.on && this.commands.off) { //Assume default to off. this.irState = Characteristic.Off; var service = new Service.Switch(this.name); service.subtype = "default"; service .getCharacteristic(Characteristic.On) .on('set', this.setIrState.bind(this, '_on/off_')) .on('get', this.getState.bind(this)); this.services.push(service); } for (var i = 0; i < Object.keys(this.commands).length; i++) { var command = Object.keys(this.commands)[i]; if (command == "on" || command == "off") { continue; } var service = new Service.Switch(command); service.subtype = command; service.getCharacteristic(Characteristic.On) .on('set', this.setIrState.bind(this, command)) .on('get', this.getState.bind(this)); this.services.push(service); } } else { throw new Error("Unsupported device type: " + this.deviceType); } } ItachAccessory.prototype.getServices = function () { return this.services; } ItachAccessory.prototype.setIrState = function (command, state, callback) { this.log("Setting IR state for command: " + command); var commandArray; if (command == '_on/off_') { commandArray = state ? this.commands.on : this.commands.off; this.irState = state; } else { commandArray = this.commands[command]; this.irState = false; //Aways false. } var commandKeys; if(typeof commandArray === 'string') { commandKeys = [commandArray]; } else { commandKeys = commandArray.slice(0, commandArray.length); } commandKeys.reverse(); this.doNextCall(commandKeys, function() { console.log("Finished all commands"); callback(null, state); }.bind(this)); } ItachAccessory.prototype.doNextCall = function(commandKeys, callback) { var self = this; var commandKey = commandKeys.pop(); var command = self.commands[commandKey] ? self.commands[commandKey] : commandKey; this.setState(command, function (error, state) { if (commandKeys.length == 0) { callback(); } else { self.doNextCall(commandKeys, callback); } }); } ItachAccessory.prototype.setState = function (state, callback) { var command = "setstate"; if (this.deviceType == "ir") { command = "sendir"; } command += (",1:" + (this.portIndex + 1) + ","); if (this.deviceType == "ir") { command += state; } else { command += (this.toggleMode || state ? '1' : '0'); } this.sendSocketCommand(command, function (data) { var expected = command.trim(); if (this.deviceType == "ir") { expected = "completeir" + command.substring(6, 12); } if (data.trim() == expected) { if (this.toggleMode) { setTimeout(function () { var command = "setstate,1:" + (this.portIndex + 1) + ",0"; this.sendSocketCommand(command, function (data) { if (data.trim() == command.trim()) { callback(null); } }); }.bind(this), 1000); } else { if (this.deviceType == "ir") { this.irState = state; callback(null, this.irState); } else { callback(null); } } } else { callback(new Error('Failed to set state to ' + state + ". Response: " + data)); } }.bind(this)); } /* TODO */ ItachAccessory.prototype.getState = function (callback) { if (this.deviceType == "ir") { callback(null, this.irState); return; } if (this.toggleMode) { //No way to determine current state in toggle mode. callback(null, "Unknown"); return; } var command = "getstate,1:" + (this.portIndex + 1) + '\r'; this.sendSocketCommand(command, function (data) { var dataSplit = data.split(','); if (dataSplit.length != 3) { callback(new Error("Unexpected response from device: " + data)); } else { callback(null, dataSplit[2].trim() == '1'); } }.bind(this)); } ItachPlatform.prototype.sendSocketCommand = function (deviceIndex, command, callback, persistent) { var device = this.devices[deviceIndex]; var host = device.host; var port = device.port ? device.port : 4998; var sock = new net.Socket(); sock.log = this.log; var self = this; sock.connect(port, host, function () { this.log('Connected to ' + this.localAddress + ':' + this.localPort + ". Sending command: " + command); this.write(command + "\r"); }).on('data', function (data) { this.log('DATA: ' + data); callback(deviceIndex, data.toString()); // Close the connection if not persistent if (!persistent) { sock.destroy(); } }); } ItachAccessory.prototype.sendSocketCommand = function (command, callback) { var host = this.host; var port = this.port ? this.port : 4998; var sock = new net.Socket(); // A socket to communicate to the GC100 with sock.log = this.log; // Make it possible to use the platform log from the net.Socket instance var self = this; sock.connect(port, host, function () { this.log('Connected to ' + this.remoteAddress + ':' + this.remotePort + ". Sending command: " + command); this.write(command + "\r"); }).on('data', function (data) { var result = data.toString() this.log('DATA: ' + result); if (result.substring(0, 3) == "ERR") { var code = result.split(',')[1].trim(); var message = self.errors[code]; this.log("An error has occurred. " + code + ": " + message); } callback(result); // Close the connection this.destroy(); }); } <|start_filename|>package.json<|end_filename|> { "name": "homebridge-globalcache-itach", "version": "0.1.7", "description": "A homebridge plugin for Global Cache iTach devices", "main": "index.js", "scripts": { "test": "" }, "repository": { "type": "git", "url": "https://github.com/dustindclark/homebridge-globalcache-itach" }, "keywords": [ "homebridge-plugin", "global cache", "globalcache", "itach", "WF2CC", "IP2CC" ], "author": "<NAME>", "license": "MIT", "bugs": { "url": "https://github.com/dustindclark/homebridge-globalcache-itach/issues" }, "engines": { "node": ">=0.12.0", "homebridge": ">=0.2.0" }, "dependencies": { "net": ">=1.0" }, "homepage": "https://github.com/dustindclark/homebridge-globalcache-itach#readme" }
dustindclark/homebridge-globalcache-itach
<|start_filename|>Pds/Pds.Api.Contracts/Bill/EditBillRequest.cs<|end_filename|> using System.ComponentModel.DataAnnotations; using Pds.Core.Enums; namespace Pds.Api.Contracts.Bill; public class EditBillRequest { [Required] public Guid Id { get; set; } [Required] [Range(10.00, Double.MaxValue, ErrorMessage = "Значение поля {0} должно быть больше чем {1}.")] public decimal Value { get; set; } public string Comment { get; set; } public string ContractNumber { get; set; } public DateTime? ContractDate { get; set; } public bool IsNeedPayNds { get; set; } [Required] public DateTime PaidAt { get; set; } [Required, EnumDataType(typeof(BillType))] public BillType Type { get; set; } [Required, EnumDataType(typeof(PaymentType))] public PaymentType PaymentType { get; set; } [Required] public Guid BrandId { get; set; } public BillContentDto Content { get; set; } } <|start_filename|>Pds/Pds.Core/Exceptions/Gift/GiftCreateException.cs<|end_filename|> namespace Pds.Core.Exceptions.Gift; public class GiftCreateException : Exception, IApiException { public List<string> Errors { get; } public GiftCreateException(List<string> errors) { Errors = errors; } public GiftCreateException(string message) : base(message) { Errors = new List<string> { message }; } public GiftCreateException(string message, Exception inner) : base(message, inner) { } } <|start_filename|>Pds/Pds.Web/Components/Search/Gift/GiftsPageSearchSettings.cs<|end_filename|> namespace Pds.Web.Components.Search.Gift; public class ContentsPageSearchSettings { public string Search { get; set; } } <|start_filename|>Pds/Pds.Core/Exceptions/Gift/GiftDeleteException.cs<|end_filename|> namespace Pds.Core.Exceptions.Gift; public class GiftDeleteException : Exception, IApiException { public List<string> Errors { get; } public GiftDeleteException(List<string> errors) { Errors = errors; } public GiftDeleteException(string message) : base(message) { Errors = new List<string> { message }; } public GiftDeleteException(string message, Exception inner) : base(message, inner) { } } <|start_filename|>Pds/Pds.Api.Contracts/Paging/PageResult.cs<|end_filename|> namespace Pds.Api.Contracts.Paging; public class PageResult<T> { public List<T> Items { get; set; } public int Total { get; set; } } <|start_filename|>Pds/Pds.Core/Enums/CostStatus.cs<|end_filename|> namespace Pds.Core.Enums; public enum CostStatus { Active = 0, Archived = 1 } <|start_filename|>Pds/Pds.Services.Models/Client/EditContentModel.cs<|end_filename|> namespace Pds.Services.Models.Client; public class EditClientModel { public Guid Id { get; set; } public string Name { get; set; } public string Comment { get; set; } } <|start_filename|>Pds/Pds.Api.Contracts/Client/GetClientsRequest.cs<|end_filename|> using Pds.Api.Contracts.Paging; namespace Pds.Api.Contracts.Client; public class GetClientsRequest : PageSettings { } <|start_filename|>Pds/Pds.Web/Pages/Clients/List/Actions.razor.css<|end_filename|> .actions-panel { margin: 0 auto; width: 100px; } button { margin: 0 5px; } <|start_filename|>Pds/Pds.Api.Contracts/Gift/GetGiftsRequest.cs<|end_filename|> using Pds.Api.Contracts.Paging; namespace Pds.Api.Contracts.Gift; public class GetGiftsRequest : PageSettings { } <|start_filename|>Pds/Pds.Data/Entities/Bill.cs<|end_filename|> using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Pds.Core.Enums; namespace Pds.Data.Entities; public class Bill : EntityBase { [Required] [Column(TypeName = "decimal(18,2)")] public decimal Value { get; set; } [Required] public BillStatus Status { get; set; } [Required] public PaymentStatus PaymentStatus { get; set; } [Required] public BillType Type { get; set; } public PaymentType? PaymentType { get; set; } public string Comment { get; set; } [Column(TypeName = "varchar(300)")] public string Contact { get; set; } [Column(TypeName = "varchar(300)")] public string ContactName { get; set; } public ContactType? ContactType { get; set; } [Column(TypeName = "varchar(50)")] public string ContractNumber { get; set; } public DateTime? ContractDate { get; set; } public bool IsNeedPayNds { get; set; } public DateTime? PaidAt { get; set; } public Guid BrandId { get; set; } public Guid? ContentId { get; set; } public Guid? ClientId { get; set; } public virtual Brand Brand { get; set; } public virtual Content Content { get; set; } public virtual Client Client { get; set; } } <|start_filename|>Pds/Pds.Web/Pages/Content/Info/Actions.razor.css<|end_filename|> button { margin: 0 3px; } button i{ font-size: 0.8rem; margin-right: 5px; } <|start_filename|>Pds/Pds.Services/Services/GiftService.cs<|end_filename|> using Pds.Core.Enums; using Pds.Core.Exceptions.Gift; using Pds.Data; using Pds.Data.Entities; using Pds.Services.Interfaces; using Pds.Services.Models.Gift; namespace Pds.Services.Services; public class GiftService : IGiftService { private readonly IUnitOfWork unitOfWork; public GiftService(IUnitOfWork unitOfWork) { this.unitOfWork = unitOfWork; } public async Task<Gift> GetAsync(Guid giftId) { return await unitOfWork.Gifts.GetFullByIdAsync(giftId); } public async Task<List<Gift>> GetAllAsync() { return await unitOfWork.Gifts.GetAllFullAsync(); } public async Task<Guid> CreateAsync(Gift gift) { if (gift == null) { throw new GiftCreateException("Запрос был пуст."); } if (gift.Status == GiftStatus.Raffled && string.IsNullOrWhiteSpace(gift.Comment)) { throw new GiftCreateException("Не указан адрес доставки или ФИО победителя"); } if (gift.Status == GiftStatus.Waiting && (string.IsNullOrWhiteSpace(gift.FirstName) || string.IsNullOrWhiteSpace(gift.LastName) || string.IsNullOrWhiteSpace(gift.PostalAddress))) { throw new GiftCreateException("Не указан адрес доставки или ФИО победителя"); } gift.CreatedAt = DateTime.UtcNow; gift.FirstName = gift.FirstName.Trim(); gift.LastName = gift.LastName.Trim(); gift.ThirdName = gift.ThirdName.Trim(); gift.Title = gift.Title.Trim(); switch (gift.Status) { case GiftStatus.Raffled: gift.RaffledAt = DateTime.UtcNow; break; case GiftStatus.Completed: gift.CompletedAt = DateTime.UtcNow; break; } if (gift.ContentId == Guid.Empty) { gift.ContentId = null; } var result = await unitOfWork.Gifts.InsertAsync(gift); return result.Id; } public async Task<Guid> EditAsync(EditGiftModel model) { if (model == null) { throw new GiftEditException($"Модель запроса пуста."); } if (model.Status == GiftStatus.Raffled && string.IsNullOrWhiteSpace(model.Comment)) { throw new GiftEditException("Не указан адрес доставки или ФИО победителя"); } if (model.Status == GiftStatus.Waiting && (string.IsNullOrWhiteSpace(model.FirstName) || string.IsNullOrWhiteSpace(model.LastName) || string.IsNullOrWhiteSpace(model.PostalAddress))) { throw new GiftEditException("Не указан адрес доставки или ФИО победителя"); } var gift = await unitOfWork.Gifts.GetFullByIdAsync(model.Id); if (gift == null) { throw new GiftEditException($"Подарок с id {model.Id} не найден."); } if (gift.Status == GiftStatus.Completed) { throw new GiftEditException($"Нельзя редактировать отправленный подарок."); } gift.UpdatedAt = DateTime.UtcNow; gift.PreviousStatus = gift.Status; switch (model.Status) { case GiftStatus.Raffled: gift.RaffledAt = DateTime.UtcNow; break; case GiftStatus.Completed: gift.CompletedAt = DateTime.UtcNow; break; } gift.Title = model.Title; gift.Type = model.Type; gift.Status = model.Status; gift.Comment = model.Comment; gift.FirstName = model.FirstName; gift.LastName = model.LastName; gift.ThirdName = model.ThirdName; gift.PostalAddress = model.PostalAddress; gift.BrandId = model.BrandId; gift.ContentId = model.ContentId != null && model.ContentId.Value == Guid.Empty ? null : model.ContentId; var result = await unitOfWork.Gifts.UpdateAsync(gift); return result.Id; } public async Task CompleteAsync(Guid giftId) { var gift = await unitOfWork.Gifts.GetFirstWhereAsync(p => p.Id == giftId); if (gift != null) { gift.PreviousStatus = gift.Status; gift.Status = GiftStatus.Completed; gift.CompletedAt = DateTime.UtcNow; gift.UpdatedAt = DateTime.UtcNow; await unitOfWork.Gifts.UpdateAsync(gift); } } public async Task UncompleteAsync(Guid giftId) { var gift = await unitOfWork.Gifts.GetFirstWhereAsync(p => p.Id == giftId); if (gift != null) { gift.Status = gift.PreviousStatus ?? GiftStatus.New; gift.UpdatedAt = DateTime.UtcNow; await unitOfWork.Gifts.UpdateAsync(gift); } } public async Task DeleteAsync(Guid giftId) { var gift = await unitOfWork.Gifts.GetFirstWhereAsync(p => p.Id == giftId); if (gift == null) { throw new GiftDeleteException($"Подарок с id {giftId} не найден."); } if (gift.Status == GiftStatus.Completed) { throw new GiftDeleteException($"Нельзя удалить отправленный подарок."); } await unitOfWork.Gifts.Delete(gift); } } <|start_filename|>Pds/Pds.Api.Contracts/Gift/EditGiftResponse.cs<|end_filename|> namespace Pds.Api.Contracts.Gift; public class EditGiftResponse { public Guid Id { get; set; } } <|start_filename|>Pds/Pds.Api/Program.cs<|end_filename|> using Autofac; using Autofac.Extensions.DependencyInjection; using Pds.Api.AppStart; using Pds.Di; var builder = WebApplication.CreateBuilder(args); builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory()); builder.Host.ConfigureContainer<ContainerBuilder>(builder => builder.RegisterModule(new ApiDiModule())); //Add services builder.Services.AddCustomAuth0Authentication(builder.Configuration); builder.Services.AddCustomPdsCorsPolicy(builder.Configuration); builder.Services.AddControllers(); builder.Services.AddCustomSwagger(); builder.Services.AddCustomSqlContext(builder.Configuration); builder.Services.AddCustomAutoMapper(); var app = builder.Build(); if (app.Environment.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseCustomSwaggerUI(); } app.UseCustomPdsCorsPolicy(); app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); app.Run(); <|start_filename|>Pds/Pds.Data/Repositories/GiftRepository.cs<|end_filename|> using Microsoft.EntityFrameworkCore; using Pds.Core.Enums; using Pds.Data.Entities; using Pds.Data.Repositories.Interfaces; namespace Pds.Data.Repositories; public class GiftRepository : RepositoryBase<Gift>, IGiftRepository { private readonly ApplicationDbContext context; public GiftRepository(ApplicationDbContext context) : base(context) { this.context = context; } public async Task<List<Gift>> GetAllFullAsync() { return await context.Gifts .Include(b=>b.Content) .Include(b=>b.Brand) .OrderByDescending(p =>p.CreatedAt) .ToListAsync(); } public async Task<Gift> GetFullByIdAsync(Guid giftId) { return await context.Gifts .Include(c => c.Content) .Include(c => c.Brand) .FirstOrDefaultAsync(c => c.Id == giftId); } } <|start_filename|>Pds/Pds.Api.Contracts/Person/PersonDto.cs<|end_filename|> using Pds.Core.Enums; namespace Pds.Api.Contracts.Person; public class PersonDto { public Guid Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string ThirdName { get; set; } public string FullName { get; set; } public string Country { get; set; } public string City { get; set; } public string Location { get; set; } public string Topics { get; set; } public string Info { get; set; } public int? Rate { get; set; } public PersonStatus Status { get; set; } public List<ResourceDto> Resources { get; set; } public List<PersonContentDto> Contents { get; set; } public List<BrandDto> Brands { get; set; } } <|start_filename|>Pds/Pds.Web/Program.cs<|end_filename|> global using Newtonsoft.Json; using Microsoft.AspNetCore.Components.Web; using Microsoft.AspNetCore.Components.WebAssembly.Hosting; using Pds.Web; using Pds.Web.Common; using Toolbelt.Blazor.Extensions.DependencyInjection; var builder = WebAssemblyHostBuilder.CreateDefault(args); builder.RootComponents.Add<App>("#app"); builder.RootComponents.Add<HeadOutlet>("head::after"); builder.Services.AddTransient(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) }); builder.Services.AddTransient<IApiClient, ApiClient>(); builder.Services.AddSingleton<PageHistoryState>(); builder.Services.AddHeadElementHelper(); builder.Services.AddCustomAutoMapper(); builder.Services.AddOidcAuthentication(options => { builder.Configuration.Bind("Auth0", options.ProviderOptions); options.ProviderOptions.ResponseType = "code"; }); await builder.Build().RunAsync(); <|start_filename|>Pds/Pds.Data/Migrations/20210324203029_RenameOrderToBillAndUpdate.cs<|end_filename|> using System; using Microsoft.EntityFrameworkCore.Migrations; namespace Pds.Data.Migrations { public partial class RenameOrderToBillAndUpdate : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Orders"); migrationBuilder.RenameColumn( name: "OrderId", table: "Contents", newName: "BillId"); migrationBuilder.CreateTable( name: "Bills", columns: table => new { Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), Cost = table.Column<decimal>(type: "decimal(18,2)", nullable: false), Status = table.Column<int>(type: "int", nullable: false), Type = table.Column<int>(type: "int", nullable: false), PaymentType = table.Column<int>(type: "int", nullable: false), Comment = table.Column<string>(type: "nvarchar(max)", nullable: true), PrimaryContact = table.Column<string>(type: "varchar(300)", nullable: false), PrimaryContactType = table.Column<int>(type: "int", nullable: false), ChannelId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), ContentId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), ClientId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false), UpdatedAt = table.Column<DateTime>(type: "datetime2", nullable: true) }, constraints: table => { table.PrimaryKey("PK_Bills", x => x.Id); table.ForeignKey( name: "FK_Bills_Channels_ChannelId", column: x => x.ChannelId, principalTable: "Channels", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Bills_Clients_ClientId", column: x => x.ClientId, principalTable: "Clients", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_Bills_Contents_ContentId", column: x => x.ContentId, principalTable: "Contents", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateIndex( name: "IX_Bills_ChannelId", table: "Bills", column: "ChannelId"); migrationBuilder.CreateIndex( name: "IX_Bills_ClientId", table: "Bills", column: "ClientId"); migrationBuilder.CreateIndex( name: "IX_Bills_ContentId", table: "Bills", column: "ContentId", unique: true, filter: "[ContentId] IS NOT NULL"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Bills"); migrationBuilder.RenameColumn( name: "BillId", table: "Contents", newName: "OrderId"); migrationBuilder.CreateTable( name: "Orders", columns: table => new { Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), ChannelId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), ClientId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), Comment = table.Column<string>(type: "nvarchar(max)", nullable: true), ContentId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), Cost = table.Column<decimal>(type: "decimal(18,2)", nullable: false), CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false), PrimaryContact = table.Column<string>(type: "varchar(300)", nullable: false), PrimaryContactType = table.Column<int>(type: "int", nullable: false), Status = table.Column<int>(type: "int", nullable: false), UpdatedAt = table.Column<DateTime>(type: "datetime2", nullable: true) }, constraints: table => { table.PrimaryKey("PK_Orders", x => x.Id); table.ForeignKey( name: "FK_Orders_Channels_ChannelId", column: x => x.ChannelId, principalTable: "Channels", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_Orders_Clients_ClientId", column: x => x.ClientId, principalTable: "Clients", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_Orders_Contents_ContentId", column: x => x.ContentId, principalTable: "Contents", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_Orders_ChannelId", table: "Orders", column: "ChannelId"); migrationBuilder.CreateIndex( name: "IX_Orders_ClientId", table: "Orders", column: "ClientId"); migrationBuilder.CreateIndex( name: "IX_Orders_ContentId", table: "Orders", column: "ContentId", unique: true); } } } <|start_filename|>Pds/Pds.Web/Pages/Content/Info/Body.razor.css<|end_filename|> .page-container { padding-top: 15px; } .info-item { margin-bottom: 15px; } .info-item .info-title { background-color: lightgray; padding: 5px 15px; border-radius: 5px 5px 0 0; font-size: 0.8rem; font-style: italic; border-bottom: 6px double white; } .info-item .info-body { background-color: orchid; padding: 10px 15px 10px 15px; border-radius: 0 0 5px 5px; margin-bottom: 10px; } .info-body ul { margin-bottom: 0rem; } .active-not-paid .info-item .info-body { background-color: lightpink; } .free .info-item .info-body { background-color: lightblue; } .active-paid .info-item .info-body { background-color: lightgreen; } .archived-not-paid .info-item .info-body { background-color: orangered; } .archived-free .info-item .info-body, .archived-paid .info-item .info-body { background-color: gainsboro; } .bill-cost i.payment-type { font-size: 0.8rem; padding: 2px 4px; border-radius: 4px; font-style: normal; margin-left: 5px; margin-right: 5px } .bill-cost i.white { background-color: white; color: black; } .bill-cost i.red { background-color: lightcoral; color: white; } .bill-comment { padding-left: 15px; font-size: 0.8rem; margin-top: 10px; } .info-item.costs .info-body { background-color: lightpink !important; } .nds { background-color: lightcoral; color: white; font-size: 0.8rem; padding: 2px 4px; border-radius: 4px; font-style: normal; margin-left: 10px; } <|start_filename|>Pds/Pds.Data/Migrations/20210529225504_UpdateBillData.cs<|end_filename|> using Microsoft.EntityFrameworkCore.Migrations; namespace Pds.Data.Migrations { public partial class UpdateBillData : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.Sql( $"Update bills set PaymentStatus = [Status];" + $"Update bills set [Status] = 0;"); } protected override void Down(MigrationBuilder migrationBuilder) { } } } <|start_filename|>Pds/Pds.Api.Contracts/Bill/PayContentPayload.cs<|end_filename|> using System.ComponentModel.DataAnnotations; using Pds.Core.Enums; namespace Pds.Api.Contracts.Bill; public class PayBillPayload { [Required] public PaymentType PaymentType { get; set; } [Required] [Range(10.00, Double.MaxValue, ErrorMessage = "Значение поля {0} должно быть больше чем {1}.")] public decimal Value { get; set; } public string Comment { get; set; } public DateTime PaidAt { get; set; } public string ContractNumber { get; set; } public DateTime? ContractDate { get; set; } public bool IsNeedPayNds { get; set; } } <|start_filename|>Pds/Pds.Web/Pages/Content/List/Actions.razor.css<|end_filename|> .actions-panel { margin: 0 auto; white-space: pre; } button { margin: 0 3px; } button i{ font-size: 0.8rem; } <|start_filename|>Pds/Pds.Services/Interfaces/IBrandService.cs<|end_filename|> using Pds.Data.Entities; namespace Pds.Services.Interfaces; public interface IBrandService { Task<List<Brand>> GetBrandsForListsAsync(); } <|start_filename|>Pds/Pds.Web/wwwroot/appsettings.Production.json<|end_filename|> { "Auth0": { "Authority": "https://itbeard.eu.auth0.com", "ClientId": "3hg9NaK4s7XCUeT7yhFIafGYLlJQc0yP" }, "BackendApi": { "Url": "https://pds-api.azurewebsites.net" } } <|start_filename|>Pds/Pds.Api.Contracts/Client/ClientBillDto.cs<|end_filename|> using Pds.Core.Enums; namespace Pds.Api.Contracts.Client; public class ClientBillDto { public Guid Id { get; set; } public decimal Value { get; set; } public PaymentStatus PaymentStatus { get; set; } public BillType Type { get; set; } public PaymentType? PaymentType { get; set; } public string Comment { get; set; } public string Contact { get; set; } public string ContactName { get; set; } public ContactType? ContactType { get; set; } public string ContractNumber { get; set; } public DateTime? ContractDate { get; set; } public bool IsNeedPayNds { get; set; } public DateTime? PaidAt { get; set; } public Guid BrandId { get; set; } public Guid? ContentId { get; set; } public Guid? ClientId { get; set; } } <|start_filename|>Pds/Pds.Web/Pages/Persons/List/Body.razor.css<|end_filename|> .person-header { width: 200px; } .card-header { margin-bottom: 15px; } .rate-header { width: 100px; text-align: center; } .topics-header { width: 100px; text-align: center; } .actions-header { width: 100px; } .rate-row { text-align: center; color: #555; font-size: 0.8rem; font-weight: bold; } .location-row { min-width: 80px; } .topics-row { text-align: center; } .info-row { white-space: pre-line; } .person-row .contents { font-size: 0.75rem; margin-left: 5px; color: #888; font-weight: bold; text-decoration: none; } .active { background-color: lightgreen; } .archived, .archived a, .archived span, .archived .rate-row { background-color: gainsboro; color: #bbb !important; } .archived:hover, .archived:hover a, .archived:hover span, .archived:hover .rate-row { color: black !important; } .title-overall-info{ font-style: italic; font-size: 1rem; background-color: green; padding: 2px 4px; border-radius: 4px; color: #eee; } <|start_filename|>Pds/Pds.Api.Contracts/Content/GetContent/GetContentPersonDto.cs<|end_filename|> namespace Pds.Api.Contracts.Content.GetContent; public class GetContentPersonDto { public Guid Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string ThirdName { get; set; } public string Country { get; set; } public string City { get; set; } public List<GetContentPersonResourceDto> Resources { get; set; } } <|start_filename|>Pds/Pds.Di/ApiDiModule.cs<|end_filename|> using System.Reflection; using Autofac; using Pds.Data; using Pds.Data.Repositories; using Pds.Data.Repositories.Interfaces; using Module = Autofac.Module; namespace Pds.Di; public class ApiDiModule : Module { protected override void Load(ContainerBuilder builder) { Pds.Data.AssemblyRunner.Run(); Pds.Services.AssemblyRunner.Run(); var assemblies = AppDomain.CurrentDomain .GetAssemblies() .OrderByDescending(a => a.FullName) .ToArray(); ServicesRegister(ref builder, assemblies); RepositoriesRegister(ref builder, assemblies); UnitOfWorkRegister(ref builder); UnitOfWorkRegister(ref builder); } private void ServicesRegister(ref ContainerBuilder builder, Assembly[] assemblies) { var servicesAssembly = assemblies.FirstOrDefault(t => t.FullName.ToLower().Contains("pds.services,")); builder.RegisterAssemblyTypes(servicesAssembly) .Where(t => t.Name.EndsWith("Service")) .AsImplementedInterfaces(); } private void RepositoriesRegister(ref ContainerBuilder builder, Assembly[] assemblies) { builder.RegisterGeneric(typeof(RepositoryBase<>)) .As(typeof(IRepositoryBase<>)); var dataAssembly = assemblies.FirstOrDefault(t => t.FullName.ToLower().Contains("pds.data,")); builder.RegisterAssemblyTypes(dataAssembly) .Where(t => t.Name.EndsWith("Repository")) .AsImplementedInterfaces(); } private void UnitOfWorkRegister(ref ContainerBuilder builder) { builder.RegisterType(typeof(UnitOfWork)) .As(typeof(IUnitOfWork)); } } <|start_filename|>Pds/Pds.Web/Pages/Gifts/Edit.razor.css<|end_filename|> .card-header { margin-bottom: 15px; } .form-group { margin-bottom: 15px; } ::deep input.bill-value{ width: 100px; display: inline-block; margin-left: 10px; margin-right: 10px; } ::deep input.bill-date{ width: 150px; display: inline-block; margin-left: 10px; margin-right: 10px; } ::deep input.pay-date{ width: 150px; display: inline-block; margin-left: 10px; margin-right: 10px; } <|start_filename|>Pds/Pds.Web/Components/Search/Person/PersonsPageSearchSettings.cs<|end_filename|> namespace Pds.Web.Components.Search.Person; public class PersonsPageSearchSettings { public string Search { get; set; } } <|start_filename|>Pds/Pds.Data/Migrations/20210402075826_CreateTopicEntity.cs<|end_filename|> using System; using Microsoft.EntityFrameworkCore.Migrations; namespace Pds.Data.Migrations { public partial class CreateTopicEntity : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Topics", columns: table => new { Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), Name = table.Column<string>(type: "varchar(300)", nullable: false), CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false), UpdatedAt = table.Column<DateTime>(type: "datetime2", nullable: true) }, constraints: table => { table.PrimaryKey("PK_Topics", x => x.Id); }); migrationBuilder.CreateTable( name: "PersonTopics", columns: table => new { PersonId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), TopicId = table.Column<Guid>(type: "uniqueidentifier", nullable: false) }, constraints: table => { table.PrimaryKey("PK_PersonTopics", x => new { x.TopicId, x.PersonId }); table.ForeignKey( name: "FK_PersonTopics_Persons_PersonId", column: x => x.PersonId, principalTable: "Persons", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_PersonTopics_Topics_TopicId", column: x => x.TopicId, principalTable: "Topics", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_PersonTopics_PersonId", table: "PersonTopics", column: "PersonId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "PersonTopics"); migrationBuilder.DropTable( name: "Topics"); } } } <|start_filename|>Pds/Pds.Web/Components/Pagination/PagingEventArgs.cs<|end_filename|> namespace Pds.Web.Components.Pagination; public struct PagingEventArgs { public int PageSize { get; } public int PageOffSet { get; } public PagingEventArgs(int pageSize, int pageOffSet) { PageSize = pageSize; PageOffSet = pageOffSet; } } <|start_filename|>Pds/Pds.Api.Contracts/Content/GetContents/GetContentsResponse.cs<|end_filename|> using Pds.Api.Contracts.Paging; namespace Pds.Api.Contracts.Content.GetContents; public class GetContentsResponse : PageResult<GetContentsContentDto> { } <|start_filename|>Pds/Pds.Api.Contracts/Cost/GetCostsRequest.cs<|end_filename|> using Pds.Api.Contracts.Paging; namespace Pds.Api.Contracts.Cost; public class GetCostsRequest : PageSettings { } <|start_filename|>Pds/Pds.Web/Pages/Gifts/List/Filter.razor.css<|end_filename|> .form-group { margin-bottom: 5px; } ::deep input.from-date, ::deep input.to-date{ width: 150px; display: inline-block; } .filter-row-title { font-size: 0.77rem; padding: 2px 4px; border-radius: 4px; color: #999; width: 100px; display: inline-block; text-align: right; font-style: italic; } .filter-date-separator { font-size: 0.77rem; padding: 2px 4px; border-radius: 4px; color: #999; display: inline-block; text-align: right; font-style: italic; } .filter { padding: 15px 15px 15px 0; border-radius: calc(.25rem - 1px) calc(.25rem - 1px) 0 0; background-color: rgba(0,0,0,.03); border-bottom: 1px solid rgba(0,0,0,.125); } <|start_filename|>Pds/Pds.Core/Exceptions/Person/PersonEditException.cs<|end_filename|> namespace Pds.Core.Exceptions.Person; public class PersonEditException : Exception, IApiException { public List<string> Errors { get; } public PersonEditException(List<string> errors) { Errors = errors; } public PersonEditException(string message) : base(message) { Errors = new List<string> { message }; } public PersonEditException(string message, Exception inner) : base(message, inner) { } } <|start_filename|>Pds/Pds.Api.Contracts/Topic/GetTopicResponse.cs<|end_filename|> using Pds.Api.Contracts.Person; using Pds.Core.Enums; namespace Pds.Api.Contracts.Topic; public class GetTopicResponse { public Guid Id { get; set; } public DateTime CreatedAt { get; set; } public DateTime? UpdatedAt { get; set; } public TopicStatus Status { get; set; } public string Name { get; set; } public IReadOnlyList<PersonDto> People { get; set; } } <|start_filename|>Pds/Pds.Services/Services/ClientService.cs<|end_filename|> using Pds.Core.Exceptions.Client; using Pds.Data; using Pds.Data.Entities; using Pds.Services.Interfaces; using Pds.Services.Models.Client; namespace Pds.Services.Services; public class ClientService : IClientService { private readonly IUnitOfWork unitOfWork; public ClientService(IUnitOfWork unitOfWork) { this.unitOfWork = unitOfWork; } public async Task<Client> GetAsync(Guid clientId) { return await unitOfWork.Clients.GetFullByIdAsync(clientId); } public async Task<List<Client>> GetAllAsync() { return await unitOfWork.Clients.GetAllWithBillsOrderByNameAsync(); } public async Task<Guid> CreateAsync(Client client) { if (client == null) { throw new ArgumentNullException(nameof(client)); } if (await unitOfWork.Clients.IsExistsByNameAsync(client.Name)) { throw new ClientCreateException("Клиент с таким именем существует в системе."); } client.CreatedAt = DateTime.UtcNow; client.Name = client.Name.Trim(); var result = await unitOfWork.Clients.InsertAsync(client); return result.Id; } public async Task<Guid> EditAsync(EditClientModel model) { if (model == null) { throw new ClientEditException("Модель запроса пуста."); } var client = await unitOfWork.Clients.GetFullByIdAsync(model.Id); if (client == null) { throw new ClientEditException($"Клиент с id {model.Id} не найден."); } if (client.Name != model.Name && await unitOfWork.Clients.IsExistsByNameAsync(model.Name)) { throw new ClientCreateException("Клиент с таким именем существует в системе."); } client.UpdatedAt = DateTime.UtcNow; client.Name = model.Name.Trim(); client.Comment = model.Comment; var result = await unitOfWork.Clients.UpdateAsync(client); return result.Id; } public async Task DeleteAsync(Guid clientId) { var client = await unitOfWork.Clients.GetFullByIdAsync(clientId); if (client.Bills != null && client.Bills.Count > 0) { throw new ClientDeleteException("Нельзя удалить клиента с привязанным контентом."); } if (client != null) { await unitOfWork.Clients.Delete(client); } } public async Task<List<Client>> GetClientsForListsAsync() { var clients = new List<Client> {new() {Id = Guid.Empty}}; //Add empty as a first element of list clients.AddRange(await unitOfWork.Clients.GetAllOrderByNameAsync()); return clients; } } <|start_filename|>Pds/Pds.Api/AppStart/AuthenticationExtensions.cs<|end_filename|> using Microsoft.AspNetCore.Authentication.JwtBearer; using Pds.Api.Authentication; namespace Pds.Api.AppStart; public static class AuthenticationExtensions { private const string CorsPolicy = "PdsCorsPolicy"; public static void AddCustomAuth0Authentication(this IServiceCollection services, IConfiguration configuration) { services .AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.Authority = configuration["Auth0:Authority"]; options.Audience = configuration["Auth0:ApiIdentifier"]; }); var auth0Settings = new Auth0Settings(); configuration.GetSection("Auth0").Bind(auth0Settings); services.AddSingleton(auth0Settings); } public static void AddCustomPdsCorsPolicy(this IServiceCollection services, IConfiguration configuration) { services.AddCors(options => { options.AddPolicy(CorsPolicy, builder => builder.WithOrigins(configuration.GetSection("AllowedOrigins").Get<List<string>>().ToArray()) .AllowAnyMethod() .AllowAnyHeader()); }); } public static void UseCustomPdsCorsPolicy(this IApplicationBuilder app) { app.UseCors(CorsPolicy); } } <|start_filename|>Pds/Pds.Core/Enums/PersonStatus.cs<|end_filename|> namespace Pds.Core.Enums; public enum PersonStatus { Archived = 0, Active = 1 } <|start_filename|>Pds/Pds.Web/Components/Search/Gift/GiftsSearch.cs<|end_filename|> using Calabonga.PredicatesBuilder; using Pds.Api.Contracts.Gift; using System.Linq.Expressions; namespace Pds.Web.Components.Search.Gift; public class GiftsSearch { public Expression<Func<GiftDto, bool>> GetSearchPredicate(string searchLine) { searchLine = searchLine.ToLower(); var predicate = PredicateBuilder.False<GiftDto>(); predicate = predicate.Or(c => c.Title.ToLower().Contains(searchLine)); predicate = predicate.Or(c => !string.IsNullOrWhiteSpace(c.FirstName) && c.FirstName.ToLower().Contains(searchLine)); predicate = predicate.Or(c => !string.IsNullOrWhiteSpace(c.LastName) && c.LastName.ToLower().Contains(searchLine)); predicate = predicate.Or(c => !string.IsNullOrWhiteSpace(c.ThirdName) && c.ThirdName.ToLower().Contains(searchLine)); predicate = predicate.Or(c => !string.IsNullOrWhiteSpace(c.PostalAddress) && c.PostalAddress.ToLower().Contains(searchLine)); predicate = predicate.Or(c => !string.IsNullOrWhiteSpace(c.Comment) && c.Comment.ToLower().Contains(searchLine)); predicate = predicate.Or(c => c.CompletedAt != null && !string.IsNullOrWhiteSpace(c.CompletedAt.Value.ToString("dd.MM.yyyy")) && c.CompletedAt.Value.ToString("dd.MM.yyyy").ToLower().Contains(searchLine)); predicate = predicate.Or(c => c.CompletedAt != null && !string.IsNullOrWhiteSpace(c.CompletedAt.Value.ToString("dd.MM.yyyy")) && c.CompletedAt.Value.ToString("dd.MM.yyyy").ToLower().Contains(searchLine)); predicate = predicate.Or(c => c.RaffledAt != null && !string.IsNullOrWhiteSpace(c.RaffledAt.Value.ToString("dd.MM.yyyy")) && c.RaffledAt.Value.ToString("dd.MM.yyyy").ToLower().Contains(searchLine)); predicate = predicate.Or(c => !string.IsNullOrWhiteSpace(c.CreatedAt.ToString("dd.MM.yyyy")) && c.CreatedAt.ToString("dd.MM.yyyy").ToLower().Contains(searchLine)); predicate = predicate.Or(r => r.Content != null && r.Content.Title.ToLower().Contains(searchLine)); return predicate; } } <|start_filename|>Pds/Pds.Api.Contracts/Topic/CreateTopicResponse.cs<|end_filename|> namespace Pds.Api.Contracts.Topic; public class CreateTopicResponse { public CreateTopicResponse(Guid id) { Id = id; } public Guid Id { get; set; } } <|start_filename|>Pds/Pds.Api.Contracts/Content/GetContents/GetContentsContentDto.cs<|end_filename|> using Pds.Core.Enums; namespace Pds.Api.Contracts.Content.GetContents; public class GetContentsContentDto { public string Id { get; set; } public string Title { get; set; } public ContentStatus Status { get; set; } public string ClientName { get; set; } public DateTime ReleaseDate { get; set; } public DateTime? EndDate { get; set; } public SocialMediaType SocialMediaType { get; set; } public ContentType Type { get; set; } public GetContentsBillDto Bill { get; set; } public GetContentsPersonDto Person { get; set; } public BrandDto Brand { get; set; } } <|start_filename|>Pds/Pds.Web/Pages/Persons/List/Actions.razor.css<|end_filename|> .delete-button { pointer-events: auto; } .actions-panel { margin: 0 auto; white-space: pre; } button { margin: 0 5px; } <|start_filename|>Pds/Pds.Api.Contracts/Content/CreateContent/CreateContentResponse.cs<|end_filename|> namespace Pds.Api.Contracts.Content.CreateContent; public class CreateContentResponse { public Guid Id { get; set; } } <|start_filename|>Pds/Pds.Api/Authentication/CustomAuthorizeAttribute.cs<|end_filename|> using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; namespace Pds.Api.Authentication; [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)] public class CustomAuthorizeAttribute : AuthorizeAttribute, IAuthorizationFilter { public void OnAuthorization(AuthorizationFilterContext context) { var user = context.HttpContext.User; if (!user.Identity.IsAuthenticated) { context.Result = new UnauthorizedResult(); return; } // If "azp" claim do not exists - reject var auth0AppIdClaim = user.Claims.FirstOrDefault(c => c.Type == "azp"); if (auth0AppIdClaim == null) { context.Result = new UnauthorizedResult(); return; } // If JWT produced through unauthorized Auth0 app - reject var services = context.HttpContext.RequestServices; var auth0Settings = services.GetService<Auth0Settings>(); if (auth0Settings.AllowedAppId != auth0AppIdClaim.Value) { context.Result = new UnauthorizedResult(); return; } } } <|start_filename|>Pds/Pds.Web/Pages/Costs/List/Body.razor.css<|end_filename|> .table { font-size: 0.9rem; } .table td{ vertical-align: middle; } .table > :not(:last-child) > :last-child > *{ border-bottom: 2px solid darkgray; color: darkgray; } .card-header { margin-bottom: 15px; } .actions-header { width: 100px; } .id-header, .paid-date-header { width: 70px; text-align: center; } .paid-date-row { text-align: center; } .paid-date-row span { font-size: 0.77rem; background-color: darkgray; padding: 2px 4px; border-radius: 4px; color: white; } .cost-type-header { width: 130px; text-align: left; } .cost-value-header { width: 120px; text-align: center; padding-right: 15px; } .cost-value-row { text-align: center; padding-right: 15px; } .cost-value-row span { font-weight: bold; font-size: 1rem; margin-right: 5px; } .id-row { color: #777; } .title-overall-info{ font-style: italic; font-size: 1rem; background-color: green; padding: 2px 4px; border-radius: 4px; color: #eee; } <|start_filename|>Pds/Pds.Api.Contracts/Topic/GetTopicsResponse.cs<|end_filename|> using Pds.Api.Contracts.Paging; namespace Pds.Api.Contracts.Topic; public class GetTopicsResponse : PageResult<TopicDto> { } <|start_filename|>Pds/Pds.Data/Repositories/Interfaces/IResourceRepository.cs<|end_filename|> using Pds.Data.Entities; namespace Pds.Data.Repositories.Interfaces; public interface IResourceRepository : IRepositoryBase<Resource> { // Can bee extended by any additional methods that do not present in IRepositoryBase } <|start_filename|>Pds/Pds.Web/Pages/BasePageComponent.cs<|end_filename|> using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Components; using Pds.Web.Common; namespace Pds.Web.Pages; [Authorize] public class BasePageComponent: ComponentBase { [Inject] protected NavigationManager _navManager { get; set; } [Inject] protected PageHistoryState _pageState { get; set; } public BasePageComponent(NavigationManager navManager, PageHistoryState pageState) { _navManager = navManager; _pageState = pageState; } public BasePageComponent() { } protected override void OnInitialized() { base.OnInitialized(); _pageState.AddPage(_navManager.Uri); } protected void GoBack() { _navManager.NavigateTo(_pageState.PreviousPage()); } } <|start_filename|>Pds/Pds.Api.Contracts/Content/GetContents/GetContentsBillDto.cs<|end_filename|> using Pds.Core.Enums; namespace Pds.Api.Contracts.Content.GetContents; public class GetContentsBillDto : IPaymentStatus { public decimal Value { get; set; } public PaymentStatus PaymentStatus { get; set; } public string Contact { get; set; } public string ContactName { get; set; } public PaymentType? PaymentType { get; set; } } <|start_filename|>Pds/Pds.Api.Contracts/Content/GetContent/GetContentPersonResourceDto.cs<|end_filename|> namespace Pds.Api.Contracts.Content.GetContent; public class GetContentPersonResourceDto { public string Name { get; set; } public string Url { get; set; } } <|start_filename|>Pds/Pds.Web.Models/Bill/FilterSettings.cs<|end_filename|> namespace Pds.Web.Models.Bill; public class FilterSettings { public List<SocialMediaFilterItem> SocialMediaFilterItems { get; set; } public List<BillTypeFilterItem> BillTypeFilterItems { get; set; } public List<PaymentTypeFilterItem> PaymentTypeFilterItems { get; set; } public List<BrandFilterItem> BrandFilterItems { get; set; } public DateTime? From { get; set; } public DateTime? To { get; set; } } <|start_filename|>Pds/Pds.Data/Migrations/20210401234052_AddNullableBillToContent.cs<|end_filename|> using System; using Microsoft.EntityFrameworkCore.Migrations; namespace Pds.Data.Migrations { public partial class AddNullableBillToContent : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.RenameColumn( name: "PrimaryContactType", table: "Bills", newName: "ContactType"); migrationBuilder.RenameColumn( name: "PrimaryContact", table: "Bills", newName: "ContactName"); migrationBuilder.AlterColumn<Guid>( name: "BillId", table: "Contents", type: "uniqueidentifier", nullable: true, oldClrType: typeof(Guid), oldType: "uniqueidentifier"); migrationBuilder.AddColumn<string>( name: "Contact", table: "Bills", type: "varchar(300)", nullable: false, defaultValue: ""); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "Contact", table: "Bills"); migrationBuilder.RenameColumn( name: "ContactType", table: "Bills", newName: "PrimaryContactType"); migrationBuilder.RenameColumn( name: "ContactName", table: "Bills", newName: "PrimaryContact"); migrationBuilder.AlterColumn<Guid>( name: "BillId", table: "Contents", type: "uniqueidentifier", nullable: false, defaultValue: new Guid("00000000-0000-0000-0000-000000000000"), oldClrType: typeof(Guid), oldType: "uniqueidentifier", oldNullable: true); } } } <|start_filename|>Pds/Pds.Services.Models/Gift/EditGiftModel.cs<|end_filename|> using Pds.Core.Enums; namespace Pds.Services.Models.Gift; public class EditGiftModel { public Guid Id { get; set; } public string Title { get; set; } public GiftType Type { get; set; } public GiftStatus Status { get; set; } public string Comment { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string ThirdName { get; set; } public string PostalAddress { get; set; } public Guid BrandId { get; set; } public Guid? ContentId { get; set; } } <|start_filename|>Pds/Pds.Api.Contracts/Bill/CreateBillRequest.cs<|end_filename|> using System.ComponentModel.DataAnnotations; using Pds.Core.Enums; namespace Pds.Api.Contracts.Bill; public class CreateBillRequest { [Required] public Guid BrandId { get; set; } [Range(10, Double.MaxValue, ErrorMessage = "Значение поля {0} должно быть больше чем {1}.")] public decimal Value { get; set; } [Required, EnumDataType(typeof(BillType))] public BillType Type { get; set; } [Required] public PaymentType PaymentType { get; set; } [Required] public DateTime PaidAt { get; set; } public string Comment { get; set; } public string ContractNumber { get; set; } public DateTime? ContractDate { get; set; } public bool IsNeedPayNds { get; set; } public Guid? ClientId { get; set; } public string Contact { get; set; } public string ContactName { get; set; } public ContactType ContactType { get; set; } } <|start_filename|>Pds/Pds.Api.Contracts/Cost/CostDto.cs<|end_filename|> using Pds.Core.Enums; namespace Pds.Api.Contracts.Cost; public class CostDto { public Guid Id { get; set; } public decimal Value { get; set; } public DateTime PaidAt { get; set; } public CostType Type { get; set; } public CostStatus Status { get; set; } public string Comment { get; set; } public CostContentDto Content { get; set; } public BrandDto Brand { get; set; } public bool IsVisible { get; set; } } <|start_filename|>Pds/Pds.Web/Pages/Persons/PersonsHelper.cs<|end_filename|> using Pds.Core.Enums; namespace Pds.Web.Pages.Content; public static class PersonsHelper { public static string GetBgColorClass(PersonStatus personStatus) { return personStatus switch { PersonStatus.Active => "active", PersonStatus.Archived => "archived", _ => string.Empty }; } } <|start_filename|>Pds/Pds.Core/Exceptions/Client/ClientCreateException.cs<|end_filename|> namespace Pds.Core.Exceptions.Client; public class ClientCreateException : Exception, IApiException { public List<string> Errors { get; } public ClientCreateException(List<string> errors) { Errors = errors; } public ClientCreateException(string message) : base(message) { Errors = new List<string> { message }; } public ClientCreateException(string message, Exception inner) : base(message, inner) { } } <|start_filename|>Pds/Pds.Core/Enums/ContentType.cs<|end_filename|> namespace Pds.Core.Enums; public enum ContentType { Other = 0, // Прочий контент SponsoredVideo = 1, // Спонсированное видео Post = 2, // Пост Story = 3, // Сториз EventHosting = 4, // Ведущий EventParticipation = 5, // Участник мероприятия Exclusive = 6, // Эксклюзивный контент Integration = 7, // Интеграция } <|start_filename|>Pds/Pds.Api.Contracts/Bill/CreateBillResponse.cs<|end_filename|> namespace Pds.Api.Contracts.Bill; public class CreateBillResponse { public Guid Id { get; set; } } <|start_filename|>Pds/Pds.Web/Components/Sorting/QueryCreators/IOrderQuery.cs<|end_filename|> namespace Pds.Web.Components.Sorting.QueryCreators; public interface IOrderQuery<out TOut, TIn> { IOrderedQueryable<TOut> CreateOrderBy(IQueryable<TIn> query, bool ascending); IOrderedQueryable<TOut> CreateThenBy(IOrderedQueryable<TIn> query, bool ascending); } <|start_filename|>Pds/Pds.Core/Enums/GiftStatus.cs<|end_filename|> namespace Pds.Core.Enums; public enum GiftStatus { New = 0, // Новый, не разыгранный подарок Raffled = 1, // Разыгран Waiting = 2, // Ожидает доставки Completed = 3, // Отправлен (архивный, готов) Strange = 4 // Странный (потеряшка или перенос или еще чего) } <|start_filename|>Pds/Pds.Web/Components/Sorting/QueryCreators/Person/PersonsFieldName.cs<|end_filename|> namespace Pds.Web.Components.Sorting.QueryCreators.Person; public enum PersonsFieldName { FullName, Rating, Location } <|start_filename|>Pds/Pds.Data/Migrations/20210512191312_RenameTopicPeopleToTopicPersons.cs<|end_filename|> using Microsoft.EntityFrameworkCore.Migrations; namespace Pds.Data.Migrations { public partial class RenameTopicPeopleToTopicPersons : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_PersonTopic_Persons_PeopleId", table: "PersonTopic"); migrationBuilder.RenameColumn( name: "PeopleId", table: "PersonTopic", newName: "PersonsId"); migrationBuilder.AddForeignKey( name: "FK_PersonTopic_Persons_PersonsId", table: "PersonTopic", column: "PersonsId", principalTable: "Persons", principalColumn: "Id", onDelete: ReferentialAction.Cascade); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_PersonTopic_Persons_PersonsId", table: "PersonTopic"); migrationBuilder.RenameColumn( name: "PersonsId", table: "PersonTopic", newName: "PeopleId"); migrationBuilder.AddForeignKey( name: "FK_PersonTopic_Persons_PeopleId", table: "PersonTopic", column: "PeopleId", principalTable: "Persons", principalColumn: "Id", onDelete: ReferentialAction.Cascade); } } } <|start_filename|>Pds/Pds.Services.Models/Person/EditPersonModel.cs<|end_filename|> namespace Pds.Services.Models.Person; public class EditPersonModel { public Guid Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string ThirdName { get; set; } public string Country { get; set; } public string City { get; set; } public string Topics { get; set; } public string Info { get; set; } public int? Rate { get; set; } public List<Guid> BrandsIds { get; set; } } <|start_filename|>Pds/Pds.Api.Contracts/Content/GetContent/GetContentResponse.cs<|end_filename|> using Pds.Core.Enums; namespace Pds.Api.Contracts.Content.GetContent; public class GetContentResponse { public Guid Id { get; set; } public string Title { get; set; } public ContentType Type { get; set; } public ContentStatus Status { get; set; } public SocialMediaType SocialMediaType { get; set; } public string Comment { get; set; } public DateTime ReleaseDate { get; set; } public DateTime? EndDate { get; set; } public GetContentBillDto Bill { get; set; } public BrandDto Brand { get; set; } public GetContentPersonDto Person { get; set; } public List<GetContentCostDto> Costs { get; set; } } <|start_filename|>Pds/Pds.Web.Models/Cost/BrandFilterItem.cs<|end_filename|> namespace Pds.Web.Models.Cost; public class BrandFilterItem { public Guid Id { get; set; } public string Name { get; set; } public bool IsSelected { get; set; } } <|start_filename|>Pds/Pds.Api.Contracts/Paging/PageSettings.cs<|end_filename|> namespace Pds.Api.Contracts.Paging; public class PageSettings { public int Limit { get; set; } public int Offset { get; set; } } public class OrderSetting<T> where T : Enum { public bool Ascending { get; set; } = true; public T FieldName { get; set; } } <|start_filename|>Pds/Pds.Services/Services/BrandService.cs<|end_filename|> using Pds.Data; using Pds.Data.Entities; using Pds.Services.Interfaces; namespace Pds.Services.Services; public class BrandService : IBrandService { private readonly IUnitOfWork unitOfWork; public BrandService(IUnitOfWork unitOfWork) { this.unitOfWork = unitOfWork; } public async Task<List<Brand>> GetBrandsForListsAsync() { return await unitOfWork.Brands.GetAllAsync(); } } <|start_filename|>Pds/Pds.Data/Migrations/20210404180317_AddCosts.cs<|end_filename|> using System; using Microsoft.EntityFrameworkCore.Migrations; namespace Pds.Data.Migrations { public partial class AddCosts : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Costs", columns: table => new { Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), Value = table.Column<decimal>(type: "decimal(18,2)", nullable: false), Comment = table.Column<string>(type: "nvarchar(max)", nullable: true), Type = table.Column<int>(type: "int", nullable: false), BrandId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), ContentId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false), UpdatedAt = table.Column<DateTime>(type: "datetime2", nullable: true) }, constraints: table => { table.PrimaryKey("PK_Costs", x => x.Id); table.ForeignKey( name: "FK_Costs_Brands_BrandId", column: x => x.BrandId, principalTable: "Brands", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Costs_Contents_ContentId", column: x => x.ContentId, principalTable: "Contents", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateIndex( name: "IX_Costs_BrandId", table: "Costs", column: "BrandId"); migrationBuilder.CreateIndex( name: "IX_Costs_ContentId", table: "Costs", column: "ContentId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Costs"); } } } <|start_filename|>Pds/Pds.Data/Repositories/Interfaces/IPersonRepository.cs<|end_filename|> using Pds.Data.Entities; namespace Pds.Data.Repositories.Interfaces; public interface IPersonRepository : IRepositoryBase<Person> { Task<List<Person>> GetAllFullAsync(); Task<Person> GetFullByIdAsync(Guid personId); Task<List<Person>> GetForListsAsync(); } <|start_filename|>Pds/Pds.Data/Migrations/20210823203330_AddTopicsToPersonAsString.Designer.cs<|end_filename|> // <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Pds.Data; namespace Pds.Data.Migrations { [DbContext(typeof(ApplicationDbContext))] [Migration("20210823203330_AddTopicsToPersonAsString")] partial class AddTopicsToPersonAsString { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .UseIdentityColumns() .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("ProductVersion", "5.0.2"); modelBuilder.Entity("BrandPerson", b => { b.Property<Guid>("BrandsId") .HasColumnType("uniqueidentifier"); b.Property<Guid>("PersonsId") .HasColumnType("uniqueidentifier"); b.HasKey("BrandsId", "PersonsId"); b.HasIndex("PersonsId"); b.ToTable("BrandPerson"); }); modelBuilder.Entity("Pds.Data.Entities.Bill", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<Guid>("BrandId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("ClientId") .HasColumnType("uniqueidentifier"); b.Property<string>("Comment") .HasColumnType("nvarchar(max)"); b.Property<string>("Contact") .HasColumnType("varchar(300)"); b.Property<string>("ContactName") .HasColumnType("varchar(300)"); b.Property<int?>("ContactType") .HasColumnType("int"); b.Property<Guid?>("ContentId") .HasColumnType("uniqueidentifier"); b.Property<DateTime?>("ContractDate") .HasColumnType("datetime2"); b.Property<string>("ContractNumber") .HasColumnType("varchar(50)"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<bool>("IsNeedPayNds") .HasColumnType("bit"); b.Property<DateTime?>("PaidAt") .HasColumnType("datetime2"); b.Property<int>("PaymentStatus") .HasColumnType("int"); b.Property<int?>("PaymentType") .HasColumnType("int"); b.Property<int>("Status") .HasColumnType("int"); b.Property<int>("Type") .HasColumnType("int"); b.Property<DateTime?>("UpdatedAt") .HasColumnType("datetime2"); b.Property<decimal>("Value") .HasColumnType("decimal(18,2)"); b.HasKey("Id"); b.HasIndex("BrandId"); b.HasIndex("ClientId"); b.HasIndex("ContentId") .IsUnique() .HasFilter("[ContentId] IS NOT NULL"); b.ToTable("Bills"); }); modelBuilder.Entity("Pds.Data.Entities.Brand", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<string>("Name") .IsRequired() .HasColumnType("varchar(300)"); b.Property<DateTime?>("UpdatedAt") .HasColumnType("datetime2"); b.Property<string>("Url") .IsRequired() .HasColumnType("varchar(300)"); b.HasKey("Id"); b.ToTable("Brands"); b.HasData( new { Id = new Guid("5aa23fa2-4b73-4a3f-c3d4-08d8d2705c5f"), CreatedAt = new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Name = "АйТиБорода", Url = "https://youtube.com/itbeard" }, new { Id = new Guid("6bb23fa2-4b73-4a3f-c3d4-08d8d2705c5f"), CreatedAt = new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Name = "<NAME>", Url = "https://youtube.com/thedarkless" }); }); modelBuilder.Entity("Pds.Data.Entities.Client", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Comment") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<string>("Name") .IsRequired() .HasColumnType("varchar(300)"); b.Property<DateTime?>("UpdatedAt") .HasColumnType("datetime2"); b.HasKey("Id"); b.ToTable("Clients"); }); modelBuilder.Entity("Pds.Data.Entities.Content", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<Guid?>("BillId") .HasColumnType("uniqueidentifier"); b.Property<Guid>("BrandId") .HasColumnType("uniqueidentifier"); b.Property<string>("Comment") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<DateTime?>("EndDate") .HasColumnType("datetime2"); b.Property<Guid?>("PersonId") .HasColumnType("uniqueidentifier"); b.Property<DateTime>("ReleaseDate") .HasColumnType("datetime2"); b.Property<int>("SocialMediaType") .HasColumnType("int"); b.Property<int>("Status") .HasColumnType("int"); b.Property<string>("Title") .IsRequired() .HasColumnType("varchar(300)"); b.Property<int>("Type") .HasColumnType("int"); b.Property<DateTime?>("UpdatedAt") .HasColumnType("datetime2"); b.HasKey("Id"); b.HasIndex("BrandId"); b.HasIndex("PersonId"); b.ToTable("Contents"); }); modelBuilder.Entity("Pds.Data.Entities.Cost", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<Guid>("BrandId") .HasColumnType("uniqueidentifier"); b.Property<string>("Comment") .HasColumnType("nvarchar(max)"); b.Property<Guid?>("ContentId") .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<DateTime>("PaidAt") .HasColumnType("datetime2"); b.Property<int>("Status") .HasColumnType("int"); b.Property<int>("Type") .HasColumnType("int"); b.Property<DateTime?>("UpdatedAt") .HasColumnType("datetime2"); b.Property<decimal>("Value") .HasColumnType("decimal(18,2)"); b.HasKey("Id"); b.HasIndex("BrandId"); b.HasIndex("ContentId"); b.ToTable("Costs"); }); modelBuilder.Entity("Pds.Data.Entities.Person", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime?>("ArchivedAt") .HasColumnType("datetime2"); b.Property<string>("City") .HasColumnType("nvarchar(max)"); b.Property<string>("Country") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<string>("FirstName") .IsRequired() .HasColumnType("varchar(300)"); b.Property<string>("Info") .HasColumnType("nvarchar(max)"); b.Property<string>("LastName") .IsRequired() .HasColumnType("varchar(300)"); b.Property<string>("Latitude") .HasColumnType("nvarchar(max)"); b.Property<string>("Longitude") .HasColumnType("nvarchar(max)"); b.Property<int?>("Rate") .HasColumnType("int"); b.Property<int>("Status") .ValueGeneratedOnAdd() .HasColumnType("int") .HasDefaultValue(1); b.Property<string>("ThirdName") .HasColumnType("varchar(300)"); b.Property<string>("Topics") .HasColumnType("nvarchar(max)"); b.Property<DateTime?>("UnarchivedAt") .HasColumnType("datetime2"); b.Property<DateTime?>("UpdatedAt") .HasColumnType("datetime2"); b.HasKey("Id"); b.ToTable("Persons"); }); modelBuilder.Entity("Pds.Data.Entities.Resource", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<Guid>("PersonId") .HasColumnType("uniqueidentifier"); b.Property<DateTime?>("UpdatedAt") .HasColumnType("datetime2"); b.Property<string>("Url") .IsRequired() .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("PersonId"); b.ToTable("Resources"); }); modelBuilder.Entity("BrandPerson", b => { b.HasOne("Pds.Data.Entities.Brand", null) .WithMany() .HasForeignKey("BrandsId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Pds.Data.Entities.Person", null) .WithMany() .HasForeignKey("PersonsId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Pds.Data.Entities.Bill", b => { b.HasOne("Pds.Data.Entities.Brand", "Brand") .WithMany("Bills") .HasForeignKey("BrandId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Pds.Data.Entities.Client", "Client") .WithMany("Bills") .HasForeignKey("ClientId"); b.HasOne("Pds.Data.Entities.Content", "Content") .WithOne("Bill") .HasForeignKey("Pds.Data.Entities.Bill", "ContentId"); b.Navigation("Brand"); b.Navigation("Client"); b.Navigation("Content"); }); modelBuilder.Entity("Pds.Data.Entities.Content", b => { b.HasOne("Pds.Data.Entities.Brand", "Brand") .WithMany("Contents") .HasForeignKey("BrandId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Pds.Data.Entities.Person", "Person") .WithMany("Contents") .HasForeignKey("PersonId"); b.Navigation("Brand"); b.Navigation("Person"); }); modelBuilder.Entity("Pds.Data.Entities.Cost", b => { b.HasOne("Pds.Data.Entities.Brand", "Brand") .WithMany("Costs") .HasForeignKey("BrandId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Pds.Data.Entities.Content", "Content") .WithMany("Costs") .HasForeignKey("ContentId"); b.Navigation("Brand"); b.Navigation("Content"); }); modelBuilder.Entity("Pds.Data.Entities.Resource", b => { b.HasOne("Pds.Data.Entities.Person", "Person") .WithMany("Resources") .HasForeignKey("PersonId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Person"); }); modelBuilder.Entity("Pds.Data.Entities.Brand", b => { b.Navigation("Bills"); b.Navigation("Contents"); b.Navigation("Costs"); }); modelBuilder.Entity("Pds.Data.Entities.Client", b => { b.Navigation("Bills"); }); modelBuilder.Entity("Pds.Data.Entities.Content", b => { b.Navigation("Bill"); b.Navigation("Costs"); }); modelBuilder.Entity("Pds.Data.Entities.Person", b => { b.Navigation("Contents"); b.Navigation("Resources"); }); #pragma warning restore 612, 618 } } } <|start_filename|>Pds/Pds.Web/Components/Search/SearchComponent.razor.css<|end_filename|> .search-position { display: flex; justify-content: flex-end; float: right; } .search-button-show{ display:none; } .search-btn { margin-left: 10px; color: #fff; background-color: #1b6ec2; height: 38px; position: relative; } .searchcleaner{ text-align:center; align-items:center; position:absolute; top:8px; right:10px; } .searchcleaner:hover { cursor:pointer; } <|start_filename|>Pds/Pds.Data/Repositories/Interfaces/IBrandRepository.cs<|end_filename|> using Pds.Data.Entities; namespace Pds.Data.Repositories.Interfaces; public interface IBrandRepository : IRepositoryBase<Brand> { } <|start_filename|>Pds/Pds.Core/Extensions/DateTimeExtensions.cs<|end_filename|> namespace Pds.Core.Extensions; public static class DateTimeExtensions { public static string ToShortStringDateWithDay(this DateTime date) { return $"{date:dd.MM} / {date.Date.DayOfWeek.ToShortRussianDayOfWeek()}"; } public static string ToShortStringDate(this DateTime date) { return $"{date:dd.MM}"; } public static string ToLongStringDateWithDay(this DateTime date) { return $"{date:d MMMM yyyy} г. ({date.Date.DayOfWeek.ToLongRussianDayOfWeek().ToLower()})"; } public static string ToLongStringDate(this DateTime date) { return $"{date:d MMMM yyyy} г."; } } <|start_filename|>Pds/Pds.Api/Controllers/GiftController.cs<|end_filename|> using AutoMapper; using Microsoft.AspNetCore.Mvc; using Pds.Api.Authentication; using Pds.Api.Contracts; using Pds.Api.Contracts.Gift; using Pds.Data.Entities; using Pds.Services.Interfaces; using Pds.Services.Models.Gift; namespace Pds.Api.Controllers; [Route("api/gifts")] [CustomAuthorize] public class GiftController : ApiControllerBase { private readonly ILogger<PersonController> logger; private readonly IMapper mapper; private readonly IGiftService giftService; private readonly IBrandService brandService; private readonly IContentService contentService; public GiftController( ILogger<PersonController> logger, IMapper mapper, IGiftService giftService, IBrandService brandService, IContentService contentService) { this.logger = logger; this.mapper = mapper; this.giftService = giftService; this.brandService = brandService; this.contentService = contentService; } /// <summary> /// Get gift by id /// </summary> /// <param name="giftId"></param> /// <returns></returns> [HttpGet("{giftId}")] [ProducesResponseType(typeof(GetGiftResponse), StatusCodes.Status200OK)] public async Task<IActionResult> Get(Guid giftId) { try { var bill = await giftService.GetAsync(giftId); var response = mapper.Map<GetGiftResponse>(bill); return Ok(response); } catch (Exception e) { return ExceptionResult(e); } } /// <summary> /// Return list of gifts /// </summary> /// <param name="request"></param> /// <returns></returns> [HttpGet("")] [ProducesResponseType(typeof(GetGiftsResponse), StatusCodes.Status200OK)] public async Task<IActionResult> GetAll([FromQuery] GetGiftsRequest request) { try { var gifts = await giftService.GetAllAsync(); var response = new GetGiftsResponse { Items = mapper.Map<List<GiftDto>>(gifts), Total = gifts.Count }; return Ok(response); } catch (Exception e) { return ExceptionResult(e); } } /// <summary> /// Create gift /// </summary> /// <returns></returns> [HttpPost] [ProducesResponseType(typeof(CreateGiftResponse), StatusCodes.Status200OK)] public async Task<IActionResult> Create(CreateGiftRequest request) { try { if (ModelState.IsValid) { var gift = mapper.Map<Gift>(request); var giftId = await giftService.CreateAsync(gift); return Ok(new CreateGiftResponse{Id = giftId}); } return BadRequest(); } catch (Exception e) { return ExceptionResult(e); } } /// <summary> /// Edit gift /// </summary> /// <returns></returns> [HttpPut] [ProducesResponseType(typeof(EditGiftResponse), StatusCodes.Status200OK)] [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)] public async Task<IActionResult> Edit(EditGiftRequest request) { try { if (!ModelState.IsValid) return BadRequest(); var editGiftModel = mapper.Map<EditGiftModel>(request); var billId = await giftService.EditAsync(editGiftModel); return Ok(new EditGiftResponse{Id = billId}); } catch (Exception e) { return ExceptionResult(e); } } /// <summary> /// Return list of brands for checkboxes group /// </summary> [HttpGet] [Route("get-brands")] public async Task<IActionResult> GetListOfBrands() { try { var brands = await brandService.GetBrandsForListsAsync(); var response = mapper.Map<List<BrandDto>>(brands); return Ok(response); } catch (Exception e) { return ExceptionResult(e); } } /// <summary> /// Return list of contents for lookup box /// </summary> [HttpGet] [Route("get-contents")] public async Task<IActionResult> GetListOfContents() { try { var contents = await contentService.GetContentsForListsAsync(); var response = mapper.Map<List<ContentForLookupDto>>(contents); return Ok(response); } catch (Exception e) { return ExceptionResult(e); } } /// <summary> /// Complete specified gift /// </summary> /// <param name="giftId"></param> /// <returns></returns> [HttpPut("{giftId}/complete")] [ProducesResponseType(StatusCodes.Status200OK)] public async Task<IActionResult> Complete(Guid giftId) { try { await giftService.CompleteAsync(giftId); return Ok(); } catch (Exception e) { return ExceptionResult(e); } } /// <summary> /// Uncomplete specified gift /// </summary> /// <param name="giftId"></param> /// <returns></returns> [HttpPut("{giftId}/uncomplete")] [ProducesResponseType(StatusCodes.Status200OK)] public async Task<IActionResult> Uncomplete(Guid giftId) { try { await giftService.UncompleteAsync(giftId); return Ok(); } catch (Exception e) { return ExceptionResult(e); } } /// <summary> /// Delete specified gift /// </summary> /// <param name="giftId"></param> /// <returns></returns> [HttpDelete("{giftId}")] [ProducesResponseType(StatusCodes.Status200OK)] public async Task<IActionResult> Delete(Guid giftId) { try { await giftService.DeleteAsync(giftId); return Ok(); } catch (Exception e) { return ExceptionResult(e); } } } <|start_filename|>Pds/Pds.Web/Components/Sorting/QueryCreators/Person/PersonLocationOrderQueryCreator.cs<|end_filename|> using Pds.Api.Contracts.Person; namespace Pds.Web.Components.Sorting.QueryCreators.Person; public class PersonLocationOrderQueryCreator : IOrderQuery<PersonDto, PersonDto> { public IOrderedQueryable<PersonDto> CreateOrderBy(IQueryable<PersonDto> query, bool ascending) { if (ascending) { return query.OrderBy(x => x.Location); } else { return query.OrderByDescending(x => x.Location); } } public IOrderedQueryable<PersonDto> CreateThenBy(IOrderedQueryable<PersonDto> query, bool ascending) { if (ascending) { return query.ThenBy(x => x.Location); } else { return query.ThenByDescending(x => x.Location); } } } <|start_filename|>Pds/Pds.Api.Contracts/Person/BrandForCheckboxesDto.cs<|end_filename|> namespace Pds.Api.Contracts.Person; public class BrandForCheckboxesDto { public Guid Id { get; set; } public string Name { get; set; } public bool IsSelected { get; set; } } <|start_filename|>Pds/Pds.Data/Repositories/Interfaces/ICostRepository.cs<|end_filename|> using Pds.Data.Entities; namespace Pds.Data.Repositories.Interfaces; public interface ICostRepository : IRepositoryBase<Cost> { Task<List<Cost>> GetAllOrderByDateDescAsync(); Task<Cost> GetFullByIdAsync(Guid costId); } <|start_filename|>Pds/Pds.Data/Migrations/20210420060534_RemovePersonTopic.cs<|end_filename|> using System; using Microsoft.EntityFrameworkCore.Migrations; namespace Pds.Data.Migrations { public partial class RemovePersonTopic : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "PersonTopics"); migrationBuilder.DropColumn( name: "ArchivedAt", table: "Topics"); migrationBuilder.DropColumn( name: "UnarchivedAt", table: "Topics"); migrationBuilder.CreateTable( name: "PersonTopic", columns: table => new { PeopleId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), TopicsId = table.Column<Guid>(type: "uniqueidentifier", nullable: false) }, constraints: table => { table.PrimaryKey("PK_PersonTopic", x => new { x.PeopleId, x.TopicsId }); table.ForeignKey( name: "FK_PersonTopic_Persons_PeopleId", column: x => x.PeopleId, principalTable: "Persons", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_PersonTopic_Topics_TopicsId", column: x => x.TopicsId, principalTable: "Topics", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_PersonTopic_TopicsId", table: "PersonTopic", column: "TopicsId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "PersonTopic"); migrationBuilder.AddColumn<DateTime>( name: "ArchivedAt", table: "Topics", type: "datetime2", nullable: true); migrationBuilder.AddColumn<DateTime>( name: "UnarchivedAt", table: "Topics", type: "datetime2", nullable: true); migrationBuilder.CreateTable( name: "PersonTopics", columns: table => new { TopicId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), PersonId = table.Column<Guid>(type: "uniqueidentifier", nullable: false) }, constraints: table => { table.PrimaryKey("PK_PersonTopics", x => new { x.TopicId, x.PersonId }); table.ForeignKey( name: "FK_PersonTopics_Persons_PersonId", column: x => x.PersonId, principalTable: "Persons", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_PersonTopics_Topics_TopicId", column: x => x.TopicId, principalTable: "Topics", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_PersonTopics_PersonId", table: "PersonTopics", column: "PersonId"); } } } <|start_filename|>Pds/Pds.Web/Common/MappersExtensions.cs<|end_filename|> using AutoMapper; using Pds.Mappers; namespace Pds.Web.Common; public static class MappersExtensions { public static void AddCustomAutoMapper(this IServiceCollection services) { var mappingConfig = new MapperConfiguration(mc => { mc.AddProfile(new ApiMappingProfile()); }); IMapper mapper = mappingConfig.CreateMapper(); services.AddSingleton(mapper); } } <|start_filename|>Pds/Pds.Data/Migrations/20210407232650_AddContractDataToBill.cs<|end_filename|> using System; using Microsoft.EntityFrameworkCore.Migrations; namespace Pds.Data.Migrations { public partial class AddContractDataToBill : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<DateTime>( name: "ContractDate", table: "Bills", type: "datetime2", nullable: false, defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); migrationBuilder.AddColumn<string>( name: "ContractNumber", table: "Bills", type: "varchar(50)", nullable: true); migrationBuilder.AddColumn<bool>( name: "IsNeedPayNds", table: "Bills", type: "bit", nullable: false, defaultValue: false); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "ContractDate", table: "Bills"); migrationBuilder.DropColumn( name: "ContractNumber", table: "Bills"); migrationBuilder.DropColumn( name: "IsNeedPayNds", table: "Bills"); } } } <|start_filename|>Pds/Pds.Data/Migrations/20210322180605_UpdateOrdersAndContent.cs<|end_filename|> using System; using Microsoft.EntityFrameworkCore.Migrations; namespace Pds.Data.Migrations { public partial class UpdateOrdersAndContent : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_Orders_Clients_ClientId", table: "Orders"); migrationBuilder.DropColumn( name: "PrimaryContact", table: "Contents"); migrationBuilder.AlterColumn<Guid>( name: "ClientId", table: "Orders", type: "uniqueidentifier", nullable: true, oldClrType: typeof(Guid), oldType: "uniqueidentifier"); migrationBuilder.AddForeignKey( name: "FK_Orders_Clients_ClientId", table: "Orders", column: "ClientId", principalTable: "Clients", principalColumn: "Id", onDelete: ReferentialAction.Restrict); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_Orders_Clients_ClientId", table: "Orders"); migrationBuilder.AlterColumn<Guid>( name: "ClientId", table: "Orders", type: "uniqueidentifier", nullable: false, defaultValue: new Guid("00000000-0000-0000-0000-000000000000"), oldClrType: typeof(Guid), oldType: "uniqueidentifier", oldNullable: true); migrationBuilder.AddColumn<string>( name: "PrimaryContact", table: "Contents", type: "varchar(300)", nullable: false, defaultValue: ""); migrationBuilder.AddForeignKey( name: "FK_Orders_Clients_ClientId", table: "Orders", column: "ClientId", principalTable: "Clients", principalColumn: "Id", onDelete: ReferentialAction.Cascade); } } } <|start_filename|>Pds/Pds.Web/Components/Sorting/QueryCreators/OrderQueryCreator.cs<|end_filename|> using Pds.Api.Contracts.Paging; namespace Pds.Web.Components.Sorting.QueryCreators; public class OrderQueryCreator<T, TField> where T : class where TField : Enum { private readonly Dictionary<TField, IOrderQuery<T, T>> queryCreators; public OrderQueryCreator(Dictionary<TField, IOrderQuery<T, T>> queryCreators) { this.queryCreators = queryCreators; } public IQueryable<T> Create(OrderSetting<TField>[] orderSettings, IQueryable<T> query) { var selector = queryCreators[orderSettings[0].FieldName]; var orderedQuery = selector.CreateOrderBy(query, orderSettings[0].Ascending); foreach (var orderSetting in orderSettings.Skip(1)) { selector = queryCreators[orderSetting.FieldName]; orderedQuery = selector.CreateThenBy(orderedQuery, orderSetting.Ascending); } query = orderedQuery; return query; } } <|start_filename|>Pds/Pds.Data/Repositories/Interfaces/IGiftRepository.cs<|end_filename|> using Pds.Data.Entities; namespace Pds.Data.Repositories.Interfaces; public interface IGiftRepository : IRepositoryBase<Gift> { Task<List<Gift>> GetAllFullAsync(); Task<Gift> GetFullByIdAsync(Guid giftId); } <|start_filename|>Pds/Pds.Web/Pages/Clients/Info/Body.razor.css<|end_filename|> .page-container { padding-top: 15px; } .info-item { margin-bottom: 15px; } .info-item .info-title { background-color: lightgray; padding: 5px 15px; border-radius: 5px 5px 0 0; font-size: 0.8rem; font-style: italic; border-bottom: 6px double white; } .info-item .info-body { background-color: gainsboro; padding: 10px 15px 10px 15px; border-radius: 0 0 5px 5px; margin-bottom: 10px; } .info-item-bill-paid .info-body { background-color: lightgreen; } .info-item-bill-active .info-body { background-color: lightpink; } .info-body ul { margin-bottom: 0rem; } <|start_filename|>Pds/Pds.Core/Extensions/DayOfWeekExtensions.cs<|end_filename|> namespace Pds.Core.Extensions; public static class DayOfWeekExtensions { public static string ToShortRussianDayOfWeek(this DayOfWeek day) { return day switch { DayOfWeek.Monday => "пн", DayOfWeek.Tuesday => "вт", DayOfWeek.Wednesday => "ср", DayOfWeek.Thursday => "чт", DayOfWeek.Friday => "пт", DayOfWeek.Saturday => "сб", DayOfWeek.Sunday => "вс", _ => string.Empty }; } public static string ToLongRussianDayOfWeek(this DayOfWeek day) { return day switch { DayOfWeek.Monday => "Понедельник", DayOfWeek.Tuesday => "Вторник", DayOfWeek.Wednesday => "Среда", DayOfWeek.Thursday => "Четверг", DayOfWeek.Friday => "Пятница", DayOfWeek.Saturday => "Суббота", DayOfWeek.Sunday => "Воскресенье", _ => string.Empty }; } } <|start_filename|>Pds/Pds.Api.Contracts/Gift/GiftContentDto.cs<|end_filename|> namespace Pds.Api.Contracts.Gift; public class GiftContentDto { public Guid Id { get; set; } public string Title { get; set; } } <|start_filename|>Pds/Pds.Services/Services/BillService.cs<|end_filename|> using Pds.Core.Enums; using Pds.Core.Exceptions.Bill; using Pds.Data; using Pds.Data.Entities; using Pds.Services.Interfaces; using Pds.Services.Models.Bill; namespace Pds.Services.Services; public class BillService : IBillService { private readonly IUnitOfWork unitOfWork; public BillService(IUnitOfWork unitOfWork) { this.unitOfWork = unitOfWork; } public async Task PayBillAsync(PayBillModel model) { var bill = await unitOfWork.Bills.GetFirstWhereAsync(b => b.Id == model.BillId); if (bill != null) { bill.Value = model.Value; bill.PaymentType = model.PaymentType; bill.Comment = model.Comment; bill.PaymentStatus = PaymentStatus.Paid; bill.UpdatedAt = DateTime.UtcNow; bill.PaidAt = model.PaidAt; bill.IsNeedPayNds = model.IsNeedPayNds; bill.ContractNumber = model.ContractNumber; bill.ContractDate = model.ContractDate; await unitOfWork.Bills.UpdateAsync(bill); } } public async Task<Bill> GetAsync(Guid billId) { return await unitOfWork.Bills.GetFullByIdAsync(billId); } public async Task<List<Bill>> GetAllPaidAsync() { return await unitOfWork.Bills.GetAllPaidOrderByDateDescAsync(); } public async Task<Guid> CreateAsync(Bill bill) { if (bill == null) { throw new BillCreateException("Запрос был пуст."); } if (bill.Type == BillType.Content) { throw new BillCreateException("Счета типа \"Контент\" добавляются через создание контента."); } bill.CreatedAt = DateTime.UtcNow; bill.PaymentStatus = PaymentStatus.Paid; bill.Status = BillStatus.Active; if (bill.ClientId == Guid.Empty) { bill.ClientId = null; bill.ContactName = null; bill.Contact = null; bill.ContactType = null; } var result = await unitOfWork.Bills.InsertAsync(bill); return result.Id; } public async Task<Guid> EditAsync(EditBillModel model) { if (model == null) { throw new BillEditException($"Модель запроса пуста."); } var bill = await unitOfWork.Bills.GetFullByIdAsync(model.Id); if (bill == null) { throw new BillEditException($"Доход с id {model.Id} не найден."); } if (bill.Status == BillStatus.Archived) { throw new BillEditException($"Нельзя редактировать архивный доход."); } bill.UpdatedAt = DateTime.UtcNow; bill.Value = model.Value; bill.Comment = model.Comment; bill.PaidAt = model.PaidAt; bill.Comment = model.Comment; bill.Type = model.Type; bill.PaymentType = model.PaymentType; bill.IsNeedPayNds = model.IsNeedPayNds; bill.ContractNumber = model.ContractNumber; bill.ContractDate = model.ContractDate; bill.BrandId = model.BrandId; bill.UpdatedAt = DateTime.UtcNow; var result = await unitOfWork.Bills.UpdateAsync(bill); return result.Id; } public async Task ArchiveAsync(Guid billId) { var bill = await unitOfWork.Bills.GetFirstWhereAsync(p => p.Id == billId); if (bill != null) { bill.Status = BillStatus.Archived; bill.UpdatedAt = DateTime.UtcNow; await unitOfWork.Bills.UpdateAsync(bill); } } public async Task UnarchiveAsync(Guid billId) { var bill = await unitOfWork.Bills.GetFirstWhereAsync(p => p.Id == billId); if (bill is {Status: BillStatus.Archived}) { bill.Status = BillStatus.Active; bill.UpdatedAt = DateTime.UtcNow; await unitOfWork.Bills.UpdateAsync(bill); } } public async Task DeleteAsync(Guid billId) { var bill = await unitOfWork.Bills.GetFirstWhereAsync(p => p.Id == billId); if (bill == null) { throw new BillDeleteException($"Доход с id {billId} не найден."); } if (bill.Status == BillStatus.Archived) { throw new BillDeleteException($"Нельзя удалить архивный доход."); } if (bill.Content != null) { throw new BillDeleteException($"Доход, привязанный к контенту, удаляется только через контент."); } await unitOfWork.Bills.Delete(bill); } } <|start_filename|>Pds/Pds.Web/Pages/Clients/Info/Bill.razor.css<|end_filename|> .bill-cost i.payment-type { font-size: 0.8rem; padding: 2px 4px; border-radius: 4px; font-style: normal; margin-left: 5px; margin-right: 5px } .bill-cost i.white { background-color: white; color: black; } .bill-cost i.red { background-color: lightcoral; color: white; } .bill-comment { padding-left: 15px; font-size: 0.8rem; margin-top: 10px; } <|start_filename|>Pds/Pds.Api.Contracts/Bill/GetBillsResponse.cs<|end_filename|> using Pds.Api.Contracts.Paging; namespace Pds.Api.Contracts.Bill; public class GetBillsResponse : PageResult<BillDto> { } <|start_filename|>Pds/Pds.Core/Exceptions/IApiException.cs<|end_filename|> namespace Pds.Core.Exceptions; public interface IApiException { List<string> Errors { get; } } <|start_filename|>Pds/Pds.Core/Exceptions/Content/ContentDeleteException.cs<|end_filename|> namespace Pds.Core.Exceptions.Content; public class ContentDeleteException : Exception, IApiException { public List<string> Errors { get; } public ContentDeleteException(List<string> errors) { Errors = errors; } public ContentDeleteException(string message) : base(message) { Errors = new List<string> { message }; } public ContentDeleteException(string message, Exception inner) : base(message, inner) { } } <|start_filename|>Pds/Pds.Api.Contracts/Content/GetContent/GetContentBillDto.cs<|end_filename|> using Pds.Core.Enums; namespace Pds.Api.Contracts.Content.GetContent; public class GetContentBillDto : IPaymentStatus { public Guid Id { get; set; } public decimal Value { get; set; } public string Comment { get; set; } public string Contact { get; set; } public string ContactName { get; set; } public ContactType ContactType { get; set; } public PaymentStatus PaymentStatus { get; set; } public PaymentType? PaymentType { get; set; } public DateTime? PaidAt { get; set; } public string ContractNumber { get; set; } public DateTime? ContractDate { get; set; } public bool IsNeedPayNds { get; set; } public Guid ClientId { get; set; } public GetContentBillClientDto Client { get; set; } } <|start_filename|>Pds/Pds.Api.Contracts/Gift/GiftDto.cs<|end_filename|> using Pds.Api.Contracts.Content; using Pds.Core.Enums; namespace Pds.Api.Contracts.Gift; public class GiftDto { public Guid Id { get; set; } public string Title { get; set; } public string Comment { get; set; } public GiftStatus Status { get; set; } public GiftType Type { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string ThirdName { get; set; } public string PostalAddress { get; set; } public DateTime SortDate { get; set; } public DateTime CreatedAt { get; set; } public DateTime? RaffledAt { get; set; } public DateTime? CompletedAt { get; set; } public virtual BrandDto Brand { get; set; } public virtual GiftContentDto Content { get; set; } } <|start_filename|>Pds/Pds.Data/Migrations/20211115114236_AddPreviousStatusFieldToGifts.cs<|end_filename|> using Microsoft.EntityFrameworkCore.Migrations; #nullable disable namespace Pds.Data.Migrations { public partial class AddPreviousStatusFieldToGifts : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<int>( name: "PreviousStatus", table: "Gifts", type: "int", nullable: true); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "PreviousStatus", table: "Gifts"); } } } <|start_filename|>Pds/Pds.Core/Exceptions/TokenException.cs<|end_filename|> namespace Pds.Core.Exceptions; public class TokenException : Exception { } <|start_filename|>Pds/Pds.Services/Interfaces/ICostService.cs<|end_filename|> using Pds.Data.Entities; using Pds.Services.Models.Cost; namespace Pds.Services.Interfaces; public interface ICostService { Task<Cost> GetAsync(Guid costId); Task<List<Cost>> GetAllAsync(); Task<Guid> CreateAsync(Cost cost); Task DeleteAsync(Guid costId); Task<Guid> EditAsync(EditCostModel model); Task ArchiveAsync(Guid costId); Task UnarchiveAsync(Guid costId); } <|start_filename|>Pds/Pds.Api.Contracts/Gift/CreateGiftResponse.cs<|end_filename|> namespace Pds.Api.Contracts.Gift; public class CreateGiftResponse { public Guid Id { get; set; } } <|start_filename|>Pds/Pds.Web/Components/Search/Content/ContentsSearch.cs<|end_filename|> using Calabonga.PredicatesBuilder; using System.Linq.Expressions; using Pds.Api.Contracts.Content; using Pds.Api.Contracts.Content.GetContents; namespace Pds.Web.Components.Search.Content; public class ContentsSearch { public Expression<Func<GetContentsContentDto, bool>> GetSearchPredicate(string searchLine) { searchLine = searchLine.ToLower(); var predicate = PredicateBuilder.False<GetContentsContentDto>(); predicate = predicate.Or(c => c.Title.ToLower().Contains(searchLine)); predicate = predicate.Or(c => c.ClientName != null && c.ClientName.ToLower().Contains(searchLine)); predicate = predicate.Or(c => c.EndDate != null && !string.IsNullOrWhiteSpace(c.EndDate.Value.ToString("dd.MM.yyyy")) && c.EndDate.Value.ToString("dd.MM.yyyy").ToLower().Contains(searchLine)); predicate = predicate.Or(c => !string.IsNullOrWhiteSpace(c.ReleaseDate.ToString("dd.MM.yyyy")) && c.ReleaseDate.ToString("dd.MM.yyyy").ToLower().Contains(searchLine)); predicate = predicate.Or(r => r.Brand != null && r.Brand.Name != null && r.Brand.Name.ToLower().Contains(searchLine)); predicate = predicate.Or(r => r.Person != null && r.Person.FirstName != null && r.Person.FirstName.ToLower().Contains(searchLine)); predicate = predicate.Or(r => r.Person != null && r.Person.LastName != null && r.Person.LastName.ToLower().Contains(searchLine)); predicate = predicate.Or(r => r.Person != null && r.Person.ThirdName != null && r.Person.ThirdName.ToLower().Contains(searchLine)); predicate = predicate.Or(r => r.Bill != null && r.Bill.Contact != null && r.Bill.Contact.ToLower().Contains(searchLine)); predicate = predicate.Or(r => r.Bill != null && r.Bill.ContactName != null && r.Bill.ContactName.ToLower().Contains(searchLine)); predicate = predicate.Or(r => r.Bill != null && r.Bill.Value.ToString("N0").Contains(searchLine)); return predicate; } } <|start_filename|>Pds/Pds.Services/Interfaces/IBillService.cs<|end_filename|> using Pds.Data.Entities; using Pds.Services.Models.Bill; namespace Pds.Services.Interfaces; public interface IBillService { Task PayBillAsync(PayBillModel model); Task<Bill> GetAsync(Guid billId); Task<List<Bill>> GetAllPaidAsync(); Task<Guid> CreateAsync(Bill bill); Task<Guid> EditAsync(EditBillModel model); Task ArchiveAsync(Guid billId); Task UnarchiveAsync(Guid billId); Task DeleteAsync(Guid billId); } <|start_filename|>Pds/Pds.Web/Components/Sorting/SortingComponent.razor.cs<|end_filename|> using Microsoft.AspNetCore.Components; using System; namespace Pds.Web.Components.Sorting; public partial class SortingComponent<TField> : ComponentBase where TField : Enum { } <|start_filename|>Pds/Pds.Api.Contracts/Gift/GetGiftResponse.cs<|end_filename|> using System.ComponentModel.DataAnnotations; using Pds.Core.Enums; namespace Pds.Api.Contracts.Gift; public class GetGiftResponse { public Guid Id { get; set; } public string Title { get; set; } public GiftType Type { get; set; } public GiftStatus Status { get; set; } public string Comment { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string ThirdName { get; set; } public string PostalAddress { get; set; } public Guid BrandId { get; set; } public GiftContentDto Content { get; set; } } <|start_filename|>Pds/Pds.Api.Contracts/Person/GetPersonsResponse.cs<|end_filename|> using Pds.Api.Contracts.Paging; namespace Pds.Api.Contracts.Person; public class GetPersonsResponse : PageResult<PersonDto> { } <|start_filename|>Pds/Pds.Web/Components/Pagination/PagingComponent.razor.css<|end_filename|> .paging-position{ justify-content: center; margin-bottom: 0rem; } .btn-paging { margin-right: 4px; } .page-size-selector { margin-left: 10px; color: #fff; background-color: #1b6ec2; height: 31px; padding-left: 10px; } .paging-item { color: #1b6ec2; background-color: #fff; cursor: pointer; } .btn-outline-primary:hover { color: #fff; background-color: #1b6ec2; border-color: #1b6ec2; } .col{ text-align: center; } .paging-info { font-style: italic; font-size: 0.8rem; color: gray; } <|start_filename|>Pds/Pds.Services.Models/Bill/EditBillModel.cs<|end_filename|> using Pds.Core.Enums; namespace Pds.Services.Models.Bill; public class EditBillModel { public Guid Id { get; set; } public decimal Value { get; set; } public string Comment { get; set; } public string ContractNumber { get; set; } public DateTime? ContractDate { get; set; } public bool IsNeedPayNds { get; set; } public DateTime PaidAt { get; set; } public BillType Type { get; set; } public PaymentType PaymentType { get; set; } public Guid BrandId { get; set; } } <|start_filename|>Pds/Pds.Api.Contracts/Bill/EditBillResponse.cs<|end_filename|> namespace Pds.Api.Contracts.Bill; public class EditBillResponse { public Guid Id { get; set; } } <|start_filename|>Pds/Pds.Api/Controllers/BillController.cs<|end_filename|> using AutoMapper; using Microsoft.AspNetCore.Mvc; using Pds.Api.Authentication; using Pds.Api.Contracts; using Pds.Api.Contracts.Bill; using Pds.Data.Entities; using Pds.Services.Interfaces; using Pds.Services.Models.Bill; namespace Pds.Api.Controllers; [Route("api/bills")] [CustomAuthorize] public class BillController : ApiControllerBase { private readonly ILogger<PersonController> logger; private readonly IMapper mapper; private readonly IBillService billService; private readonly IBrandService brandService; private readonly IClientService clientService; public BillController( ILogger<PersonController> logger, IMapper mapper, IBillService billService, IBrandService brandService, IClientService clientService) { this.logger = logger; this.mapper = mapper; this.billService = billService; this.brandService = brandService; this.clientService = clientService; } /// <summary> /// Pay bill /// </summary> /// <returns></returns> [HttpPut("{billId}/pay")] [ProducesResponseType(StatusCodes.Status200OK)] public async Task<IActionResult> PayBill(Guid billId, PayBillPayload payload) { try { var model = new PayBillModel { BillId = billId, Value = payload.Value, Comment = payload.Comment, PaymentType = payload.PaymentType, PaidAt = payload.PaidAt, IsNeedPayNds = payload.IsNeedPayNds, ContractDate = payload.ContractDate, ContractNumber = payload.ContractNumber }; await billService.PayBillAsync(model); return Ok(); } catch (Exception e) { return ExceptionResult(e); } } /// <summary> /// Get bill by id /// </summary> /// <param name="billId"></param> /// <returns></returns> [HttpGet("{billId}")] [ProducesResponseType(typeof(GetBillResponse), StatusCodes.Status200OK)] public async Task<IActionResult> Get(Guid billId) { try { var bill = await billService.GetAsync(billId); var response = mapper.Map<GetBillResponse>(bill); return Ok(response); } catch (Exception e) { return ExceptionResult(e); } } /// <summary> /// Return list of bills /// </summary> /// <param name="request"></param> /// <returns></returns> [HttpGet("paid")] [ProducesResponseType(typeof(GetBillsResponse), StatusCodes.Status200OK)] public async Task<IActionResult> GetAllPaid([FromQuery] GetBillsRequest request) { try { var paidBills = await billService.GetAllPaidAsync(); var response = new GetBillsResponse { Items = mapper.Map<List<BillDto>>(paidBills), Total = paidBills.Count }; return Ok(response); } catch (Exception e) { return ExceptionResult(e); } } /// <summary> /// Return list of brands for checkboxes group /// </summary> [HttpGet] [Route("get-brands")] public async Task<IActionResult> GetListOfBrands() { try { var brands = await brandService.GetBrandsForListsAsync(); var response = mapper.Map<List<BrandDto>>(brands); return Ok(response); } catch (Exception e) { return ExceptionResult(e); } } /// <summary> /// Return list of clients for lookup box /// </summary> [HttpGet] [Route("get-clients")] public async Task<IActionResult> GetListOfClients() { try { var clients = await clientService.GetClientsForListsAsync(); var response = mapper.Map<List<ClientForLookupDto>>(clients); return Ok(response); } catch (Exception e) { return ExceptionResult(e); } } /// <summary> /// Add bill /// </summary> /// <returns></returns> [HttpPost] [ProducesResponseType(typeof(CreateBillResponse), StatusCodes.Status200OK)] public async Task<IActionResult> Create(CreateBillRequest request) { try { if (ModelState.IsValid) { var newBill = mapper.Map<Bill>(request); var billId = await billService.CreateAsync(newBill); return Ok(new CreateBillResponse{Id = billId}); } return BadRequest(); } catch (Exception e) { return ExceptionResult(e); } } /// <summary> /// Edit bill /// </summary> /// <returns></returns> [HttpPut] [ProducesResponseType(typeof(EditBillResponse), StatusCodes.Status200OK)] [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status400BadRequest)] public async Task<IActionResult> Edit(EditBillRequest request) { try { if (!ModelState.IsValid) return BadRequest(); var editBillModel = mapper.Map<EditBillModel>(request); var billId = await billService.EditAsync(editBillModel); return Ok(new EditBillResponse{Id = billId}); } catch (Exception e) { return ExceptionResult(e); } } /// <summary> /// Archive specified bill /// </summary> /// <param name="billId"></param> /// <returns></returns> [HttpPut("{billId}/archive")] [ProducesResponseType(StatusCodes.Status200OK)] public async Task<IActionResult> Archive(Guid billId) { try { await billService.ArchiveAsync(billId); return Ok(); } catch (Exception e) { return ExceptionResult(e); } } /// <summary> /// Unarchive specified bill /// </summary> /// <param name="billId"></param> /// <returns></returns> [HttpPut("{billId}/unarchive")] [ProducesResponseType(StatusCodes.Status200OK)] public async Task<IActionResult> Unarchive(Guid billId) { try { await billService.UnarchiveAsync(billId); return Ok(); } catch (Exception e) { return ExceptionResult(e); } } /// <summary> /// Delete specified bill /// </summary> /// <param name="billId"></param> /// <returns></returns> [HttpDelete("{billId}")] [ProducesResponseType(StatusCodes.Status200OK)] public async Task<IActionResult> Delete(Guid billId) { try { await billService.DeleteAsync(billId); return Ok(); } catch (Exception e) { return ExceptionResult(e); } } } <|start_filename|>Pds/Pds.Api.Contracts/Topic/TopicDto.cs<|end_filename|> using Pds.Api.Contracts.Person; using Pds.Core.Enums; namespace Pds.Api.Contracts.Topic; public class TopicDto { public Guid Id { get; set; } public DateTime CreatedAt { get; set; } public DateTime? UpdatedAt { get; set; } public string Name { get; set; } public ICollection<PersonDto> Persons { get; set; } public TopicStatus Status { get; set; } } <|start_filename|>Pds/Pds.Services/Interfaces/IGiftService.cs<|end_filename|> using Pds.Data.Entities; using Pds.Services.Models.Bill; using Pds.Services.Models.Gift; namespace Pds.Services.Interfaces; public interface IGiftService { Task<Gift> GetAsync(Guid giftId); Task<List<Gift>> GetAllAsync(); Task<Guid> CreateAsync(Gift gift); Task<Guid> EditAsync(EditGiftModel model); Task CompleteAsync(Guid giftId); Task UncompleteAsync(Guid giftId); Task DeleteAsync(Guid giftId); } <|start_filename|>Pds/Pds.Api.Contracts/Cost/GetCostsResponse.cs<|end_filename|> using Pds.Api.Contracts.Paging; namespace Pds.Api.Contracts.Cost; public class GetCostsResponse : PageResult<CostDto> { } <|start_filename|>Pds/Pds.Core/Enums/ContactType.cs<|end_filename|> namespace Pds.Core.Enums; public enum ContactType { Other = 0, Telegram = 1, Instagram = 2, WhatsApp = 3, Email = 4, Phone = 5 } <|start_filename|>Pds/Pds.Api.Contracts/Person/PersonContentDto.cs<|end_filename|> namespace Pds.Api.Contracts.Person; public class PersonContentDto { public Guid Id { get; set; } public string Title { get; set; } } <|start_filename|>Pds/Pds.Web.Models/Person/FilterSettings.cs<|end_filename|> namespace Pds.Web.Models.Person; public class FilterSettings { public List<BrandFilterItem> BrandFilterItems { get; set; } } <|start_filename|>Pds/Pds.Api.Contracts/Topic/CreateTopicRequest.cs<|end_filename|> using System.ComponentModel.DataAnnotations; namespace Pds.Api.Contracts.Topic; public class CreateTopicRequest { [Required, StringLength(300, MinimumLength = 3)] public string Name { get; set; } public ICollection<Guid> People { get; set; } } <|start_filename|>Pds/Pds.Data/Repositories/BillRepository.cs<|end_filename|> using Microsoft.EntityFrameworkCore; using Pds.Core.Enums; using Pds.Data.Entities; using Pds.Data.Repositories.Interfaces; namespace Pds.Data.Repositories; public class BillRepository : RepositoryBase<Bill>, IBillRepository { private readonly ApplicationDbContext context; public BillRepository(ApplicationDbContext context) : base(context) { this.context = context; } public async Task<List<Bill>> GetAllPaidOrderByDateDescAsync() { return await context.Bills .Where(b => b.PaymentStatus == PaymentStatus.Paid) .Include(b=>b.Content) .Include(b=>b.Brand) .OrderByDescending(p =>p.PaidAt) .ToListAsync(); } public async Task<Bill> GetFullByIdAsync(Guid billId) { return await context.Bills .Include(c => c.Content) .Include(c => c.Brand) .Include(c => c.Client) .FirstOrDefaultAsync(c => c.Id == billId); } } <|start_filename|>Pds/Pds.Web/wwwroot/appsettings.LocalDevelopment.json<|end_filename|> { "Auth0": { "Authority": "https://itbeard.eu.auth0.com", "ClientId": "tzfWOiWpwcbm05QhREjkyFQet3KzOyHl" }, "BackendApi": { "Url": "https://localhost:5003" } } <|start_filename|>Pds/Pds.Data/Repositories/RepositoryBase.cs<|end_filename|> using System.Linq.Expressions; using Pds.Core.Exceptions; using Pds.Data.Repositories.Interfaces; using Microsoft.EntityFrameworkCore; namespace Pds.Data.Repositories; public abstract class RepositoryBase<TEntity> : IRepositoryBase<TEntity> where TEntity : class { private readonly ApplicationDbContext context; private readonly DbSet<TEntity> dbSet; protected RepositoryBase(ApplicationDbContext context) { this.context = context; this.dbSet = context.Set<TEntity>(); } public async Task Delete(TEntity entity) { context.Set<TEntity>().Remove(entity); await context.SaveChangesAsync(); } public async Task DeleteRange(ICollection<TEntity> entities) { context.Set<TEntity>().RemoveRange(entities); await context.SaveChangesAsync(); } public async Task<int> Count() { return await context.Set<TEntity>().CountAsync(); } public virtual async Task<List<TEntity>> GetAllAsync() { return await context.Set<TEntity>().AsNoTracking().ToListAsync(); } public async Task<List<TEntity>> FindAllByWhereAsync(Expression<Func<TEntity, bool>> match) { return await context.Set<TEntity>().Where(match).ToListAsync(); } public async Task<List<TEntity>> FindAllByWhereOrderedAscendingAsync( Expression<Func<TEntity, bool>> match, Expression<Func<TEntity, object>> orderBy) { return await context.Set<TEntity>().Where(match).OrderBy(orderBy).ToListAsync(); } public async Task<List<TEntity>> FindAllByWhereOrderedDescendingAsync( Expression<Func<TEntity, bool>> match, Expression<Func<TEntity, object>> orderBy) { return await context.Set<TEntity>().Where(match).OrderByDescending(orderBy).ToListAsync(); } public async Task<bool> AnyAsync(Expression<Func<TEntity, bool>> match) { return await context.Set<TEntity>().AnyAsync(match); } public virtual async Task<TEntity> GetFirstWhereAsync(Expression<Func<TEntity, bool>> match) { return await context.Set<TEntity>().FirstOrDefaultAsync(match); } public virtual async Task<TEntity> UpdateAsync(TEntity entityToUpdate) { try { if (context.Entry(entityToUpdate).State == EntityState.Detached) { dbSet.Attach(entityToUpdate); } context.Entry(entityToUpdate).State = EntityState.Modified; context.ChangeTracker.AutoDetectChangesEnabled = false; await context.SaveChangesAsync(); return entityToUpdate; } catch (Exception e) { throw new RepositoryException(e.Message, e.InnerException, typeof(TEntity).ToString()); } } public virtual async Task<IList<TEntity>> UpdateRangeAsync(IList<TEntity> entities) { var detachedEntities = new List<TEntity>(); context.ChangeTracker.AutoDetectChangesEnabled = false; foreach (var entity in entities) { if (context.Entry(entity).State == EntityState.Detached) { detachedEntities.Add(entity); } context.Entry(entity).State = EntityState.Modified; } dbSet.AttachRange(detachedEntities); await context.SaveChangesAsync(); context.ChangeTracker.AutoDetectChangesEnabled = true; return entities; } public virtual async Task<TEntity> InsertAsync(TEntity entity) { await context.Set<TEntity>().AddAsync(entity); await context.SaveChangesAsync(); return entity; } public virtual async Task<IList<TEntity>> InsertRangeAsync(IList<TEntity> entities, bool saveChanges = true) { await context.Set<TEntity>().AddRangeAsync(entities); if (saveChanges) { await context.SaveChangesAsync(); } return entities; } } <|start_filename|>Pds/Pds.Web/Pages/Persons/Edit.razor.css<|end_filename|> .card-header { margin-bottom: 15px; } .form-group { margin-bottom: 15px; } ::deep input.person-city, ::deep input.person-country{ width: 100px; display: inline-block; margin-left: 10px; } ::deep input.person-rate { width: 80px; display: inline-block; margin-left: 10px; } ::deep label.person-links { margin-right: 17px; } <|start_filename|>Pds/Pds.Web.Models/Content/FilterSettings.cs<|end_filename|> namespace Pds.Web.Models.Content; public class FilterSettings { public List<SocialMediaFilterItem> SocialMediaFilterItems { get; set; } public List<ContentTypeFilterItem> ContentTypeFilterItems { get; set; } public List<BrandFilterItem> BrandFilterItems { get; set; } } <|start_filename|>Pds/Pds.Web/Common/PageHistoryState.cs<|end_filename|> namespace Pds.Web.Common; public class PageHistoryState { private List<string> previousPages; public PageHistoryState() { previousPages = new List<string>(); } public void AddPage(string pageName) { previousPages.Add(pageName); } public string PreviousPage() { if (previousPages.Count > 1) { // You add a page on initialization, so you need to return the 2nd from the last return previousPages.ElementAt(previousPages.Count - 2); } // Can't go back because you didn't navigate enough return previousPages.FirstOrDefault(); } public bool CanGoBack() { return previousPages.Count > 1; } } <|start_filename|>Pds/Pds.Data/Repositories/Interfaces/IBillRepository.cs<|end_filename|> using Pds.Data.Entities; namespace Pds.Data.Repositories.Interfaces; public interface IBillRepository : IRepositoryBase<Bill> { Task<List<Bill>> GetAllPaidOrderByDateDescAsync(); Task<Bill> GetFullByIdAsync(Guid billId); } <|start_filename|>Pds/Pds.Api.Contracts/Gift/GetGiftsResponse.cs<|end_filename|> using Pds.Api.Contracts.Paging; namespace Pds.Api.Contracts.Gift; public class GetGiftsResponse : PageResult<GiftDto> { } <|start_filename|>Pds/Pds.Api.Contracts/Content/ClientForLookupDto.cs<|end_filename|> namespace Pds.Api.Contracts.Content; public class ClientForLookupDto { public Guid? Id { get; set; } public string Name { get; set; } } <|start_filename|>Pds/Pds.Core/Exceptions/Client/ClientEditException.cs<|end_filename|> namespace Pds.Core.Exceptions.Client; public class ClientEditException : Exception, IApiException { public List<string> Errors { get; } public ClientEditException(List<string> errors) { Errors = errors; } public ClientEditException(string message) : base(message) { Errors = new List<string> { message }; } public ClientEditException(string message, Exception inner) : base(message, inner) { } } <|start_filename|>Pds/Pds.Data/Entities/Gift.cs<|end_filename|> using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Pds.Core.Enums; namespace Pds.Data.Entities; public class Gift : EntityBase { [Required] public string Title { get; set; } public string Comment { get; set; } [Required] public GiftStatus Status { get; set; } public GiftStatus? PreviousStatus { get; set; } [Required] public GiftType Type { get; set; } [Column(TypeName = "varchar(300)")] public string FirstName { get; set; } [Column(TypeName = "varchar(300)")] public string LastName { get; set; } [Column(TypeName = "varchar(300)")] public string ThirdName { get; set; } public string PostalAddress { get; set; } public DateTime? RaffledAt { get; set; } public DateTime? CompletedAt { get; set; } public Guid BrandId { get; set; } public Guid? ContentId { get; set; } public virtual Brand Brand { get; set; } public virtual Content Content { get; set; } } <|start_filename|>Pds/Pds.Web.Models/Gift/FilterSettings.cs<|end_filename|> namespace Pds.Web.Models.Gift; public class FilterSettings { public List<BrandFilterItem> BrandFilterItems { get; set; } public List<GiftTypeFilterItem> GiftTypeFilterItems { get; set; } public List<GiftStatusFilterItem> GiftStatusFilterItems { get; set; } public DateTime? CreatedFrom { get; set; } public DateTime? CreatedTo { get; set; } public DateTime? RaffledFrom { get; set; } public DateTime? RaffledTo { get; set; } public DateTime? CompletedFrom { get; set; } public DateTime? CompletedTo { get; set; } } <|start_filename|>Pds/Pds.Services.Models/Content/EditContentModel.cs<|end_filename|> using Pds.Core.Enums; namespace Pds.Services.Models.Content; public class EditContentModel { public Guid Id { get; set; } public ContentType Type { get; set; } public SocialMediaType SocialMediaType { get; set; } public string Title { get; set; } public string Comment { get; set; } public DateTime ReleaseDate { get; set; } public DateTime? EndDate { get; set; } public bool IsContentFree { get; set; } public EditContentBillModel Bill { get; set; } public Guid? PersonId { get; set; } } <|start_filename|>Pds/Pds.Api.Contracts/Person/ResourceDto.cs<|end_filename|> using System.ComponentModel.DataAnnotations; namespace Pds.Api.Contracts.Person; public class ResourceDto { [Required] public string Name { get; set; } [Required] public string Url { get; set; } } <|start_filename|>Pds/Pds.Web/Common/ApiResponse.cs<|end_filename|> using System.Net; using Microsoft.AspNetCore.Components.Forms; namespace Pds.Web.Common; public class ApiResponse<T> { public ApiResponse(HttpResponseMessage response, string rawPayload) { IsSuccessStatusCode = response.IsSuccessStatusCode; Code = response.StatusCode; RawPayload = rawPayload; } public HttpStatusCode Code { get; } public bool IsSuccessStatusCode { get; } public string RawPayload { get;} public T Payload { get; set; } public void AddErrors(ValidationMessageStore msgStore, EditContext editContext) { var errors = JsonConvert.DeserializeObject<List<string>>(RawPayload); foreach (var error in errors) { msgStore.Add(editContext.Field(string.Empty), error); } editContext.NotifyValidationStateChanged(); } } <|start_filename|>Pds/Pds.Data/Migrations/20210322104734_AddOrders.cs<|end_filename|> using System; using Microsoft.EntityFrameworkCore.Migrations; namespace Pds.Data.Migrations { public partial class AddOrders : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_Resources_Persons_PersonId", table: "Resources"); migrationBuilder.AlterColumn<Guid>( name: "PersonId", table: "Resources", type: "uniqueidentifier", nullable: false, defaultValue: new Guid("00000000-0000-0000-0000-000000000000"), oldClrType: typeof(Guid), oldType: "uniqueidentifier", oldNullable: true); migrationBuilder.CreateTable( name: "Channels", columns: table => new { Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), Name = table.Column<string>(type: "varchar(300)", nullable: false), Url = table.Column<string>(type: "varchar(300)", nullable: false), CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false), UpdatedAt = table.Column<DateTime>(type: "datetime2", nullable: true) }, constraints: table => { table.PrimaryKey("PK_Channels", x => x.Id); }); migrationBuilder.CreateTable( name: "Clients", columns: table => new { Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), Name = table.Column<string>(type: "varchar(300)", nullable: false), Comment = table.Column<string>(type: "nvarchar(max)", nullable: true), CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false), UpdatedAt = table.Column<DateTime>(type: "datetime2", nullable: true) }, constraints: table => { table.PrimaryKey("PK_Clients", x => x.Id); }); migrationBuilder.CreateTable( name: "Contents", columns: table => new { Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), Title = table.Column<string>(type: "varchar(300)", nullable: false), Type = table.Column<int>(type: "int", nullable: false), SocialMediaType = table.Column<int>(type: "int", nullable: false, defaultValue: 1), Comment = table.Column<string>(type: "nvarchar(max)", nullable: false), ReleaseDateUtc = table.Column<DateTime>(type: "datetime2", nullable: false), EndDateUtc = table.Column<DateTime>(type: "datetime2", nullable: true), PrimaryContact = table.Column<string>(type: "varchar(300)", nullable: false), OrderId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), ChannelId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), PersonId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false), UpdatedAt = table.Column<DateTime>(type: "datetime2", nullable: true) }, constraints: table => { table.PrimaryKey("PK_Contents", x => x.Id); table.ForeignKey( name: "FK_Contents_Channels_ChannelId", column: x => x.ChannelId, principalTable: "Channels", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Contents_Persons_PersonId", column: x => x.PersonId, principalTable: "Persons", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "Orders", columns: table => new { Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), Cost = table.Column<decimal>(type: "decimal(18,2)", nullable: false), Status = table.Column<int>(type: "int", nullable: false), Comment = table.Column<string>(type: "nvarchar(max)", nullable: false), PrimaryContact = table.Column<string>(type: "varchar(300)", nullable: false), ContentId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), ClientId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), ChannelId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false), UpdatedAt = table.Column<DateTime>(type: "datetime2", nullable: true) }, constraints: table => { table.PrimaryKey("PK_Orders", x => x.Id); table.ForeignKey( name: "FK_Orders_Channels_ChannelId", column: x => x.ChannelId, principalTable: "Channels", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_Orders_Clients_ClientId", column: x => x.ClientId, principalTable: "Clients", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Orders_Contents_ContentId", column: x => x.ContentId, principalTable: "Contents", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_Contents_ChannelId", table: "Contents", column: "ChannelId"); migrationBuilder.CreateIndex( name: "IX_Contents_PersonId", table: "Contents", column: "PersonId"); migrationBuilder.CreateIndex( name: "IX_Orders_ChannelId", table: "Orders", column: "ChannelId"); migrationBuilder.CreateIndex( name: "IX_Orders_ClientId", table: "Orders", column: "ClientId"); migrationBuilder.CreateIndex( name: "IX_Orders_ContentId", table: "Orders", column: "ContentId", unique: true); migrationBuilder.AddForeignKey( name: "FK_Resources_Persons_PersonId", table: "Resources", column: "PersonId", principalTable: "Persons", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.InsertData( table: "Channels", columns: new[] { "Id", "CreatedAt", "Name", "UpdatedAt", "Url" }, values: new object[] { new Guid("5aa23fa2-4b73-4a3f-c3d4-08d8d2705c5f"), new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), "АйТиБорода", null, "https://youtube.com/itbeard" }); migrationBuilder.InsertData( table: "Channels", columns: new[] { "Id", "CreatedAt", "Name", "UpdatedAt", "Url" }, values: new object[] { new Guid("6bb23fa2-4b73-4a3f-c3d4-08d8d2705c5f"), new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), "Тёмный Лес", null, "https://youtube.com/thedarkless" }); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_Resources_Persons_PersonId", table: "Resources"); migrationBuilder.DropTable( name: "Orders"); migrationBuilder.DropTable( name: "Clients"); migrationBuilder.DropTable( name: "Contents"); migrationBuilder.DropTable( name: "Channels"); migrationBuilder.AlterColumn<Guid>( name: "PersonId", table: "Resources", type: "uniqueidentifier", nullable: true, oldClrType: typeof(Guid), oldType: "uniqueidentifier"); migrationBuilder.AddForeignKey( name: "FK_Resources_Persons_PersonId", table: "Resources", column: "PersonId", principalTable: "Persons", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.DeleteData( table: "Channels", keyColumn: "Id", keyValue: new Guid("<KEY>")); migrationBuilder.DeleteData( table: "Channels", keyColumn: "Id", keyValue: new Guid("6bb23fa2-4b73-4a3f-c3d4-08d8d2705c5f")); } } } <|start_filename|>Pds/Pds.Api.Contracts/Person/EditPersonResponse.cs<|end_filename|> namespace Pds.Api.Contracts.Person; public class EditPersonResponse { public Guid Id { get; set; } } <|start_filename|>Pds/Pds.Core/Enums/GiftType.cs<|end_filename|> namespace Pds.Core.Enums; public enum GiftType { Other = 0, // Прочий доход Stickers = 1, // Стикера Book = 2, // Книга } <|start_filename|>Pds/Pds.Data/Entities/Person.cs<|end_filename|> using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using Pds.Core.Enums; namespace Pds.Data.Entities; public class Person : EntityBase { [Required] [Column(TypeName = "varchar(300)")] public string FirstName { get; set; } [Required] [Column(TypeName = "varchar(300)")] public string LastName { get; set; } [Column(TypeName = "varchar(300)")] public string ThirdName { get; set; } public string Info { get; set; } public int? Rate { get; set; } public string Country { get; set; } public string City { get; set; } public string Latitude { get; set; } public string Longitude { get; set; } public string Topics { get; set; } public PersonStatus Status { get; set; } public DateTime? ArchivedAt { get; set; } public DateTime? UnarchivedAt { get; set; } public virtual ICollection<Resource> Resources { get; set; } public virtual ICollection<Content> Contents { get; set; } public virtual ICollection<Brand> Brands { get; set; } } <|start_filename|>Pds/Pds.Api.Contracts/Content/PersonForLookupDto.cs<|end_filename|> namespace Pds.Api.Contracts.Content; public class PersonForLookupDto { public Guid? Id { get; set; } public string FullName { get; set; } } <|start_filename|>Pds/Pds.Data/Migrations/20210409001555_UpdateReleaseDate.cs<|end_filename|> using Microsoft.EntityFrameworkCore.Migrations; namespace Pds.Data.Migrations { public partial class UpdateReleaseDate : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.RenameColumn( name: "ReleaseDateUtc", table: "Contents", newName: "ReleaseDate"); migrationBuilder.RenameColumn( name: "EndDateUtc", table: "Contents", newName: "EndDate"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.RenameColumn( name: "ReleaseDate", table: "Contents", newName: "ReleaseDateUtc"); migrationBuilder.RenameColumn( name: "EndDate", table: "Contents", newName: "EndDateUtc"); } } } <|start_filename|>Pds/Pds.Web.Models/Gift/GiftTypeFilterItem.cs<|end_filename|> using Pds.Core.Enums; namespace Pds.Web.Models.Gift; public class GiftTypeFilterItem { public GiftType GiftType { get; set; } public bool IsSelected { get; set; } } <|start_filename|>Pds/Pds.Services.Models/Content/EditContentBillModel.cs<|end_filename|> using Pds.Core.Enums; namespace Pds.Services.Models.Content; public class EditContentBillModel { public Guid ClientId { get; set; } public string Contact { get; set; } public string ContactName { get; set; } public ContactType ContactType { get; set; } public decimal Value { get; set; } } <|start_filename|>Pds/Pds.Data/Repositories/Interfaces/IClientRepository.cs<|end_filename|> using Pds.Data.Entities; namespace Pds.Data.Repositories.Interfaces; public interface IClientRepository : IRepositoryBase<Client> { Task<List<Client>> GetAllOrderByNameAsync(); Task<List<Client>> GetAllWithBillsOrderByNameAsync(); Task<Client> GetFullByIdAsync(Guid clientId); Task<bool> IsExistsByNameAsync(string clientName); } <|start_filename|>Pds/Pds.Web/Common/TitleExtension.cs<|end_filename|> namespace Pds.Web.Common; public static class TitleExtension { public static string WithSuffix(string title, bool nosuffix = false) { return nosuffix ? title : title + $" / {Constants.AppName}"; } } <|start_filename|>Pds/Pds.Api.Contracts/Person/CreatePersonResponse.cs<|end_filename|> namespace Pds.Api.Contracts.Person; public class CreatePersonResponse { public Guid Id { get; set; } } <|start_filename|>Pds/Pds.Web/Pages/Gifts/List/Body.razor.css<|end_filename|> .card-header { margin-bottom: 15px; } .actions-header { width: 100px; } .id-header, .paid-date-header { width: 70px; text-align: center; } .paid-date-row { text-align: center; } .release-date-row { text-align: center; } .release-date-row span { font-size: 0.89rem; background-color: white; padding: 2px 4px; border-radius: 4px; } .gift-type { font-size: 0.77rem; background-color: darkgray; padding: 2px 4px; border-radius: 4px; color: white; } .gift-cost-row span { font-weight: bold; font-size: 1rem; margin-right: 5px; } .title-overall-info{ font-style: italic; font-size: 1rem; background-color: green; padding: 2px 4px; border-radius: 4px; color: #eee; } .status-new { background-color: lightpink; } .status-raffled{ background-color: lightblue; } .status-waiting{ background-color: lightgreen; } .status-strange{ background-color: #fecd82; } .status-completed, .status-completed a { background-color: gainsboro; color: #bbb !important; } .create-date { font-size: 0.7rem; background-color: white; padding: 2px 4px; border-radius: 4px; } .raffle-date { font-size: 0.7rem; background-color: dodgerblue; padding: 2px 4px; border-radius: 4px; color: white; } .complete-date { font-size: 0.7rem; background-color: gray; padding: 2px 4px; border-radius: 4px; color: white; } <|start_filename|>Pds/Pds.Api.Contracts/Cost/ContentForLookupDto.cs<|end_filename|> namespace Pds.Api.Contracts.Cost; public class ContentForLookupDto { public Guid? Id { get; set; } public string Title { get; set; } } <|start_filename|>Pds/Pds.Data/Migrations/20210405111506_UpdateTopicEntityAddArchivingProperties.cs<|end_filename|> using System; using Microsoft.EntityFrameworkCore.Migrations; namespace Pds.Data.Migrations { public partial class UpdateTopicEntityAddArchivingProperties : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<DateTime>( name: "ArchivedAt", table: "Topics", type: "datetime2", nullable: true); migrationBuilder.AddColumn<int>( name: "Status", table: "Topics", type: "int", nullable: false, defaultValue: 0); migrationBuilder.AddColumn<DateTime>( name: "UnarchivedAt", table: "Topics", type: "datetime2", nullable: true); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "ArchivedAt", table: "Topics"); migrationBuilder.DropColumn( name: "Status", table: "Topics"); migrationBuilder.DropColumn( name: "UnarchivedAt", table: "Topics"); } } } <|start_filename|>Pds/Pds.Api.Contracts/Bill/GetBillResponse.cs<|end_filename|> using Pds.Core.Enums; namespace Pds.Api.Contracts.Bill; public class GetBillResponse { public Guid Id { get; set; } public decimal Value { get; set; } public string Comment { get; set; } public string ContractNumber { get; set; } public DateTime? ContractDate { get; set; } public bool IsNeedPayNds { get; set; } public DateTime PaidAt { get; set; } public BillType Type { get; set; } public PaymentType PaymentType { get; set; } public Guid BrandId { get; set; } public Guid? ClientId { get; set; } public BillContentDto Content { get; set; } } <|start_filename|>Pds/Pds.Data/Migrations/20210127231349_UpdatePersonsAndResourcesTables.cs<|end_filename|> using Microsoft.EntityFrameworkCore.Migrations; namespace Pds.Data.Migrations { public partial class UpdatePersonsAndResourcesTables : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_Resources_Persons_PersonID", table: "Resources"); migrationBuilder.RenameColumn( name: "PersonID", table: "Resources", newName: "PersonId"); migrationBuilder.RenameColumn( name: "ID", table: "Resources", newName: "Id"); migrationBuilder.RenameIndex( name: "IX_Resources_PersonID", table: "Resources", newName: "IX_Resources_PersonId"); migrationBuilder.RenameColumn( name: "ID", table: "Persons", newName: "Id"); migrationBuilder.AlterColumn<string>( name: "Url", table: "Resources", type: "nvarchar(max)", nullable: false, defaultValue: "", oldClrType: typeof(string), oldType: "nvarchar(max)", oldNullable: true); migrationBuilder.AlterColumn<string>( name: "Name", table: "Resources", type: "nvarchar(max)", nullable: false, defaultValue: "", oldClrType: typeof(string), oldType: "nvarchar(max)", oldNullable: true); migrationBuilder.AlterColumn<int>( name: "Status", table: "Persons", type: "int", nullable: false, defaultValue: 1, oldClrType: typeof(int), oldType: "int"); migrationBuilder.AddForeignKey( name: "FK_Resources_Persons_PersonId", table: "Resources", column: "PersonId", principalTable: "Persons", principalColumn: "Id", onDelete: ReferentialAction.Restrict); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_Resources_Persons_PersonId", table: "Resources"); migrationBuilder.RenameColumn( name: "PersonId", table: "Resources", newName: "PersonID"); migrationBuilder.RenameColumn( name: "Id", table: "Resources", newName: "ID"); migrationBuilder.RenameIndex( name: "IX_Resources_PersonId", table: "Resources", newName: "IX_Resources_PersonID"); migrationBuilder.RenameColumn( name: "Id", table: "Persons", newName: "ID"); migrationBuilder.AlterColumn<string>( name: "Url", table: "Resources", type: "nvarchar(max)", nullable: true, oldClrType: typeof(string), oldType: "nvarchar(max)"); migrationBuilder.AlterColumn<string>( name: "Name", table: "Resources", type: "nvarchar(max)", nullable: true, oldClrType: typeof(string), oldType: "nvarchar(max)"); migrationBuilder.AlterColumn<int>( name: "Status", table: "Persons", type: "int", nullable: false, oldClrType: typeof(int), oldType: "int", oldDefaultValue: 1); migrationBuilder.AddForeignKey( name: "FK_Resources_Persons_PersonID", table: "Resources", column: "PersonID", principalTable: "Persons", principalColumn: "ID", onDelete: ReferentialAction.Restrict); } } } <|start_filename|>Pds/Pds.Api.Contracts/Content/EditContent/EditContentBillDto.cs<|end_filename|> using System.ComponentModel.DataAnnotations; using Pds.Core.Attributes; using Pds.Core.Enums; namespace Pds.Api.Contracts.Content.EditContent; public class EditContentBillDto { [GuidNotEmpty] public Guid ClientId { get; set; } [Required] public string Contact { get; set; } [Required] public string ContactName { get; set; } [Required, EnumDataType(typeof(ContactType))] public ContactType ContactType { get; set; } [Range(10, Double.MaxValue, ErrorMessage = "Значение поля {0} должно быть больше чем {1}.")] public decimal Value { get; set; } } <|start_filename|>Pds/Pds.Services/Interfaces/IContentService.cs<|end_filename|> using Pds.Data.Entities; using Pds.Services.Models.Content; namespace Pds.Services.Interfaces; public interface IContentService { Task<List<Content>> GetAllAsync(); Task<Content> GetAsync(Guid contentId); Task<Guid> CreateAsync(CreateContentModel model); Task<Guid> EditAsync(EditContentModel model); Task DeleteAsync(Guid clientId); Task ArchiveAsync(Guid contentId); Task UnarchiveAsync(Guid contentId); Task<List<Content>> GetContentsForListsAsync(); } <|start_filename|>Pds/Pds.Data/Migrations/20211114120230_AddGiftEntity.cs<|end_filename|> using System; using Microsoft.EntityFrameworkCore.Migrations; #nullable disable namespace Pds.Data.Migrations { public partial class AddGiftEntity : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Gifts", columns: table => new { Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), Title = table.Column<string>(type: "nvarchar(max)", nullable: false), Comment = table.Column<string>(type: "nvarchar(max)", nullable: true), Status = table.Column<int>(type: "int", nullable: false), Type = table.Column<int>(type: "int", nullable: false), FirstName = table.Column<string>(type: "varchar(300)", nullable: true), LastName = table.Column<string>(type: "varchar(300)", nullable: true), ThirdName = table.Column<string>(type: "varchar(300)", nullable: true), PostalAddress = table.Column<string>(type: "nvarchar(max)", nullable: true), BrandId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), ContentId = table.Column<Guid>(type: "uniqueidentifier", nullable: true), CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false), UpdatedAt = table.Column<DateTime>(type: "datetime2", nullable: true) }, constraints: table => { table.PrimaryKey("PK_Gifts", x => x.Id); table.ForeignKey( name: "FK_Gifts_Brands_BrandId", column: x => x.BrandId, principalTable: "Brands", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Gifts_Contents_ContentId", column: x => x.ContentId, principalTable: "Contents", principalColumn: "Id"); }); migrationBuilder.CreateIndex( name: "IX_Gifts_BrandId", table: "Gifts", column: "BrandId"); migrationBuilder.CreateIndex( name: "IX_Gifts_ContentId", table: "Gifts", column: "ContentId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Gifts"); } } } <|start_filename|>Pds/Pds.Data/Migrations/20210330221602_RemoveDefaultSocialMediaTypeValue.cs<|end_filename|> using Microsoft.EntityFrameworkCore.Migrations; namespace Pds.Data.Migrations { public partial class RemoveDefaultSocialMediaTypeValue : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AlterColumn<int>( name: "SocialMediaType", table: "Contents", type: "int", nullable: false, oldClrType: typeof(int), oldType: "int", oldDefaultValue: 1); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.AlterColumn<int>( name: "SocialMediaType", table: "Contents", type: "int", nullable: false, defaultValue: 1, oldClrType: typeof(int), oldType: "int"); } } } <|start_filename|>Pds/Pds.Data/Repositories/CostRepository.cs<|end_filename|> using Microsoft.EntityFrameworkCore; using Pds.Data.Entities; using Pds.Data.Repositories.Interfaces; namespace Pds.Data.Repositories; public class CostRepository : RepositoryBase<Cost>, ICostRepository { private readonly ApplicationDbContext context; public CostRepository(ApplicationDbContext context) : base(context) { this.context = context; } public async Task<Cost> GetFullByIdAsync(Guid costId) { return await context.Costs .Include(c => c.Brand) .Include(c => c.Content) .FirstOrDefaultAsync(c => c.Id == costId); } public async Task<List<Cost>> GetAllOrderByDateDescAsync() { return await context.Costs .Include(b=>b.Content) .Include(b=>b.Brand) .OrderByDescending(p =>p.PaidAt) .ToListAsync(); } } <|start_filename|>Pds/Pds.Api.Contracts/Content/GetContent/GetContentBillClientDto.cs<|end_filename|> namespace Pds.Api.Contracts.Content.GetContent; public class GetContentBillClientDto { public Guid Id { get; set; } public string Name { get; set; } public string Comment { get; set; } } <|start_filename|>Pds/Pds.Data/Repositories/ClientRepository.cs<|end_filename|> using Microsoft.EntityFrameworkCore; using Pds.Data.Entities; using Pds.Data.Repositories.Interfaces; namespace Pds.Data.Repositories; public class ClientRepository : RepositoryBase<Client>, IClientRepository { private readonly ApplicationDbContext context; public ClientRepository(ApplicationDbContext context) : base(context) { this.context = context; } public async Task<List<Client>> GetAllOrderByNameAsync() { return await context.Clients .OrderBy(p =>p.Name) .ToListAsync(); } public async Task<List<Client>> GetAllWithBillsOrderByNameAsync() { return await context.Clients .Include(c=>c.Bills) .OrderBy(p =>p.Name) .ToListAsync(); } public async Task<Client> GetFullByIdAsync(Guid clientId) { return await context.Clients .Include(c => c.Bills) .FirstOrDefaultAsync(c => c.Id == clientId); } public async Task<bool> IsExistsByNameAsync(string clientName) { var client = await context.Clients .FirstOrDefaultAsync(c => c.Name.ToLower().Trim() == clientName.ToLower().Trim()); return client != null; } } <|start_filename|>Pds/Pds.Web/Pages/Gifts/GiftHelper.cs<|end_filename|> using Pds.Api.Contracts.Content; using Pds.Core.Enums; namespace Pds.Web.Pages.Gifts; public static class GiftHelper { public static string GetGiftBgColorClass(GiftStatus giftStatus) { return giftStatus switch { GiftStatus.New => "status-new", GiftStatus.Raffled => "status-raffled", GiftStatus.Waiting => "status-waiting", GiftStatus.Strange => "status-strange", GiftStatus.Completed => "status-completed", _ => string.Empty }; } } <|start_filename|>Pds/Pds.Api.Contracts/Person/EditPersonRequest.cs<|end_filename|> using System.ComponentModel.DataAnnotations; namespace Pds.Api.Contracts.Person; public class EditPersonRequest { [Required] public Guid Id { get; set; } [Required] public string FirstName { get; set; } [Required] public string LastName { get; set; } public string ThirdName { get; set; } public string Country { get; set; } public string City { get; set; } public string Topics { get; set; } public string Info { get; set; } public int? Rate { get; set; } public List<BrandForCheckboxesDto> Brands { get; set; } public List<ResourceDto> Resources { get; set; } } <|start_filename|>Pds/Pds.Web.Models/Bill/BillTypeFilterItem.cs<|end_filename|> using Pds.Core.Enums; namespace Pds.Web.Models.Bill; public class BillTypeFilterItem { public BillType BillType { get; set; } public bool IsSelected { get; set; } } <|start_filename|>Pds/Pds.Data/Migrations/20210401221958_RenameChannelsToBrands.cs<|end_filename|> using System; using Microsoft.EntityFrameworkCore.Migrations; namespace Pds.Data.Migrations { public partial class RenameChannelsToBrands : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_Bills_Channels_ChannelId", table: "Bills"); migrationBuilder.DropForeignKey( name: "FK_Contents_Channels_ChannelId", table: "Contents"); migrationBuilder.DropTable( name: "ChannelPerson"); migrationBuilder.DropTable( name: "Channels"); migrationBuilder.RenameColumn( name: "ChannelId", table: "Contents", newName: "BrandId"); migrationBuilder.RenameIndex( name: "IX_Contents_ChannelId", table: "Contents", newName: "IX_Contents_BrandId"); migrationBuilder.RenameColumn( name: "ChannelId", table: "Bills", newName: "BrandId"); migrationBuilder.RenameIndex( name: "IX_Bills_ChannelId", table: "Bills", newName: "IX_Bills_BrandId"); migrationBuilder.CreateTable( name: "Brands", columns: table => new { Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), Name = table.Column<string>(type: "varchar(300)", nullable: false), Url = table.Column<string>(type: "varchar(300)", nullable: false), CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false), UpdatedAt = table.Column<DateTime>(type: "datetime2", nullable: true) }, constraints: table => { table.PrimaryKey("PK_Brands", x => x.Id); }); migrationBuilder.CreateTable( name: "BrandPerson", columns: table => new { BrandsId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), PersonsId = table.Column<Guid>(type: "uniqueidentifier", nullable: false) }, constraints: table => { table.PrimaryKey("PK_BrandPerson", x => new { x.BrandsId, x.PersonsId }); table.ForeignKey( name: "FK_BrandPerson_Brands_BrandsId", column: x => x.BrandsId, principalTable: "Brands", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_BrandPerson_Persons_PersonsId", column: x => x.PersonsId, principalTable: "Persons", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.InsertData( table: "Brands", columns: new[] { "Id", "CreatedAt", "Name", "UpdatedAt", "Url" }, values: new object[] { new Guid("5aa23fa2-4b73-4a3f-c3d4-08d8d2705c5f"), new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), "АйТиБорода", null, "https://youtube.com/itbeard" }); migrationBuilder.InsertData( table: "Brands", columns: new[] { "Id", "CreatedAt", "Name", "UpdatedAt", "Url" }, values: new object[] { new Guid("6bb23fa2-4b73-4a3f-c3d4-08d8d2705c5f"), new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), "Тёмный Лес", null, "https://youtube.com/thedarkless" }); migrationBuilder.CreateIndex( name: "IX_BrandPerson_PersonsId", table: "BrandPerson", column: "PersonsId"); migrationBuilder.AddForeignKey( name: "FK_Bills_Brands_BrandId", table: "Bills", column: "BrandId", principalTable: "Brands", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Contents_Brands_BrandId", table: "Contents", column: "BrandId", principalTable: "Brands", principalColumn: "Id", onDelete: ReferentialAction.Cascade); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_Bills_Brands_BrandId", table: "Bills"); migrationBuilder.DropForeignKey( name: "FK_Contents_Brands_BrandId", table: "Contents"); migrationBuilder.DropTable( name: "BrandPerson"); migrationBuilder.DropTable( name: "Brands"); migrationBuilder.RenameColumn( name: "BrandId", table: "Contents", newName: "ChannelId"); migrationBuilder.RenameIndex( name: "IX_Contents_BrandId", table: "Contents", newName: "IX_Contents_ChannelId"); migrationBuilder.RenameColumn( name: "BrandId", table: "Bills", newName: "ChannelId"); migrationBuilder.RenameIndex( name: "IX_Bills_BrandId", table: "Bills", newName: "IX_Bills_ChannelId"); migrationBuilder.CreateTable( name: "Channels", columns: table => new { Id = table.Column<Guid>(type: "uniqueidentifier", nullable: false), CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false), Name = table.Column<string>(type: "varchar(300)", nullable: false), UpdatedAt = table.Column<DateTime>(type: "datetime2", nullable: true), Url = table.Column<string>(type: "varchar(300)", nullable: false) }, constraints: table => { table.PrimaryKey("PK_Channels", x => x.Id); }); migrationBuilder.CreateTable( name: "ChannelPerson", columns: table => new { ChannelsId = table.Column<Guid>(type: "uniqueidentifier", nullable: false), PersonsId = table.Column<Guid>(type: "uniqueidentifier", nullable: false) }, constraints: table => { table.PrimaryKey("PK_ChannelPerson", x => new { x.ChannelsId, x.PersonsId }); table.ForeignKey( name: "FK_ChannelPerson_Channels_ChannelsId", column: x => x.ChannelsId, principalTable: "Channels", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_ChannelPerson_Persons_PersonsId", column: x => x.PersonsId, principalTable: "Persons", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.InsertData( table: "Channels", columns: new[] { "Id", "CreatedAt", "Name", "UpdatedAt", "Url" }, values: new object[] { new Guid("5aa23fa2-4b73-4a3f-c3d4-08d8d2705c5f"), new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), "АйТиБорода", null, "https://youtube.com/itbeard" }); migrationBuilder.InsertData( table: "Channels", columns: new[] { "Id", "CreatedAt", "Name", "UpdatedAt", "Url" }, values: new object[] { new Guid("6bb23fa2-4b73-4a3f-c3d4-08d8d2705c5f"), new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), "Тёмный Лес", null, "https://youtube.com/thedarkless" }); migrationBuilder.CreateIndex( name: "IX_ChannelPerson_PersonsId", table: "ChannelPerson", column: "PersonsId"); migrationBuilder.AddForeignKey( name: "FK_Bills_Channels_ChannelId", table: "Bills", column: "ChannelId", principalTable: "Channels", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Contents_Channels_ChannelId", table: "Contents", column: "ChannelId", principalTable: "Channels", principalColumn: "Id", onDelete: ReferentialAction.Cascade); } } } <|start_filename|>Pds/Pds.Web/Pages/Gifts/Create.razor.css<|end_filename|> .card-header { margin-bottom: 15px; } .form-group { margin-bottom: 15px; } ::deep input.bill-cost{ width: 120px; display: inline-block; margin-left: 10px; margin-right: 10px; } ::deep input.pay-date{ width: 150px; display: inline-block; margin-left: 10px; margin-right: 10px; } .label-required::after{ content: "*"; color: red; margin-left: 3px; } .contact-type { margin-top: 5px; } <|start_filename|>Pds/Pds.Api.Tests/CreatePersonRequestTests.cs<|end_filename|> using System.ComponentModel.DataAnnotations; using AutoFixture; using NUnit.Framework; using Pds.Api.Contracts.Person; namespace Pds.Api.Tests; public class CreatePersonRequestTests { [Test] public void Validate_ShouldReturnFalse() { // arrange var request = new CreatePersonRequest(); var context = new ValidationContext(request, null, null); var results = new List<ValidationResult>(); // act var isModelStateValid = Validator.TryValidateObject(request, context, results, true); // assert Assert.False(isModelStateValid); } [Test] public void Validate_ShouldReturnTrue() { // arrange var fixture = new Fixture(); var request = new CreatePersonRequest { FirstName = fixture.Create<string>(), LastName = fixture.Create<string>() }; var context = new ValidationContext(request, null, null); var results = new List<ValidationResult>(); // act var isModelStateValid = Validator.TryValidateObject(request, context, results, true); // assert Assert.True(isModelStateValid); } } <|start_filename|>Pds/Pds.Api.Contracts/Topic/CheckBoxPersonDto.cs<|end_filename|> using Pds.Api.Contracts.Person; namespace Pds.Api.Contracts.Topic; public class CheckBoxPersonDto : PersonDto { public CheckBoxPersonDto(PersonDto personDto) { Id = personDto.Id; FullName = personDto.FullName; Location = personDto.Location; Info = personDto.Info; Rate = personDto.Rate; Status = personDto.Status; Resources = personDto.Resources; Contents = personDto.Contents; } public bool IsSelected { get; set; } } <|start_filename|>Pds/Pds.Services/Services/CostService.cs<|end_filename|> using Pds.Core.Enums; using Pds.Core.Exceptions.Content; using Pds.Core.Exceptions.Cost; using Pds.Data; using Pds.Data.Entities; using Pds.Services.Interfaces; using Pds.Services.Models.Cost; namespace Pds.Services.Services; public class CostService : ICostService { private readonly IUnitOfWork unitOfWork; public CostService(IUnitOfWork unitOfWork) { this.unitOfWork = unitOfWork; } public async Task<Cost> GetAsync(Guid costId) { return await unitOfWork.Costs.GetFullByIdAsync(costId); } public async Task<List<Cost>> GetAllAsync() { return await unitOfWork.Costs.GetAllOrderByDateDescAsync(); } public async Task<Guid> CreateAsync(Cost cost) { if (cost == null) { throw new ArgumentNullException(nameof(cost)); } cost.CreatedAt = DateTime.UtcNow; cost.Status = CostStatus.Active; var result = await unitOfWork.Costs.InsertAsync(cost); return result.Id; } public async Task<Guid> EditAsync(EditCostModel model) { if (model == null) { throw new CostEditException($"Модель запроса пуста."); } var cost = await unitOfWork.Costs.GetFullByIdAsync(model.Id); if (cost == null) { throw new CostEditException($"Расход с id {model.Id} не найден."); } if (cost.Status == CostStatus.Archived) { throw new ContentEditException($"Нельзя редактировать архивный расход."); } cost.UpdatedAt = DateTime.UtcNow; cost.Value = model.Value; cost.Comment = model.Comment; cost.PaidAt = model.PaidAt; cost.Comment = model.Comment; cost.Type = model.Type; cost.BrandId = model.BrandId; cost.ContentId = model.ContentId != null && model.ContentId.Value == Guid.Empty ? null : model.ContentId;; var result = await unitOfWork.Costs.UpdateAsync(cost); return result.Id; } public async Task ArchiveAsync(Guid costId) { var cost = await unitOfWork.Costs.GetFirstWhereAsync(p => p.Id == costId); if (cost != null) { cost.Status = CostStatus.Archived; cost.UpdatedAt = DateTime.UtcNow; await unitOfWork.Costs.UpdateAsync(cost); } } public async Task UnarchiveAsync(Guid costId) { var cost = await unitOfWork.Costs.GetFirstWhereAsync(p => p.Id == costId); if (cost is {Status: CostStatus.Archived}) { cost.Status = CostStatus.Active; cost.UpdatedAt = DateTime.UtcNow; await unitOfWork.Costs.UpdateAsync(cost); } } public async Task DeleteAsync(Guid costId) { var cost = await unitOfWork.Costs.GetFirstWhereAsync(p => p.Id == costId); if (cost == null) { throw new CostDeleteException($"Расход с id {costId} не найден."); } if (cost.Status == CostStatus.Archived) { throw new CostDeleteException($"Нельзя удалить архивный расход."); } await unitOfWork.Costs.Delete(cost); } } <|start_filename|>Pds/Pds.Api.Contracts/Content/CreateContent/CreateContentRequest.cs<|end_filename|> using System.ComponentModel.DataAnnotations; using Pds.Core.Enums; namespace Pds.Api.Contracts.Content.CreateContent; public class CreateContentRequest { [Required] public Guid? BrandId { get; set; } [Required, EnumDataType(typeof(ContentType))] public ContentType Type { get; set; } [Required, EnumDataType(typeof(SocialMediaType))] public SocialMediaType SocialMediaType { get; set; } [Required] public string Title { get; set; } public string Comment { get; set; } [Required] public DateTime ReleaseDate { get; set; } public DateTime? EndDate { get; set; } public bool IsFree { get; set; } [ValidateComplexType] public CreateContentBillDto Bill { get; set; } public Guid? PersonId { get; set; } } <|start_filename|>Pds/Pds.Web.Models/Gift/GiftStatusFilterItem.cs<|end_filename|> using Pds.Core.Enums; namespace Pds.Web.Models.Gift; public class GiftStatusFilterItem { public GiftStatus GiftStatus { get; set; } public bool IsSelected { get; set; } } <|start_filename|>Pds/Pds.Web/Common/ContactBuilder.cs<|end_filename|> using Pds.Core.Enums; namespace Pds.Web.Common; public class ContactBuilder { public static string ToLink(ContactType type, string contact) { return type switch { ContactType.Other => contact, ContactType.Telegram => $"<a href=\"https://t.me/{contact}\" target=\"_blank\">{contact}</a>", ContactType.WhatsApp => contact, ContactType.Instagram => $"<a href=\"https://instagram.com/{contact}\" target=\"_blank\">{contact}</a>", ContactType.Email => contact, ContactType.Phone => contact, _ => string.Empty }; } } <|start_filename|>Pds/Pds.Api.Contracts/Client/GetClientsResponse.cs<|end_filename|> using Pds.Api.Contracts.Paging; namespace Pds.Api.Contracts.Client; public class GetClientsResponse : PageResult<ClientDto> { } <|start_filename|>Pds/Pds.Api.Contracts/Client/EditClientResponse.cs<|end_filename|> namespace Pds.Api.Contracts.Client; public class EditClientResponse { public Guid Id { get; set; } } <|start_filename|>Pds/Pds.Web/Pages/Content/Edit.razor.css<|end_filename|> .form-group { margin-bottom: 15px; } .card-header { margin-bottom: 15px; } ::deep input.bill-cost{ width: 100px; display: inline-block; margin-left: 10px; margin-right: 10px; } ::deep input.release-date{ width: 150px; display: inline-block; margin-left: 10px; margin-right: 10px; } .contact-type { margin-top: 5px; } .btn-free { margin-right: 10px; } <|start_filename|>Pds/Pds.Core/Exceptions/Client/ClientDeleteException.cs<|end_filename|> namespace Pds.Core.Exceptions.Client; public class ClientDeleteException : Exception, IApiException { public List<string> Errors { get; } public ClientDeleteException(List<string> errors) { Errors = errors; } public ClientDeleteException(string message) : base(message) { Errors = new List<string> { message }; } public ClientDeleteException(string message, Exception inner) : base(message, inner) { } } <|start_filename|>Pds/Pds.Web/Shared/AccessControl.razor.css<|end_filename|> .login-panel { padding: 0 15px; color: white; width: 100%; position: relative; overflow: auto; display: flex; font-size: 0.9rem; } .login-panel a { color: #fff; background-color: #1b6ec2; border-color: #1861ac; margin: auto 0 auto auto; } .login-panel span { display: inline-block; margin: auto; } <|start_filename|>Pds/Pds.Api.Contracts/Content/GetContents/GetContentsPersonDto.cs<|end_filename|> namespace Pds.Api.Contracts.Content.GetContents; public class GetContentsPersonDto { public string FirstName { get; set; } public string LastName { get; set; } public string ThirdName { get; set; } } <|start_filename|>Pds/Pds.Api/Controllers/ApiControllerBase.cs<|end_filename|> using System.Net; using Pds.Core.Exceptions; using Microsoft.AspNetCore.Mvc; namespace Pds.Api.Controllers; [ApiController] [Produces("application/json")] public abstract class ApiControllerBase : ControllerBase { protected IActionResult ExceptionResult(Exception exception) { return exception switch { _ when exception is RepositoryException => StatusCode((int) HttpStatusCode.BadRequest, "DB error"), _ when exception is IApiException apiException => StatusCode((int) HttpStatusCode.BadRequest, apiException.Errors), _ => StatusCode((int) HttpStatusCode.BadRequest, "Smtg went wrong") }; } } <|start_filename|>Pds/Pds.Data/Migrations/20210404181341_RenameBillCostToBillValue.cs<|end_filename|> using Microsoft.EntityFrameworkCore.Migrations; namespace Pds.Data.Migrations { public partial class RenameBillCostToBillValue : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.RenameColumn( name: "Cost", table: "Bills", newName: "Value"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.RenameColumn( name: "Value", table: "Bills", newName: "Cost"); } } } <|start_filename|>Pds/Pds.Data/Migrations/20210127205753_Initial.cs<|end_filename|> using System; using Microsoft.EntityFrameworkCore.Migrations; namespace Pds.Data.Migrations { public partial class Initial : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Persons", columns: table => new { ID = table.Column<Guid>(type: "uniqueidentifier", nullable: false), FirstName = table.Column<string>(type: "varchar(300)", nullable: false), LastName = table.Column<string>(type: "varchar(300)", nullable: false), ThirdName = table.Column<string>(type: "varchar(300)", nullable: false), Info = table.Column<string>(type: "nvarchar(max)", nullable: true), Rate = table.Column<int>(type: "int", nullable: false), Status = table.Column<int>(type: "int", nullable: false), CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false), UpdatedAt = table.Column<DateTime>(type: "datetime2", nullable: true), ArchivedAt = table.Column<DateTime>(type: "datetime2", nullable: true), UnarchivedAt = table.Column<DateTime>(type: "datetime2", nullable: true) }, constraints: table => { table.PrimaryKey("PK_Persons", x => x.ID); }); migrationBuilder.CreateTable( name: "Resources", columns: table => new { ID = table.Column<Guid>(type: "uniqueidentifier", nullable: false), Name = table.Column<string>(type: "nvarchar(max)", nullable: true), Url = table.Column<string>(type: "nvarchar(max)", nullable: true), CreatedAt = table.Column<DateTime>(type: "datetime2", nullable: false), UpdatedAt = table.Column<DateTime>(type: "datetime2", nullable: true), PersonID = table.Column<Guid>(type: "uniqueidentifier", nullable: true) }, constraints: table => { table.PrimaryKey("PK_Resources", x => x.ID); table.ForeignKey( name: "FK_Resources_Persons_PersonID", column: x => x.PersonID, principalTable: "Persons", principalColumn: "ID", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateIndex( name: "IX_Resources_PersonID", table: "Resources", column: "PersonID"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Resources"); migrationBuilder.DropTable( name: "Persons"); } } } <|start_filename|>Pds/Pds.Api.Contracts/Content/EditContent/EditContentResponse.cs<|end_filename|> namespace Pds.Api.Contracts.Content.EditContent; public class EditContentResponse { public Guid Id { get; set; } } <|start_filename|>Pds/Pds.Web/Pages/Gifts/List/Actions.razor.css<|end_filename|> .actions-panel { margin: 0 auto; white-space: pre; } button { margin: 0 5px; } <|start_filename|>Pds/Pds.Web.Models/Cost/CostTypeFilterItem.cs<|end_filename|> using Pds.Core.Enums; namespace Pds.Web.Models.Cost; public class CostTypeFilterItem { public CostType CostType { get; set; } public bool IsSelected { get; set; } } <|start_filename|>Pds/Pds.Core/Enums/ContentStatus.cs<|end_filename|> namespace Pds.Core.Enums; public enum ContentStatus { Active = 0, Archived = 1 }
SelitskiySergey/bloggers-cms
<|start_filename|>tests/lib/utils/ast.js<|end_filename|> /** * @file Tests for AST helper functions * @author <NAME> <<EMAIL>> */ "use strict"; const assert = require("assert"); const ast = require("../../../lib/utils/ast"); describe("ast.isIdentifier", function () { it("should return `false` if no argument is supplied", function () { const actual = ast.isIdentifier(); const expected = false; assert.equal(actual, expected); }); it("should return `false` if node does not contain a `type` attribute", function () { const actual = ast.isIdentifier({}); const expected = false; assert.equal(actual, expected); }); it("should return `false` if node contains a `type` other than `Identifier`", function () { const actual = ast.isIdentifier({ type: "Literal" }); const expected = false; assert.equal(actual, expected); }); it("should return `true` if supplied node is an Identifier", function () { const actual = ast.isIdentifier({ type: "Identifier" }); const expected = true; assert.equal(actual, expected); }); }); describe("ast.isLiteral", function () { it("should return `false` if no argument is supplied", function () { const actual = ast.isLiteral(); const expected = false; assert.equal(actual, expected); }); it("should return `false` if node does not contain a `type` attribute", function () { const actual = ast.isLiteral({}); const expected = false; assert.equal(actual, expected); }); it("should return `false` if node contains a `type` other than `Literal`", function () { const actual = ast.isLiteral({ type: "Identifier" }); const expected = false; assert.equal(actual, expected); }); it("should return `true` if supplied node is a `Literal`", function () { const actual = ast.isLiteral({ type: "Literal" }); const expected = true; assert.equal(actual, expected); }); }); describe("ast.isStringLiteral", function () { it("should return `false` if no argument is supplied", function () { const actual = ast.isStringLiteral(); const expected = false; assert.equal(actual, expected); }); it("should return `false` if node does not contain a `type` attribute", function () { const actual = ast.isStringLiteral({}); const expected = false; assert.equal(actual, expected); }); it("should return `false` if node does not contain a `value` attribute", function () { const actual = ast.isStringLiteral({ type: "Literal" }); const expected = false; assert.equal(actual, expected); }); it("should return `false` if node contains a `type` other than `Literal`", function () { const actual = ast.isStringLiteral({ type: "Identifier" }); const expected = false; assert.equal(actual, expected); }); it("should return `false` if node contains a `value` type other than `string`", function () { const actual = ast.isStringLiteral({ type: "Identifier", value: 5 }); const expected = false; assert.equal(actual, expected); }); it("should return `true` if supplied node is a `Literal` with a `string` value", function () { const actual = ast.isStringLiteral({ type: "Literal", value: "foobar" }); const expected = true; assert.equal(actual, expected); }); }); describe("ast.isArrayExpr", function () { it("should return `false` if no argument is supplied", function () { const actual = ast.isArrayExpr(); const expected = false; assert.equal(actual, expected); }); it("should return `false` if node does not contain a `type` attribute", function () { const actual = ast.isArrayExpr({}); const expected = false; assert.equal(actual, expected); }); it("should return `false` if node contains a `type` other than `ArrayExpression`", function () { const actual = ast.isArrayExpr({ type: "foobar" }); const expected = false; assert.equal(actual, expected); }); it("should return `true` if supplied node is an `ArrayExpression`", function () { const actual = ast.isArrayExpr({ type: "ArrayExpression" }); const expected = true; assert.equal(actual, expected); }); }); describe("ast.isObjectExpr", function () { it("should return `false` if no argument is supplied", function () { const actual = ast.isObjectExpr(); const expected = false; assert.equal(actual, expected); }); it("should return `false` if node does not contain a `type` attribute", function () { const actual = ast.isObjectExpr({}); const expected = false; assert.equal(actual, expected); }); it("should return `false` if node contains a `type` other than `ObjectExpression`", function () { const actual = ast.isObjectExpr({ type: "foobar" }); const expected = false; assert.equal(actual, expected); }); it("should return `true` if supplied node is an `ObjectExpression`", function () { const actual = ast.isObjectExpr({ type: "ObjectExpression" }); const expected = true; assert.equal(actual, expected); }); }); describe("ast.isFunctionExpr", function () { it("should return `false` if no argument is supplied", function () { const actual = ast.isFunctionExpr(); const expected = false; assert.equal(actual, expected); }); it("should return `false` if node does not contain a `type` attribute", function () { const actual = ast.isFunctionExpr({}); const expected = false; assert.equal(actual, expected); }); it("should return `false` if node contains a `type` other than `FunctionExpression` or `ArrowFunctionExpression`", function () { const actual = ast.isFunctionExpr({ type: "foobar" }); const expected = false; assert.equal(actual, expected); }); it("should return `true` if supplied node is a `FunctionExpression`", function () { const actual = ast.isFunctionExpr({ type: "FunctionExpression" }); const expected = true; assert.equal(actual, expected); }); it("should return `true` if supplied node is an `ArrowFunctionExpression`", function () { const actual = ast.isFunctionExpr({ type: "ArrowFunctionExpression" }); const expected = true; assert.equal(actual, expected); }); }); describe("ast.isMemberExpr", function () { it("should return `false` if no argument is supplied", function () { const actual = ast.isMemberExpr(); const expected = false; assert.equal(actual, expected); }); it("should return `false` if node does not contain a `type` attribute", function () { const actual = ast.isMemberExpr({}); const expected = false; assert.equal(actual, expected); }); it("should return `false` if node contains a `type` other than `MemberExpression`", function () { const actual = ast.isMemberExpr({ type: "foobar" }); const expected = false; assert.equal(actual, expected); }); it("should return `true` if supplied node is an `MemberExpression`", function () { const actual = ast.isMemberExpr({ type: "MemberExpression" }); const expected = true; assert.equal(actual, expected); }); }); describe("ast.isExprStatement", function () { it("should return `false` if no argument is supplied", function () { const actual = ast.isExprStatement(); const expected = false; assert.equal(actual, expected); }); it("should return `false` if node does not contain a `type` attribute", function () { const actual = ast.isExprStatement({}); const expected = false; assert.equal(actual, expected); }); it("should return `false` if node contains a `type` other than `ExpressionStatement`", function () { const actual = ast.isExprStatement({ type: "foobar" }); const expected = false; assert.equal(actual, expected); }); it("should return `true` if supplied node is an `ExpressionStatement`", function () { const actual = ast.isExprStatement({ type: "ExpressionStatement" }); const expected = true; assert.equal(actual, expected); }); }); describe("ast.isStringLiteralArray", function () { it("should return `false` if no argument is supplied", function () { const actual = ast.isStringLiteralArray(); const expected = false; assert.equal(actual, expected); }); it("should return `false` if node does not contain a `type` attribute", function () { const actual = ast.isStringLiteral({}); const expected = false; assert.equal(actual, expected); }); it("should return `false` if node `type` is not an `ArrayExpression`", function () { const actual = ast.isStringLiteralArray({ type: "FunctionExpression" }); const expected = false; assert.equal(actual, expected); }); it("should return `false` if node does not contain an `elements` attribute", function () { const actual = ast.isStringLiteralArray({ type: "ArrayExpression" }); const expected = false; assert.equal(actual, expected); }); it("should return `false` if node `elements` contains non-string values", function () { const actual = ast.isStringLiteralArray({ type: "ArrayExpression", elements: [ { type: "Literal", value: "a" }, { type: "Literal", value: null }, { type: "Literal", value: 5 } ] }); const expected = false; assert.equal(actual, expected); }); it("should return `true` if node `elements` contains only string values", function () { const actual = ast.isStringLiteralArray({ type: "ArrayExpression", elements: [ { type: "Literal", value: "a" }, { type: "Literal", value: "b" }, { type: "Literal", value: "c" } ] }); const expected = true; assert.equal(actual, expected); }); it("should return `true` if node `elements` is empty", function () { const actual = ast.isStringLiteralArray({ type: "ArrayExpression", elements: [] }); const expected = true; assert.equal(actual, expected); }); }); describe("ast.hasParams", function () { it("should return `false` if no argument is supplied", function () { const actual = ast.hasParams(); const expected = false; assert.equal(actual, expected); }); it("should return `false` if node does not contain a `params` attribute", function () { const actual = ast.hasParams({}); const expected = false; assert.equal(actual, expected); }); it("should return `false` if `params` is empty", function () { const actual = ast.hasParams({ params: [] }); const expected = false; assert.equal(actual, expected); }); it("should return `true` if supplied node has at least one param", function () { const actual = ast.hasParams({ params: [{ type: "Identifier", name: "boop" }] }); const expected = true; assert.equal(actual, expected); }); }); describe("ast.hasCallback", function () { it("should return `false` if no argument is supplied", function () { const actual = ast.hasCallback(); const expected = false; assert.equal(actual, expected); }); it("should return `false` if node does not contain a `arguments` attribute", function () { const actual = ast.hasCallback({}); const expected = false; assert.equal(actual, expected); }); it("should return `false` if `arguments` is empty", function () { const actual = ast.hasCallback({ arguments: [] }); const expected = false; assert.equal(actual, expected); }); it("should return `false` if `arguments` does not contain a FunctionExpression", function () { const actual = ast.hasCallback({ arguments: [{ type: "Identifier", name: "foobar" }] }); const expected = false; assert.equal(actual, expected); }); it("should return `true` if supplied node has at least one FunctionExpression argument", function () { const actual = ast.hasCallback({ arguments: [{ type: "FunctionExpression" }] }); const expected = true; assert.equal(actual, expected); }); }); describe("ast.ancestor", function () { const a = { type: "Program" }; const b = { type: "FunctionDeclaration", parent: a }; const c = { type: "BlockStatement", parent: b }; const d = { type: "ReturnStatement", parent: c }; it("should return `true` if an ancestor satisfies the predicate", function () { const actual = ast.ancestor((node) => node.type === "FunctionDeclaration", d); const expected = true; assert.equal(actual, expected); }); it("should return `false` if no ancestor satisfies the predicate", function () { const actual = ast.ancestor((node) => node.type === "VariableDeclaration", d); const expected = false; assert.equal(actual, expected); }); }); describe("ast.nearest", function () { const a = { type: "Program" }; const b = { type: "FunctionDeclaration", parent: a }; const c = { type: "BlockStatement", parent: b }; const d = { type: "ReturnStatement", parent: c }; it("should return found node if an ancestor satisfies the predicate", function () { const actual = ast.nearest((node) => node.type === "FunctionDeclaration", d); const expected = b; assert.equal(actual, expected); }); it("should return `undefined` if no ancestor satisfies the predicate", function () { const actual = ast.nearest((node) => node.type === "VariableDeclaration", d); const expected = undefined; assert.equal(actual, expected); }); }); <|start_filename|>lib/rules/no-restricted-amd-modules.js<|end_filename|> /** * @file Rule to disallow specified modules when loaded by `define` * @author <NAME> */ "use strict"; const ignore = require("ignore"); const rjs = require("../utils/rjs"); const isAmdDefine = rjs.isAmdDefine; const isAmdRequire = rjs.isAmdRequire; const getDependencyStringNodes = rjs.getDependencyStringNodes; // ----------------------------------------------------------------------------- // Configuration // ----------------------------------------------------------------------------- const docs = { description: "Disallow specified modules when loaded by `define`", category: "Stylistic Choices", recommended: false, url: "https://github.com/cvisco/eslint-plugin-requirejs/blob/master/docs/rules/no-restricted-amd-modules.md" }; const arrayOfStrings = { type: "array", items: { type: "string" }, uniqueItems: true }; const arrayOfStringsOrObjects = { type: "array", items: { anyOf: [ { type: "string" }, { type: "object", properties: { name: { type: "string" }, message: { type: "string", minLength: 1 } }, additionalProperties: false, required: ["name"] } ] }, uniqueItems: true }; const schema = { anyOf: [ arrayOfStringsOrObjects, { type: "array", items: { type: "object", properties: { paths: arrayOfStringsOrObjects, patterns: arrayOfStrings }, additionalProperties: false }, additionalItems: false } ] }; const DEFAULT_MESSAGE_TEMPLATE = "'{{moduleName}}' module is restricted from being used."; const CUSTOM_MESSAGE_TEMPLATE = "'{{moduleName}}' module is restricted from being used. {{customMessage}}"; // ----------------------------------------------------------------------------- // Rule Definition // ----------------------------------------------------------------------------- function create(context) { const options = Array.isArray(context.options) ? context.options : []; const isPathAndPatternsObject = typeof options[0] === "object" && (Object.prototype.hasOwnProperty.call(options[0], "paths") || Object.prototype.hasOwnProperty.call(options[0], "patterns")); const restrictedPaths = (isPathAndPatternsObject ? options[0].paths : options) || []; const restrictedPatterns = (isPathAndPatternsObject ? options[0].patterns : []) || []; const restrictedPathMessages = restrictedPaths.reduce( (memo, importName) => { if (typeof importName === "string") { memo[importName] = null; } else { memo[importName.name] = importName.message; } return memo; }, {} ); // if no modules are restricted we don"t need to check if ( Object.keys(restrictedPaths).length === 0 && restrictedPatterns.length === 0 ) { return {}; } const ig = ignore().add(restrictedPatterns); /** * Report a restricted path. * @param {node} node representing the restricted path reference * @returns {void} * @private */ function reportPath(node) { const moduleName = node.value.trim(); const customMessage = restrictedPathMessages[moduleName]; const message = customMessage ? CUSTOM_MESSAGE_TEMPLATE : DEFAULT_MESSAGE_TEMPLATE; context.report({ node, message, data: { moduleName, customMessage } }); } /** * Check if the given name is a restricted path name * @param {string} name name of a variable * @returns {boolean} whether the variable is a restricted path or not * @private */ function isRestrictedPath(name) { return Object.prototype.hasOwnProperty.call( restrictedPathMessages, name ); } return { CallExpression(node) { if (!isAmdDefine(node) && !isAmdRequire(node)) return; const paths = getDependencyStringNodes(node); for (let i = 0; i < paths.length; i++) { const nodeCurrent = paths[i]; const moduleName = nodeCurrent.value.trim(); // check if argument value is in restricted modules array if (isRestrictedPath(moduleName)) { reportPath(nodeCurrent); } if (restrictedPatterns.length > 0 && ig.ignores(moduleName)) { context.report({ node, message: "'{{moduleName}}' module is restricted from being used by a pattern.", data: { moduleName } }); break; } } } }; } module.exports = { meta: { docs, schema }, create }; <|start_filename|>lib/rules/no-dynamic-require.js<|end_filename|> /** * @file Rule to disallow dynamically generated paths in `require` call * @author <NAME> <<EMAIL>> */ "use strict"; const rjs = require("../utils/rjs"); const ast = require("../utils/ast"); const isRequireCall = rjs.isRequireCall; const isStringLiteral = ast.isStringLiteral; const isStringLiteralArray = ast.isStringLiteralArray; // ----------------------------------------------------------------------------- // Configuration // ----------------------------------------------------------------------------- const docs = { description: "Disallow use of dynamically generated paths in a require call", category: "Stylistic Choices", recommended: false, url: "https://github.com/cvisco/eslint-plugin-requirejs/blob/master/docs/rules/no-dynamic-require.md" }; const schema = []; const message = "Dynamic `require` calls are not allowed."; // ----------------------------------------------------------------------------- // Helpers // ----------------------------------------------------------------------------- const hasStaticDependencies = (node) => isStringLiteral(node.arguments[0]) || isStringLiteralArray(node.arguments[0]); // ----------------------------------------------------------------------------- // Rule Definition // ----------------------------------------------------------------------------- function create(context) { return { CallExpression(node) { if (isRequireCall(node) && !hasStaticDependencies(node)) { context.report(node, message); } } }; } module.exports = { meta: { docs, schema }, create }; <|start_filename|>tests/lib/rules/no-require-tourl.js<|end_filename|> /** * @file Tests for `no-require-tourl` rule * @author <NAME> <<EMAIL>> */ "use strict"; const testRule = require("../../rule-tester"); const util = require("util"); const fixtures = require("../../fixtures"); const rule = require("../../../lib/rules/no-require-tourl"); // ----------------------------------------------------------------------------- // Fixtures // ----------------------------------------------------------------------------- const REQUIREJS_NAME_TO_URL = ` define(['require'], function (require) { var idUrl = requirejs.nameToUrl('id'); }); `; const REQUIREJS_TO_URL = ` define(['require'], function (require) { var cssUrl = requirejs.toUrl('./style.css'); }); `; const REQUIRE_NAME_TO_URL = ` define(['require'], function (require) { var idUrl = require.nameToUrl('id'); }); `; const REQUIRE_TO_URL = ` define(['require'], function (require) { var cssUrl = require.toUrl('./style.css'); }); `; // ----------------------------------------------------------------------------- // Tests // ----------------------------------------------------------------------------- const MESSAGE = "Use of `require.%s` is not allowed."; testRule("no-require-tourl", rule, { valid: [ fixtures.AMD_REQUIRE_RELATIVE, fixtures.CJS_WITH_RETURN, fixtures.CJS_WITH_EXPORTS, fixtures.CJS_WITH_MODULE_EXPORTS, fixtures.NAMED_CJS_DEFINE ], invalid: [ { code: REQUIRE_TO_URL, errors: [{ message: util.format(MESSAGE, "toUrl"), type: "CallExpression" }] }, { code: REQUIREJS_TO_URL, errors: [{ message: util.format(MESSAGE, "toUrl"), type: "CallExpression" }] }, { code: REQUIRE_NAME_TO_URL, errors: [{ message: util.format(MESSAGE, "nameToUrl"), type: "CallExpression" }] }, { code: REQUIREJS_NAME_TO_URL, errors: [{ message: util.format(MESSAGE, "nameToUrl"), type: "CallExpression" }] } ] }); <|start_filename|>tests/lib/rules/no-invalid-define.js<|end_filename|> /** * @file Tests for `no-invalid-define` rule * @author <NAME> <<EMAIL>> */ "use strict"; const testRule = require("../../rule-tester"); const fixtures = require("../../fixtures"); const rule = require("../../../lib/rules/no-invalid-define"); // ----------------------------------------------------------------------------- // Tests // ----------------------------------------------------------------------------- const ERROR = { message: "Invalid module definition", type: "CallExpression" }; testRule("no-invalid-define", rule, { valid: [ fixtures.OBJECT_DEFINE, fixtures.FUNCTION_DEFINE, fixtures.CJS_WITH_RETURN, fixtures.CJS_WITH_EXPORTS, fixtures.CJS_WITH_MODULE_EXPORTS, fixtures.AMD_DEFINE, fixtures.AMD_EMPTY_DEFINE, fixtures.NAMED_OBJECT_DEFINE, fixtures.NAMED_FUNCTION_DEFINE, fixtures.NAMED_AMD_DEFINE, fixtures.NAMED_AMD_EMPTY_DEFINE, fixtures.NAMED_CJS_DEFINE ], invalid: [ { code: fixtures.EMPTY_DEFINE, errors: [ERROR] }, { code: fixtures.BAD_DEFINE, errors: [ERROR] } ] }); <|start_filename|>tests/lib/rules/no-multiple-define.js<|end_filename|> /** * @file Tests for `no-multiple-define` rule * @author <NAME> <<EMAIL>> */ "use strict"; const testRule = require("../../rule-tester"); const fixtures = require("../../fixtures"); const rule = require("../../../lib/rules/no-multiple-define"); // ----------------------------------------------------------------------------- // Fixtures // ----------------------------------------------------------------------------- const MULTIPLE_DEFINE_ONE_CALL = ` if (typeof define === "function") { define(function () { return { foo: 'bar' }; }); } `; // ----------------------------------------------------------------------------- // Tests // ----------------------------------------------------------------------------- testRule("no-multiple-define", rule, { valid: [ fixtures.OBJECT_DEFINE, fixtures.FUNCTION_DEFINE, fixtures.CJS_WITH_RETURN, fixtures.CJS_WITH_EXPORTS, fixtures.CJS_WITH_MODULE_EXPORTS, fixtures.AMD_DEFINE, fixtures.AMD_EMPTY_DEFINE, fixtures.NAMED_AMD_DEFINE, fixtures.NAMED_AMD_EMPTY_DEFINE, MULTIPLE_DEFINE_ONE_CALL ], invalid: [ { code: fixtures.MULTIPLE_DEFINE, errors: [{ message: "Multiple `define` calls in a single file are not permitted", type: "CallExpression", line: 4, column: 1 }] } ] }); <|start_filename|>lib/rules/one-dependency-per-line.js<|end_filename|> /** * @file Rule to enforce or disallow one dependency per line. * @author <NAME> <<EMAIL>> */ "use strict"; const rjs = require("../utils/rjs"); const ast = require("../utils/ast"); const isAmdCall = rjs.isAmdCall; const withoutModuleId = rjs.withoutModuleId; const isArrayExpr = ast.isArrayExpr; const isFunctionExpr = ast.isFunctionExpr; // ----------------------------------------------------------------------------- // Configuration // ----------------------------------------------------------------------------- const docs = { description: "Require or disallow one dependency per line", category: "Stylistic Choices", recommended: false, url: "https://github.com/cvisco/eslint-plugin-requirejs/blob/master/docs/rules/one-dependency-per-line.md" }; const schema = [ { type: "object", properties: { paths: { oneOf: [ { enum: ["always", "never"] }, { type: "number", minimum: 0 } ] }, names: { oneOf: [ { enum: ["always", "never"] }, { type: "number", minimum: 0 } ] } }, additionalProperties: false } ]; const defaults = { paths: "always", names: "always" }; const messages = { always: { paths: "Only one dependency path is permitted per line.", names: "Only one dependency name is permitted per line." }, never: { paths: "Dependency paths must appear on one line.", names: "Dependency names must appear on one line." } }; // ----------------------------------------------------------------------------- // Helpers // ----------------------------------------------------------------------------- const pad = (amount) => (val) => " ".repeat(amount) + val; const line = (node) => node.loc.start.line; const column = (node) => node.loc.start.column; const unique = (list) => Array.from(new Set(list)); const hasDuplicates = (list) => unique(list).length < list.length; const hasMultiple = (list) => unique(list).length > 1; const isLongerThan = (val, list) => Number.isInteger(val) && list.length > val; const isAlways = (val) => val === "always"; const isNever = (val) => val === "never"; const indentation = (node) => { const statement = node.type === "ArrowFunctionExpression" ? node.body : node.body.body[0]; return statement && line(node) !== line(statement) ? column(statement) : 0; }; const formatPaths = (indent) => (node) => { const paths = node.elements.map(v => v.raw).map(pad(indent)).join(",\n"); return `[\n${paths}\n]`; }; const formatNames = (indent, context) => (node) => { const names = node.params.map(v => v.name).map(pad(indent)).join(",\n"); const body = context.getSourceCode().getText(node.body); return `function (\n${names}\n) ${body}`; }; // ----------------------------------------------------------------------------- // Rule Definition // ----------------------------------------------------------------------------- function create(context) { const settings = Object.assign({}, defaults, context.options[0]); function check(setting, node, list, format) { const val = settings[setting]; const lines = list.map(line); if ((isLongerThan(val, lines) || isAlways(val)) && hasDuplicates(lines)) { const message = messages.always[setting]; const fix = (f) => f.replaceTextRange(node.range, format(node)); context.report({ node, message, fix }); } if (isNever(val) && hasMultiple(lines)) { const message = messages.never[setting]; context.report({ node, message }); } } return { CallExpression(node) { if (!isAmdCall(node) || node.arguments.length < 2) return; const args = withoutModuleId(node.arguments); const deps = args[0]; const func = args[1]; if (!isArrayExpr(deps) || !isFunctionExpr(func)) return; const indent = indentation(func); check("paths", deps, deps.elements, formatPaths(indent)); check("names", func, func.params, formatNames(indent, context)); } }; } module.exports = { meta: { docs, schema, fixable: "code" }, create }; <|start_filename|>tests/lib/rules/no-commonjs-exports.js<|end_filename|> /** * @file Tests for `no-commonjs-exports` rule * @author <NAME> <<EMAIL>> */ "use strict"; const testRule = require("../../rule-tester"); const fixtures = require("../../fixtures"); const rule = require("../../../lib/rules/no-commonjs-exports"); // ----------------------------------------------------------------------------- // Tests // ----------------------------------------------------------------------------- const ERROR = { message: "Unexpected use of `exports` in module definition.", type: "AssignmentExpression" }; testRule("no-commonjs-exports", rule, { valid: [ fixtures.OBJECT_DEFINE, fixtures.FUNCTION_DEFINE, fixtures.AMD_DEFINE, fixtures.AMD_EMPTY_DEFINE, fixtures.NAMED_OBJECT_DEFINE, fixtures.NAMED_FUNCTION_DEFINE, fixtures.NAMED_AMD_DEFINE, fixtures.NAMED_AMD_EMPTY_DEFINE, fixtures.NAMED_CJS_DEFINE, fixtures.CJS_WITH_RETURN, fixtures.CJS_WITH_MODULE_EXPORTS, fixtures.CJS_WITH_FUNC_EXPR, fixtures.NON_WRAPPED_EXPORTS ], invalid: [ { code: fixtures.CJS_WITH_EXPORTS, errors: [ERROR] } ] }); <|start_filename|>lib/utils/rjs.js<|end_filename|> /** * @file Helper functions for working with RequireJS-related nodes * @author <NAME> <<EMAIL>> */ "use strict"; const ast = require("./ast"); const hasParams = ast.hasParams; const isLiteral = ast.isLiteral; const isStringLiteral = ast.isStringLiteral; const isArrayExpr = ast.isArrayExpr; const isObjectExpr = ast.isObjectExpr; const isFunctionExpr = ast.isFunctionExpr; const CJS_PARAMS = ["require", "exports", "module"]; /** * Determine if supplied `node` has a parameter list that satisfies the * requirements for a Simplified CommonJS Wrapper. * @private * @param {Array} params list of function parameters to test * @returns {Boolean} true if `params` satisfies a CommonJS Wrapper format */ const hasCommonJsParams = (params) => params.length && params.every((param, i) => param.name === CJS_PARAMS[i]); /** * Determine if supplied `node` represents a function expression compatible with * the Simplfied CommonJS Wrapper. * @private * @param {ASTNode} node - node to test * @returns {Boolean} true if represents a CommonJS function expression */ const isCommonJsFuncExpr = (node) => isFunctionExpr(node) && hasCommonJsParams(node.params); /** * Determine if supplied `node` represents a "simple" function expression. That * is, one without any parameter list. * @private * @param {ASTNode} node - node to test * @returns {Boolean} true if represents a simple function expression */ const isSimpleFuncExpr = (node) => isFunctionExpr(node) && !hasParams(node); /** * Determine if supplied `node` represents a call to `define`. * @param {ASTNode} node - CallExpression node to test * @returns {Boolean} true if represents a call to `define` */ const isDefineCall = (node) => node && node.type === "CallExpression" && node.callee.type === "Identifier" && node.callee.name === "define"; /** * Determine if supplied `node` represents a module definition function with * a dependency array. This is the classic AMD style module definition. * @see http://requirejs.org/docs/api.html#defdep * @param {ASTNode} node - node to test * @returns {Boolean} true if represents an AMD style module definition */ const isAmdDefine = (node) => isDefineCall(node) && isAmdArgs(withoutModuleId(node.arguments)); /** * Determine if supplied `node` represents a require function with * a dependency array. * @param {ASTNode} node - CallExpression node to test * @returns {Boolean} true if represents an AMD style require function */ const isAmdRequire = (node) => isRequireCall(node) && isAmdArgs(node.arguments); const isAmdArgs = (args) => args.length === 2 && isArrayExpr(args[0]) && isFunctionExpr(args[1]); const withoutModuleId = (args) => isStringLiteral(args[0]) ? args.slice(1) : args; /** * Determine if supplied `node` represents a plain object module. This is * referred to as the "Simple Name/Value Pairs" form of module in the * RequireJS documentation. * @see http://requirejs.org/docs/api.html#defsimple * @param {ASTNode} node - CallExpression node to test * @returns {Boolean} true if represents an Object Module Definition */ const isObjectDefine = (node) => isDefineCall(node) && isObjectArgs(withoutModuleId(node.arguments)); const isObjectArgs = (args) => args.length === 1 && isObjectExpr(args[0]); /** * Determine if supplied `node` represents a module definition function with * no dependency array. * @see http://requirejs.org/docs/api.html#deffunc * @param {ASTNode} node - CallExpression node to test * @returns {Boolean} true if represents a Simple Function Definition */ const isFunctionDefine = (node) => isDefineCall(node) && isFunctionArgs(withoutModuleId(node.arguments)); const isFunctionArgs = (args) => args.length === 1 && isSimpleFuncExpr(args[0]); /** * Determine if supplied `node` represents a module definition using the * "Simplified CommonJS Wrapper" form. * @see http://requirejs.org/docs/api.html#cjsmodule * @param {ASTNode} node - CallExpression node to test * @returns {Boolean} true if represents a Simplified CommonJS Wrapper */ const isCommonJsWrapper = (node) => isDefineCall(node) && isCommonJsArgs(withoutModuleId(node.arguments)); const isCommonJsArgs = (args) => args.length === 1 && isCommonJsFuncExpr(args[0]); /** * Determine if supplied `node` represents a named (or aliased) module * definition function. * @see http://requirejs.org/docs/api.html#modulename * @param {ASTNode} node - CallExpression node to test * @returns {Boolean} true if represents a named module definition function */ const isNamedDefine = (node) => isDefineCall(node) && isNamedArgs(node.arguments); const isNamedArgs = (args) => (args.length === 2 || args.length === 3) && isStringLiteral(args[0]); /** * Determine if supplied `node` represents a valid `define` format. * @param {ASTNode} node - CallExpression node to test * @returns {Boolean} true if represents a valid module definition function */ const isValidDefine = (node) => { const args = withoutModuleId(node.arguments); if (args.length === 1) return isObjectExpr(args[0]) || isFunctionExpr(args[0]); if (args.length === 2) return isArrayExpr(args[0]) && isFunctionExpr(args[1]); return false; }; /** * Determine if supplied `node` represents a `require` or `requirejs` * identifier. Both are synonymous commands. * @param {ASTNode} node - Identifier node to test * @returns {Boolean} true if represents a require identifier. */ const isRequireIdentifier = (node) => node.name === "require" || node.name === "requirejs"; /** * Determine if supplied `node` represents a call to `require`. * @param {ASTNode} node - CallExpression node to test * @returns {Boolean} true if represents a call to `require` */ const isRequireCall = (node) => node.type === "CallExpression" && node.callee.type === "Identifier" && isRequireIdentifier(node.callee); /** * Determine if supplied `node` represents a valid `require` format. * @param {ASTNode} node - CallExpression node to test * @returns {Boolean} true if represents a valid `require` call */ const isValidRequire = (node) => { const args = node.arguments; // If the wrong number of arguments is present, we know it's invalid, // so just return immediately if (args.length < 1 || args.length > 3) return false; // Single argument form should be a string literal, an array expression, // or something that evalutes to one of those. Realistically, we can only // test for a few obviously incorrect cases if (args.length === 1) { return !isObjectExpr(args[0]) && !isFunctionExpr(args[0]); } // For 2 or 3-argument forms, the tail arguments should be function // expressions, or something that could evaluate to a function expression. // Realistically, we can only test for a few obviously incorrect cases. if (args.length > 1 && isInvalidRequireArg(args[1])) return false; if (args.length > 2 && isInvalidRequireArg(args[2])) return false; // For 2 or 3-argument forms, the first argument should be an array // expression or something that evaluates to one. Again, realistically, we // can only test for a few obviously incorrect cases return !isLiteral(args[0]) && !isObjectExpr(args[0]) && !isFunctionExpr(args[0]); }; const isInvalidRequireArg = (arg) => isObjectExpr(arg) || isArrayExpr(arg) || isLiteral(arg); /** * Retrieve the dependency list from the provided `node`, without any filtering * by dependency node type. * @param {ASTNode} node - CallExpression to inspect * @returns {Array} list of dependency path nodes */ const getDependencyNodes = (node) => { const args = node.arguments; if (isDefineCall(node) && args.length > 1) { if (isArrayExpr(args[0])) return args[0].elements; if (isArrayExpr(args[1])) return args[1].elements; } else if (isRequireCall(node)) { if (isArrayExpr(args[0])) return args[0].elements; if (isStringLiteral(args[0])) return [ args[0] ]; } return []; }; /** * Retrieve the dependency list from the provided `node`, filtering by node * type to return only string literal dependencies. * @param {ASTNode} node - CallExpression to inspect * @returns {Array} list of dependency path literals */ const getDependencyStringNodes = (node) => getDependencyNodes(node).filter(isStringLiteral); /** * Retrieve the module definition function from the provided `node`. It will * always be the first FunctionExpression in the arguments list. * @param {ASTNode} node - node to check * @returns {ASTNode} module definition function */ const getModuleFunction = (node) => node.arguments.find(isFunctionExpr); const isAmdCall = (node) => isDefineCall(node) || isRequireCall(node); module.exports = { isRequireCall, isDefineCall, isAmdDefine, isAmdRequire, isObjectDefine, isFunctionDefine, isCommonJsWrapper, isNamedDefine, isValidDefine, isRequireIdentifier, isValidRequire, getDependencyNodes, getDependencyStringNodes, getModuleFunction, withoutModuleId, isAmdCall }; <|start_filename|>tests/rule-tester.js<|end_filename|> "use strict"; const RuleTester = require("eslint").RuleTester; module.exports = function (ruleName, rule, test) { const ruleTester = new RuleTester(); ruleTester.run(ruleName, rule, test); }; <|start_filename|>tests/lib/rules/one-dependency-per-line.js<|end_filename|> /** * @file Tests for `one-dependency-per-line` rule * @author <NAME> <<EMAIL>> */ "use strict"; const testRule = require("../../rule-tester"); const fixtures = require("../../fixtures"); const rule = require("../../../lib/rules/one-dependency-per-line"); // ----------------------------------------------------------------------------- // Tests // ----------------------------------------------------------------------------- const ALWAYS_PATHS_ERROR = { message: "Only one dependency path is permitted per line.", type: "ArrayExpression" }; const ALWAYS_NAMES_ERROR = { message: "Only one dependency name is permitted per line.", type: "FunctionExpression" }; const NEVER_PATHS_ERROR = { message: "Dependency paths must appear on one line.", type: "ArrayExpression" }; const NEVER_NAMES_ERROR = { message: "Dependency names must appear on one line.", type: "FunctionExpression" }; testRule("one-dependency-per-line", rule, { valid: [ // Should ignore irrelevant or malformed definitions fixtures.FUNCTION_DEFINE, fixtures.EMPTY_DEFINE, fixtures.OBJECT_DEFINE, fixtures.CJS_WITH_RETURN, fixtures.BAD_DEFINE, fixtures.BAD_REQUIRE_EMPTY, fixtures.BAD_REQUIRE_INVALID_CALLBACK, fixtures.BAD_REQUIRE_NO_DEPS, fixtures.BAD_REQUIRE_OBJECT, fixtures.BAD_REQUIRE_STRING_DEP, fixtures.BAD_REQUIREJS_STRING_DEP, { code: fixtures.DEFINE_WITH_ARROW_FUNCTION, parserOptions: { ecmaVersion: 6 } }, // zero deps should never trigger warning, regardless of options { code: fixtures.AMD_DEPS_NONE, options: [{}] }, { code: fixtures.AMD_DEPS_NONE, options: [{ "paths": "never" }] }, { code: fixtures.AMD_DEPS_NONE, options: [{ "names": "never" }] }, // Default options: "always" for both { code: fixtures.AMD_DEPS_MULTI_LINE_ONE, options: [{}] }, { code: fixtures.AMD_DEPS_MULTI_LINE_TWO, options: [{}] }, { code: fixtures.AMD_DEPS_MULTI_LINE_THREE, options: [{}] }, { code: fixtures.AMD_DEPS_MULTI_LINE_FOUR, options: [{}] }, // "never" for both { code: fixtures.AMD_DEPS_SINGLE_LINE_ONE, options: [{ "paths": "never", "names": "never" }] }, { code: fixtures.AMD_DEPS_SINGLE_LINE_TWO, options: [{ "paths": "never", "names": "never" }] }, { code: fixtures.AMD_DEPS_SINGLE_LINE_THREE, options: [{ "paths": "never", "names": "never" }] }, { code: fixtures.AMD_DEPS_SINGLE_LINE_FOUR, options: [{ "paths": "never", "names": "never" }] }, // "never" for names { code: fixtures.AMD_DEPS_MULTI_LINE_PATHS_ONE, options: [{ "names": "never" }] }, { code: fixtures.AMD_DEPS_MULTI_LINE_PATHS_TWO, options: [{ "names": "never" }] }, { code: fixtures.AMD_DEPS_MULTI_LINE_PATHS_THREE, options: [{ "names": "never" }] }, { code: fixtures.AMD_DEPS_MULTI_LINE_PATHS_FOUR, options: [{ "names": "never" }] }, // "never" for paths { code: fixtures.AMD_DEPS_MULTI_LINE_NAMES_ONE, options: [{ "paths": "never" }] }, { code: fixtures.AMD_DEPS_MULTI_LINE_NAMES_TWO, options: [{ "paths": "never" }] }, { code: fixtures.AMD_DEPS_MULTI_LINE_NAMES_THREE, options: [{ "paths": "never" }] }, { code: fixtures.AMD_DEPS_MULTI_LINE_NAMES_FOUR, options: [{ "paths": "never" }] }, // Minimum values should not warn on fewer dependencies { code: fixtures.AMD_DEPS_SINGLE_LINE_ONE, options: [{ "paths": 2, "names": 2 }] }, { code: fixtures.AMD_DEPS_SINGLE_LINE_TWO, options: [{ "paths": 2, "names": 2 }] }, { code: fixtures.AMD_DEPS_SINGLE_LINE_ONE, options: [{ "paths": 2, "names": 2 }] }, { code: fixtures.AMD_DEPS_SINGLE_LINE_TWO, options: [{ "paths": 2, "names": 2 }] }, { code: fixtures.AMD_DEPS_MULTI_LINE_PATHS_ONE, options: [{ "paths": "always", "names": 2 }] }, { code: fixtures.AMD_DEPS_MULTI_LINE_PATHS_TWO, options: [{ "paths": "always", "names": 2 }] }, { code: fixtures.AMD_DEPS_MULTI_LINE_NAMES_ONE, options: [{ "paths": 2, "names": "always" }] }, { code: fixtures.AMD_DEPS_MULTI_LINE_NAMES_TWO, options: [{ "paths": 2, "names": "always" }] } ], invalid: [ // Default options: "always" for both { code: fixtures.AMD_DEPS_SINGLE_LINE_TWO, options: [{}], errors: [ ALWAYS_PATHS_ERROR, ALWAYS_NAMES_ERROR ], output: fixtures.AMD_DEPS_MULTI_LINE_TWO }, { code: fixtures.AMD_DEPS_SINGLE_LINE_THREE, options: [{}], errors: [ ALWAYS_PATHS_ERROR, ALWAYS_NAMES_ERROR ], output: fixtures.AMD_DEPS_MULTI_LINE_THREE }, { code: fixtures.AMD_DEPS_SINGLE_LINE_FOUR, options: [{}], errors: [ ALWAYS_PATHS_ERROR, ALWAYS_NAMES_ERROR ], output: fixtures.AMD_DEPS_MULTI_LINE_FOUR }, { code: fixtures.AMD_DEPS_MULTI_LINE_NAMES_TWO, options: [{}], errors: [ ALWAYS_PATHS_ERROR ], output: fixtures.AMD_DEPS_MULTI_LINE_TWO }, { code: fixtures.AMD_DEPS_MULTI_LINE_NAMES_THREE, options: [{}], errors: [ ALWAYS_PATHS_ERROR ], output: fixtures.AMD_DEPS_MULTI_LINE_THREE }, { code: fixtures.AMD_DEPS_MULTI_LINE_NAMES_FOUR, options: [{}], errors: [ ALWAYS_PATHS_ERROR ], output: fixtures.AMD_DEPS_MULTI_LINE_FOUR }, { code: fixtures.AMD_DEPS_MULTI_LINE_PATHS_TWO, options: [{}], errors: [ ALWAYS_NAMES_ERROR ], output: fixtures.AMD_DEPS_MULTI_LINE_TWO }, { code: fixtures.AMD_DEPS_MULTI_LINE_PATHS_THREE, options: [{}], errors: [ ALWAYS_NAMES_ERROR ], output: fixtures.AMD_DEPS_MULTI_LINE_THREE }, { code: fixtures.AMD_DEPS_MULTI_LINE_PATHS_FOUR, options: [{}], errors: [ ALWAYS_NAMES_ERROR ], output: fixtures.AMD_DEPS_MULTI_LINE_FOUR }, { code: fixtures.AMD_DEPS_SINGLE_LINE_NO_INDENT_TWO, options: [{}], errors: [ ALWAYS_PATHS_ERROR, ALWAYS_NAMES_ERROR ], output: fixtures.AMD_DEPS_MULTI_LINE_NO_INDENT_TWO }, { code: fixtures.AMD_DEPS_SINGLE_LINE_NO_INDENT_THREE, options: [{}], errors: [ ALWAYS_PATHS_ERROR, ALWAYS_NAMES_ERROR ], output: fixtures.AMD_DEPS_MULTI_LINE_NO_INDENT_THREE }, { code: fixtures.AMD_DEPS_SINGLE_LINE_NO_INDENT_FOUR, options: [{}], errors: [ ALWAYS_PATHS_ERROR, ALWAYS_NAMES_ERROR ], output: fixtures.AMD_DEPS_MULTI_LINE_NO_INDENT_FOUR }, // "always" for paths only { code: fixtures.AMD_DEPS_SINGLE_LINE_TWO, options: [{"names": "never"}], errors: [ ALWAYS_PATHS_ERROR ], output: fixtures.AMD_DEPS_MULTI_LINE_PATHS_TWO }, { code: fixtures.AMD_DEPS_SINGLE_LINE_THREE, options: [{"names": "never"}], errors: [ ALWAYS_PATHS_ERROR ], output: fixtures.AMD_DEPS_MULTI_LINE_PATHS_THREE }, { code: fixtures.AMD_DEPS_SINGLE_LINE_FOUR, options: [{"names": "never"}], errors: [ ALWAYS_PATHS_ERROR ], output: fixtures.AMD_DEPS_MULTI_LINE_PATHS_FOUR }, // "always" for names only { code: fixtures.AMD_DEPS_SINGLE_LINE_TWO, options: [{"paths": "never"}], errors: [ ALWAYS_NAMES_ERROR ], output: fixtures.AMD_DEPS_MULTI_LINE_NAMES_TWO }, { code: fixtures.AMD_DEPS_SINGLE_LINE_THREE, options: [{"paths": "never"}], errors: [ ALWAYS_NAMES_ERROR ], output: fixtures.AMD_DEPS_MULTI_LINE_NAMES_THREE }, { code: fixtures.AMD_DEPS_SINGLE_LINE_FOUR, options: [{"paths": "never"}], errors: [ ALWAYS_NAMES_ERROR ], output: fixtures.AMD_DEPS_MULTI_LINE_NAMES_FOUR }, // "never" for both { code: fixtures.AMD_DEPS_MULTI_LINE_TWO, options: [{ "paths": "never", "names": "never" }], errors: [ NEVER_PATHS_ERROR, NEVER_NAMES_ERROR ] }, { code: fixtures.AMD_DEPS_MULTI_LINE_THREE, options: [{ "paths": "never", "names": "never" }], errors: [ NEVER_PATHS_ERROR, NEVER_NAMES_ERROR ] }, { code: fixtures.AMD_DEPS_MULTI_LINE_FOUR, options: [{ "paths": "never", "names": "never" }], errors: [ NEVER_PATHS_ERROR, NEVER_NAMES_ERROR ] }, { code: fixtures.AMD_DEPS_MULTI_LINE_PATHS_TWO, options: [{ "paths": "never", "names": "never" }], errors: [ NEVER_PATHS_ERROR ] }, { code: fixtures.AMD_DEPS_MULTI_LINE_PATHS_THREE, options: [{ "paths": "never", "names": "never" }], errors: [ NEVER_PATHS_ERROR ] }, { code: fixtures.AMD_DEPS_MULTI_LINE_PATHS_FOUR, options: [{ "paths": "never", "names": "never" }], errors: [ NEVER_PATHS_ERROR ] }, { code: fixtures.AMD_DEPS_MULTI_LINE_NAMES_TWO, options: [{ "paths": "never", "names": "never" }], errors: [ NEVER_NAMES_ERROR ] }, { code: fixtures.AMD_DEPS_MULTI_LINE_NAMES_THREE, options: [{ "paths": "never", "names": "never" }], errors: [ NEVER_NAMES_ERROR ] }, { code: fixtures.AMD_DEPS_MULTI_LINE_NAMES_FOUR, options: [{ "paths": "never", "names": "never" }], errors: [ NEVER_NAMES_ERROR ] }, // Minimum values should warn when threshold exceeded { code: fixtures.AMD_DEPS_SINGLE_LINE_THREE, options: [{ "paths": 2, "names": 2 }], errors: [ ALWAYS_PATHS_ERROR, ALWAYS_NAMES_ERROR ] }, { code: fixtures.AMD_DEPS_SINGLE_LINE_FOUR, options: [{ "paths": 2, "names": 2 }], errors: [ ALWAYS_PATHS_ERROR, ALWAYS_NAMES_ERROR ] }, { code: fixtures.AMD_DEPS_SINGLE_LINE_THREE, options: [{ "paths": 2, "names": 2 }], errors: [ ALWAYS_PATHS_ERROR, ALWAYS_NAMES_ERROR ] }, { code: fixtures.AMD_DEPS_SINGLE_LINE_FOUR, options: [{ "paths": 2, "names": 2 }], errors: [ ALWAYS_PATHS_ERROR, ALWAYS_NAMES_ERROR ] }, { code: fixtures.AMD_DEPS_MULTI_LINE_PATHS_THREE, options: [{ "paths": "always", "names": 2 }], errors: [ ALWAYS_NAMES_ERROR ] }, { code: fixtures.AMD_DEPS_MULTI_LINE_PATHS_FOUR, options: [{ "paths": "always", "names": 2 }], errors: [ ALWAYS_NAMES_ERROR ] }, { code: fixtures.AMD_DEPS_MULTI_LINE_NAMES_THREE, options: [{ "paths": 2, "names": "always" }], errors: [ ALWAYS_PATHS_ERROR ] }, { code: fixtures.AMD_DEPS_MULTI_LINE_NAMES_FOUR, options: [{ "paths": 2, "names": "always" }], errors: [ ALWAYS_PATHS_ERROR ] } ] }); <|start_filename|>tests/lib/rules/no-assign-exports.js<|end_filename|> /** * @file Tests for `no-assign-exports` rule * @author <NAME> <<EMAIL>> */ "use strict"; const testRule = require("../../rule-tester"); const fixtures = require("../../fixtures"); const rule = require("../../../lib/rules/no-assign-exports"); // ----------------------------------------------------------------------------- // Tests // ----------------------------------------------------------------------------- const ERROR = { message: "Invalid assignment to `exports`.", type: "AssignmentExpression" }; testRule("no-assign-exports", rule, { valid: [ fixtures.CJS_WITH_EXPORTS, fixtures.CJS_WITH_MODULE_EXPORTS, fixtures.NON_WRAPPED_EXPORTS ], invalid: [ { code: fixtures.CJS_WITH_INVALID_EXPORTS, errors: [ERROR] } ] }); <|start_filename|>tests/lib/rules/no-invalid-require.js<|end_filename|> /** * @file Tests for `no-invalid-require` rule * @author <NAME> <<EMAIL>> */ "use strict"; const testRule = require("../../rule-tester"); const fixtures = require("../../fixtures"); const rule = require("../../../lib/rules/no-invalid-require"); // ----------------------------------------------------------------------------- // Tests // ----------------------------------------------------------------------------- const ERROR = { message: "Invalid arguments provided to `require` call.", type: "CallExpression" }; testRule("no-invalid-require", rule, { valid: [ fixtures.AMD_REQUIRE, fixtures.AMD_REQUIRE_RELATIVE, fixtures.AMD_REQUIRE_WITH_ERRBACK, fixtures.AMD_REQUIRE_CALLEXPRESSION_CALLBACK, fixtures.AMD_REQUIRE_MEMBEREXPRESSION_CALLBACK, fixtures.AMD_REQUIRE_IDENTIFIER_CALLBACK, fixtures.AMD_REQUIREJS, fixtures.AMD_REQUIREJS_RELATIVE, fixtures.AMD_REQUIREJS_WITH_ERRBACK, fixtures.AMD_REQUIREJS_CALLEXPRESSION_CALLBACK, fixtures.AMD_REQUIREJS_MEMBEREXPRESSION_CALLBACK, fixtures.AMD_REQUIREJS_IDENTIFIER_CALLBACK, fixtures.CJS_WITH_EXPORTS, fixtures.CJS_WITH_MODULE_EXPORTS, fixtures.CJS_WITH_RETURN, fixtures.CONDITIONAL_AMD_REQUIRE, fixtures.CONDITIONAL_AMD_REQUIREJS, fixtures.CONDITIONAL_CJS_REQUIRE, fixtures.CONDITIONAL_CJS_REQUIREJS, fixtures.CONDITIONAL_NESTED_AMD_REQUIRE, fixtures.CONDITIONAL_NESTED_AMD_REQUIREJS, fixtures.CONDITIONAL_TERNARY_CJS_REQUIRE, fixtures.CONDITIONAL_TERNARY_CJS_REQUIREJS, fixtures.DYNAMIC_AMD_REQUIRE_WITH_ERRBACK, fixtures.DYNAMIC_AMD_REQUIREJS_WITH_ERRBACK, fixtures.DYNAMIC_MIXED_AMD_REQUIRE, fixtures.DYNAMIC_MIXED_AMD_REQUIREJS, fixtures.DYNAMIC_TERNARY_AMD_REQUIRE, fixtures.DYNAMIC_TERNARY_AMD_REQUIREJS, fixtures.DYNAMIC_VARIABLE_AMD_REQUIRE, fixtures.DYNAMIC_VARIABLE_AMD_REQUIREJS, fixtures.DYNAMIC_VARIABLE_CJS_REQUIRE, fixtures.DYNAMIC_VARIABLE_CJS_REQUIREJS, fixtures.NESTED_AMD_REQUIRE, fixtures.NESTED_AMD_REQUIREJS, fixtures.NESTED_AMD_REQUIRE_NO_CALLBACK, fixtures.NESTED_AMD_REQUIREJS_NO_CALLBACK ], invalid: [ { code: fixtures.BAD_REQUIRE_EMPTY, errors: [ERROR] }, { code: fixtures.BAD_REQUIRE_NO_DEPS, errors: [ERROR] }, { code: fixtures.BAD_REQUIRE_OBJECT, errors: [ERROR] }, { code: fixtures.BAD_REQUIRE_TOO_MANY_ARGS, errors: [ERROR] }, { code: fixtures.BAD_REQUIRE_STRING_DEP, errors: [ERROR] }, { code: fixtures.BAD_REQUIREJS_STRING_DEP, errors: [ERROR] }, { code: fixtures.BAD_REQUIRE_INVALID_CALLBACK, errors: [ERROR] }, { code: fixtures.BAD_REQUIRE_INVALID_CALLBACK_ARRAY, errors: [ERROR] }, { code: fixtures.BAD_REQUIRE_INVALID_ERRBACK, errors: [ERROR] }, { code: fixtures.BAD_REQUIRE_INVALID_ERRBACK_ARRAY, errors: [ERROR] } ] }); <|start_filename|>lib/rules/sort-amd-paths.js<|end_filename|> /** * @file Rule to ensure that required paths are ordered alphabetically * @author <NAME> <<EMAIL>> * @author <NAME> <<EMAIL>> */ "use strict"; const rjs = require("../utils/rjs"); const isAmdDefine = rjs.isAmdDefine; const isAmdRequire = rjs.isAmdRequire; const getModuleFunction = rjs.getModuleFunction; const getDependencyStringNodes = rjs.getDependencyStringNodes; // ----------------------------------------------------------------------------- // Configuration // ----------------------------------------------------------------------------- const docs = { description: "Ensure that required paths are ordered alphabetically", category: "Stylistic Choices", recommended: false, url: "https://github.com/cvisco/eslint-plugin-requirejs/blob/master/docs/rules/sort-amd-paths.md" }; const schema = [ { type: "object", properties: { compare: { enum: ["dirname-basename", "fullpath", "basename"] }, sortPlugins: { enum: ["preserve", "first", "last", "ignore"] }, ignoreCase: { type: "boolean" } }, additionalProperties: false } ]; const defaults = { "compare": "dirname-basename", "sortPlugins": "preserve", "ignoreCase": true }; // ----------------------------------------------------------------------------- // Helpers // ----------------------------------------------------------------------------- const PLUGIN_REGEX = /^\w+\!/; const PATH_SEPARATOR = "/"; /** * Create a function that returns the additive inverse of the provided function. * @param {Function} fn - function to invert * @returns {Function} inverted function */ const inverse = (fn) => function () { return fn.apply(null, arguments) * -1; }; /** * Create a comparator that iteratively applies each provided function. Each * function should itself be a valid comparator (returning a negative number, * positive number or zero). This allows for sorting based on multiple criteria. * @param {Function[]} fns - array of comparator functions to apply * @returns {Function} multi-criteria comparator */ const comparator = (fns) => (a, b) => fns.reduce((n, f) => n ? n : f(a, b), 0); /** * Compare two string values. Comparison is done based on character value, so * uppercase letters are placed before lowercase ones. * @param {String} a - first value to compare * @param {String} b - second value to compare * @returns {Number} negative if `a` occurs before `b`; positive if `a` occurs * after `b`; 0 if they are equivalent in sort order */ const stringCompare = (a, b) => { if (a < b) return -1; if (a > b) return 1; return 0; }; /** * Compare two values based on existence, with values that exist sorted * before those that don't. * @param {*} a - first value to compare * @param {*} b - second value to compare * @returns {Number} negative if `a` occurs before `b`; positive if `a` occurs * after `b`; 0 if they are equivalent in sort order */ const existentialCompare = (a, b) => { if (a && !b) return -1; if (!a && b) return 1; return 0; }; /** * Compare two array values. * @param {Array} a - first array to compare * @param {Array} b - second array to compare * @returns {Number} negative if `a` occurs before `b`; positive if `a` occurs * after `b`; 0 if they are equivalent in sort order */ const arrayCompare = (a, b) => { const length = Math.max(a.length, b.length); for (let i = 0; i < length; i += 1) { if (!(i in a)) return -1; if (!(i in b)) return 1; if (a[i] < b[i]) return -1; if (a[i] > b[i]) return 1; } return 0; }; const toPathDescriptor = (opts) => (node) => { let value = opts.ignoreCase ? node.value.toLowerCase() : node.value; if (opts.sortPlugins === "ignore") { value = value.replace(PLUGIN_REGEX, ""); } const plugin = PLUGIN_REGEX.test(value); const path = value.split(PATH_SEPARATOR); const basename = path.slice(-1)[0]; const dirnames = path.slice(0, -1); return { node, value, plugin, basename, dirnames }; }; // Specific Comparators const comparePlugins = (a, b) => existentialCompare(a.plugin, b.plugin); const compareDirnames = (a, b) => arrayCompare(a.dirnames, b.dirnames); const compareBasenames = (a, b) => stringCompare(a.basename, b.basename); const compareFullPath = (a, b) => stringCompare(a.value, b.value); const message = (expected) => `Required paths are not in alphabetical order (expected '${expected}').`; // ----------------------------------------------------------------------------- // Rule Definition // ----------------------------------------------------------------------------- const comparators = { plugin: { "first": [comparePlugins], "last": [inverse(comparePlugins)], "ignore": [], "preserve": [] }, path: { "dirname-basename": [compareDirnames, compareBasenames], "basename": [compareBasenames], "fullpath": [compareFullPath] } }; function create(context) { const opts = Object.assign({}, defaults, context.options[0]); return { CallExpression(node) { if (!isAmdDefine(node) && !isAmdRequire(node)) return; const arity = getModuleFunction(node).params.length; const paths = getDependencyStringNodes(node).slice(0, arity); const criteria = [] .concat(comparators.plugin[opts.sortPlugins]) .concat(comparators.path[opts.compare]); const sorted = paths.slice() .map(toPathDescriptor(opts)) .sort(comparator(criteria)); for (let i = 0; i < paths.length; i++) { if (paths[i] !== sorted[i].node) { context.report(paths[i], message(sorted[i].node.value)); break; } } } }; } module.exports = { meta: { docs, schema }, create }; <|start_filename|>lib/rules/no-commonjs-return.js<|end_filename|> /** * @file Rule to disallow use of `return` statement in a module definition * when using Simplified CommonJS Wrapper * @author <NAME> <<EMAIL>> */ "use strict"; const ast = require("../utils/ast"); const rjs = require("../utils/rjs"); const nearest = ast.nearest; const isCommonJsWrapper = rjs.isCommonJsWrapper; // ----------------------------------------------------------------------------- // Configuration // ----------------------------------------------------------------------------- const docs = { description: "Disallow use of `return` statement in a module definition when", category: "Stylistic Choices", recommended: true, url: "https://github.com/cvisco/eslint-plugin-requirejs/blob/master/docs/rules/no-commonjs-return.md" }; const schema = []; const message = "Unexpected `return` in module definition."; // ----------------------------------------------------------------------------- // Helpers // ----------------------------------------------------------------------------- const isFunction = (node) => node.type === "FunctionDeclaration" || node.type === "FunctionExpression"; const nearestFunction = (node) => nearest(isFunction, node); // ----------------------------------------------------------------------------- // Rule Definition // ----------------------------------------------------------------------------- function create(context) { return { ReturnStatement(node) { if (isCommonJsWrapper(nearestFunction(node).parent)) { context.report(node, message); } } }; } module.exports = { meta: { docs, schema }, create }; <|start_filename|>tests/lib/rules/enforce-define.js<|end_filename|> /** * @file Tests for `enforce-define` rule * @author <NAME> <<EMAIL>> */ "use strict"; const testRule = require("../../rule-tester"); const fixtures = require("../../fixtures"); const rule = require("../../../lib/rules/enforce-define"); // ----------------------------------------------------------------------------- // Fixtures // ----------------------------------------------------------------------------- const UNWRAPPED_FILE_NO_EXPRESSIONSTATEMENT = ` var foo = 'foo'; function bar() { return foo; } `; const UNWRAPPED_FILE = ` var foo = 'foo'; function bar() { return foo; } window.bar = bar; `; // ----------------------------------------------------------------------------- // Tests // ----------------------------------------------------------------------------- const ERROR = { message: "File must be wrapped in a `define` call", type: "Program" }; testRule("enforce-define", rule, { valid: [ // Any sort of define should work fixtures.MULTIPLE_DEFINE, fixtures.OBJECT_DEFINE, fixtures.FUNCTION_DEFINE, fixtures.AMD_DEFINE, fixtures.AMD_EMPTY_DEFINE, fixtures.CJS_WITH_RETURN, fixtures.CJS_WITH_EXPORTS, fixtures.CJS_WITH_MODULE_EXPORTS, fixtures.CJS_WITH_FUNC_EXPR, fixtures.CJS_WITH_INVALID_EXPORTS, fixtures.NAMED_AMD_DEFINE, fixtures.NAMED_AMD_EMPTY_DEFINE, fixtures.NAMED_FUNCTION_DEFINE, fixtures.NAMED_OBJECT_DEFINE, fixtures.NAMED_CJS_DEFINE, fixtures.AMD_DEFINE_WITH_JS_EXT, fixtures.CJS_WITH_JS_EXT, fixtures.NAMED_AMD_DEFINE_WITH_JS_EXT, fixtures.NAMED_CJS_DEFINE_WITH_JS_EXT, // All of the invalid cases should work if we ignore the file { code: UNWRAPPED_FILE, filename: "main.js", options: [ "main.js" ] }, { code: fixtures.NON_WRAPPED_EXPORTS, filename: "main.js", options: [ "main.js" ] }, { code: fixtures.AMD_REQUIRE, filename: "main.js", options: [ "main.js" ] }, { code: fixtures.AMD_REQUIREJS, filename: "main.js", options: [ "main.js" ] }, // Ignore should work with full path { code: UNWRAPPED_FILE, filename: "path/to/main.js", options: [ [ "main.js" ] ] }, // Ignore should support multiple filenames { code: UNWRAPPED_FILE, filename: "main.js", options: [ [ "main.js", "index.js" ] ] }, { code: UNWRAPPED_FILE, filename: "index.js", options: [ [ "main.js", "index.js" ] ] } ], invalid: [ { code: UNWRAPPED_FILE, errors: [ERROR] }, { code: UNWRAPPED_FILE_NO_EXPRESSIONSTATEMENT, errors: [ERROR] }, { code: fixtures.NON_WRAPPED_EXPORTS, errors: [ERROR] }, { code: fixtures.AMD_REQUIRE, errors: [ERROR] }, { code: fixtures.AMD_REQUIREJS, errors: [ERROR] }, { code: UNWRAPPED_FILE, filename: "foo.js", args: [ 1, "main.js" ], errors: [ERROR] }, { code: UNWRAPPED_FILE, filename: "foo.js", args: [ 1, [ "main.js", "index.js" ] ], errors: [ERROR] }, { code: UNWRAPPED_FILE, filename: "path/to/foo.js", args: [ 1, "main.js" ], errors: [ERROR] }, { code: UNWRAPPED_FILE, filename: "path/to/main.js/foo.js", args: [ 1, "main.js" ], errors: [ERROR] } ] }); <|start_filename|>lib/utils/ast.js<|end_filename|> /** * @file Helper functions for working with AST Nodes * @author <NAME> <<EMAIL>> */ "use strict"; const isArray = Array.isArray; /** * Test if supplied `value` is an object. * @private * @param {*} value - value to test * @returns {Boolean} true if value is an object */ function isObject(value) { const type = typeof value; return type === "object" || type === "function"; } /** * Test if supplied `node` represents an identifier. * @param {ASTNode} node - node to test * @returns {Boolean} true if node represents an identifier */ function isIdentifier(node) { return isObject(node) && node.type === "Identifier"; } /** * Test if supplied `node` represents a literal of any kind. * @param {ASTNode} node - node to test * @returns {Boolean} true if node represents a literal */ function isLiteral(node) { return isObject(node) && node.type === "Literal"; } /** * Test if supplied `node` represents a string literal. * @param {ASTNode} node - node to test * @returns {Boolean} true if node represents a string literal */ function isStringLiteral(node) { return isLiteral(node) && typeof node.value === "string"; } /** * Test if supplied `node` represents an array expression. * @param {ASTNode} node - node to test * @returns {Boolean} true if node represents an array expression */ function isArrayExpr(node) { return isObject(node) && node.type === "ArrayExpression"; } /** * Test if supplied `node` represents an object expression. * @param {ASTNode} node - node to test * @returns {Boolean} true if node represents an object expression */ function isObjectExpr(node) { return isObject(node) && node.type === "ObjectExpression"; } /** * Test if supplied `node` represents a function expression. * @param {ASTNode} node - node to test * @returns {Boolean} true if node represents a function expression */ function isFunctionExpr(node) { return isObject(node) && (node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression"); } /** * Test if supplied `node` represents a member expression. * @param {ASTNode} node - node to test * @returns {Boolean} true if node represents a member expression */ function isMemberExpr(node) { return isObject(node) && node.type === "MemberExpression"; } /** * Test if supplied `node` represents an expression of any kind. * @param {ASTNode} node - node to test * @returns {Boolean} true if node represents an expression statement */ function isExprStatement(node) { return isObject(node) && node.type === "ExpressionStatement"; } /** * Test if supplied `node` represents an array of string literals. Empty * arrays are also valid here. * @param {ASTNode} node - ArrayExpression node to test * @returns {Boolean} true if node represents an array of string literals */ function isStringLiteralArray(node) { return isArrayExpr(node) && isArray(node.elements) && node.elements.every(isStringLiteral); } /** * Test if supplied `node` has parameters. * @param {ASTNode} node - FunctionExpression node to test * @returns {Boolean} true if node has at least one parameter */ function hasParams(node) { return isObject(node) && isArray(node.params) && node.params.length > 0; } /** * Test if supplied `node` has at least one callback argument * @param {ASTNode} node - CallExpression node to test * @returns {Boolean} true if node has at least one callback */ function hasCallback(node) { return isObject(node) && isArray(node.arguments) && node.arguments.some(isFunctionExpr); } /** * Determine if `node` has an ancestor satisfying `predicate`. * @param {Function} predicate - predicate to test each ancestor against * @param {ASTNode} node - child node to begin search at * @returns {Boolean} true if an ancestor satisfies `predicate` */ function ancestor(predicate, node) { while ((node = node.parent)) { if (predicate(node)) return true; } return false; } /** * Find the nearest ancestor satisfying `predicate`. * @param {Function} predicate - predicate to test each ancestor against * @param {ASTNode} node - child node to begin search at * @returns {ASTNode|undefined} nearest ancestor satisfying `predicate`, if any */ function nearest(predicate, node) { while ((node = node.parent)) { if (predicate(node)) return node; } return undefined; } module.exports = { isIdentifier, isLiteral, isStringLiteral, isArrayExpr, isObjectExpr, isMemberExpr, isFunctionExpr, isExprStatement, isStringLiteralArray, hasParams, hasCallback, ancestor, nearest }; <|start_filename|>tests/lib/rules/no-amd-define.js<|end_filename|> /** * @file Tests for `no-amd-define` rule * @author <NAME> <<EMAIL>> */ "use strict"; const testRule = require("../../rule-tester"); const fixtures = require("../../fixtures"); const rule = require("../../../lib/rules/no-amd-define"); // ----------------------------------------------------------------------------- // Tests // ----------------------------------------------------------------------------- const ERROR = { message: "AMD form of `define` is not allowed.", type: "CallExpression" }; testRule("no-amd-define", rule, { valid: [ fixtures.OBJECT_DEFINE, fixtures.FUNCTION_DEFINE, fixtures.CJS_WITH_RETURN, fixtures.CJS_WITH_EXPORTS, fixtures.CJS_WITH_MODULE_EXPORTS, fixtures.NAMED_OBJECT_DEFINE, fixtures.NAMED_FUNCTION_DEFINE, fixtures.NAMED_CJS_DEFINE ], invalid: [ { code: fixtures.AMD_DEFINE, errors: [ERROR] }, { code: fixtures.AMD_EMPTY_DEFINE, errors: [ERROR] }, { code: fixtures.NAMED_AMD_DEFINE, errors: [ERROR] }, { code: fixtures.NAMED_AMD_EMPTY_DEFINE, errors: [ERROR] } ] }); <|start_filename|>tests/lib/rules/no-function-define.js<|end_filename|> /** * @file Tests for `no-function-define` rule * @author <NAME> <<EMAIL>> */ "use strict"; const testRule = require("../../rule-tester"); const fixtures = require("../../fixtures"); const rule = require("../../../lib/rules/no-function-define"); // ----------------------------------------------------------------------------- // Tests // ----------------------------------------------------------------------------- const ERROR = { message: "Simple function form of `define` is not allowed", type: "CallExpression" }; testRule("no-function-define", rule, { valid: [ fixtures.OBJECT_DEFINE, fixtures.CJS_WITH_RETURN, fixtures.CJS_WITH_EXPORTS, fixtures.CJS_WITH_MODULE_EXPORTS, fixtures.AMD_DEFINE, fixtures.AMD_EMPTY_DEFINE, fixtures.NAMED_OBJECT_DEFINE, fixtures.NAMED_AMD_DEFINE, fixtures.NAMED_AMD_EMPTY_DEFINE, fixtures.NAMED_CJS_DEFINE ], invalid: [ { code: fixtures.FUNCTION_DEFINE, errors: [ERROR] }, { code: fixtures.NAMED_FUNCTION_DEFINE, errors: [ERROR] } ] }); <|start_filename|>tests/lib/rules/no-commonjs-return.js<|end_filename|> /** * @file Tests for `no-commonjs-return` rule * @author <NAME> <<EMAIL>> */ "use strict"; const testRule = require("../../rule-tester"); const fixtures = require("../../fixtures"); const rule = require("../../../lib/rules/no-commonjs-return"); // ----------------------------------------------------------------------------- // Tests // ----------------------------------------------------------------------------- const ERROR = { message: "Unexpected `return` in module definition.", type: "ReturnStatement" }; testRule("no-commonjs-return", rule, { valid: [ fixtures.OBJECT_DEFINE, fixtures.FUNCTION_DEFINE, fixtures.AMD_DEFINE, fixtures.AMD_EMPTY_DEFINE, fixtures.NAMED_OBJECT_DEFINE, fixtures.NAMED_FUNCTION_DEFINE, fixtures.NAMED_AMD_DEFINE, fixtures.NAMED_AMD_EMPTY_DEFINE, fixtures.NAMED_CJS_DEFINE, fixtures.CJS_WITH_EXPORTS, fixtures.CJS_WITH_MODULE_EXPORTS, fixtures.CJS_WITH_FUNC_EXPR, fixtures.CJS_WITH_NESTED_RETURNS ], invalid: [ { code: fixtures.CJS_WITH_RETURN, errors: [ERROR] } ] }); <|start_filename|>tests/lib/rules/no-commonjs-module-exports.js<|end_filename|> /** * @file Tests for `no-commonjs-module-exports` rule * @author <NAME> <<EMAIL>> */ "use strict"; const testRule = require("../../rule-tester"); const fixtures = require("../../fixtures"); const rule = require("../../../lib/rules/no-commonjs-module-exports"); // ----------------------------------------------------------------------------- // Tests // ----------------------------------------------------------------------------- const ERROR = { message: "Unexpected use of `module.exports` in module definition.", type: "AssignmentExpression" }; testRule("no-commonjs-module-exports", rule, { valid: [ fixtures.OBJECT_DEFINE, fixtures.FUNCTION_DEFINE, fixtures.AMD_DEFINE, fixtures.AMD_EMPTY_DEFINE, fixtures.NAMED_OBJECT_DEFINE, fixtures.NAMED_FUNCTION_DEFINE, fixtures.NAMED_AMD_DEFINE, fixtures.NAMED_AMD_EMPTY_DEFINE, fixtures.CJS_WITH_RETURN, fixtures.CJS_WITH_EXPORTS, fixtures.NON_WRAPPED_EXPORTS ], invalid: [ { code: fixtures.CJS_WITH_MODULE_EXPORTS, errors: [ERROR] }, { code: fixtures.CJS_WITH_FUNC_EXPR, errors: [ERROR] }, { code: fixtures.NAMED_CJS_DEFINE, errors: [ERROR] } ] }); <|start_filename|>tests/lib/rules/no-restricted-amd-modules.js<|end_filename|> /** * @file Tests for `no-restricted-amd-modules` rule * @author <NAME> */ "use strict"; const testRule = require("../../rule-tester"); const fixtures = require("../../fixtures"); const rule = require("../../../lib/rules/no-restricted-amd-modules"); // ----------------------------------------------------------------------------- // Tests // ----------------------------------------------------------------------------- const errorMsg = expected => ({ message: `'${expected}' module is restricted from being used.`, type: "Literal" }); testRule("no-restricted-amd-modules", rule, { valid: [ { code: fixtures.AMD_DEFINE, options: ["foo"] }, { code: fixtures.FUNCTION_DEFINE, options: ["foo", "bar"] }, { code: fixtures.AMD_DEFINE, options: ["foo", "bar"] }, fixtures.AMD_DEFINE, { code: fixtures.AMD_DEFINE_WITH_FOO_PLUGIN_AND_JS_EXT, options: ["foo"] }, { code: fixtures.AMD_DEFINE_WITH_JS_EXT, options: ["foo"] }, { code: fixtures.AMD_EMPTY_DEFINE, options: ["foo"] }, { code: fixtures.AMD_DEFINE, options: ["path/to"] }, { code: fixtures.AMD_DEFINE, options: [{ paths: ["path", "to", "a"] }] }, { code: fixtures.AMD_DEFINE, options: [{ patterns: ["path/to/c*"] }] }, { code: fixtures.AMD_DEFINE, options: [{ paths: ["path/to"], patterns: ["path/to/c*"] }] }, { code: fixtures.AMD_DEFINE_WITH_JS_EXT, options: [ { paths: ["path/to"], patterns: ["path/to/*", "!path/to/a.js"] } ] } ], invalid: [ { code: fixtures.AMD_DEFINE, options: ["path/to/a"], errors: [errorMsg("path/to/a")] }, { code: fixtures.AMD_DEFINE, options: ["path/to/b"], errors: [errorMsg("path/to/b")] }, { code: fixtures.AMD_DEFINE_WITH_JS_EXT, options: [{ paths: ["path/to/a.js"] }], errors: [errorMsg("path/to/a.js")] }, { code: fixtures.AMD_DEFINE_WITH_FOO_PLUGIN_AND_JS_EXT, options: [{ paths: ["foo!aaa/bbb/ccc.js"] }], errors: [errorMsg("foo!aaa/bbb/ccc.js")] }, { code: fixtures.AMD_DEFINE_WITH_FOO_PLUGIN_AND_JS_EXT, options: [{ patterns: ["*!aaa/bbb/ccc.js"] }], errors: [ { message: "'foo!aaa/bbb/ccc.js' module is restricted from being used by a pattern.", type: "CallExpression" } ] }, { code: fixtures.AMD_DEFINE, options: [{ patterns: ["path/to/*"] }], errors: [ { message: "'path/to/a' module is restricted from being used by a pattern.", type: "CallExpression" } ] }, { code: fixtures.AMD_DEFINE, options: [{ paths: ["path/to/*"], patterns: ["path/to"] }], errors: [ { message: "'path/to/a' module is restricted from being used by a pattern.", type: "CallExpression" } ] }, { code: fixtures.AMD_DEFINE, options: [ { patterns: ["path/to/*", "!path/to/c"], paths: ["path/to"] } ], errors: [ { message: "'path/to/a' module is restricted from being used by a pattern.", type: "CallExpression" } ] }, { code: fixtures.AMD_DEFINE, options: [ { name: "path/to/a", message: "Please use 'path/to/c' module instead." } ], errors: [ { message: "'path/to/a' module is restricted from being used. Please use 'path/to/c' module instead.", type: "Literal" } ] }, { code: fixtures.AMD_DEFINE, options: [ "path/to", { name: "path/to/a", message: "Please use 'path/to/c' module instead." }, "path/to/d" ], errors: [ { message: "'path/to/a' module is restricted from being used. Please use 'path/to/c' module instead.", type: "Literal" } ] } ] }); <|start_filename|>tests/lib/rules/no-dynamic-require.js<|end_filename|> /** * @file Tests for `no-dynamic-require` rule * @author <NAME> <<EMAIL>> */ "use strict"; const testRule = require("../../rule-tester"); const fixtures = require("../../fixtures"); const rule = require("../../../lib/rules/no-dynamic-require"); // ----------------------------------------------------------------------------- // Tests // ----------------------------------------------------------------------------- const ERROR = { message: "Dynamic `require` calls are not allowed.", type: "CallExpression" }; testRule("no-dynamic-require", rule, { valid: [ fixtures.AMD_REQUIRE, fixtures.AMD_REQUIRE_RELATIVE, fixtures.AMD_EMPTY_REQUIRE, fixtures.AMD_REQUIRE_WITH_ERRBACK, fixtures.AMD_REQUIREJS, fixtures.AMD_REQUIREJS_RELATIVE, fixtures.AMD_EMPTY_REQUIREJS, fixtures.AMD_REQUIREJS_WITH_ERRBACK, fixtures.NESTED_AMD_REQUIRE, fixtures.NESTED_AMD_REQUIREJS, fixtures.NESTED_AMD_REQUIRE_NO_CALLBACK, fixtures.NESTED_AMD_REQUIREJS_NO_CALLBACK, fixtures.CJS_WITH_RETURN, fixtures.CJS_WITH_EXPORTS, fixtures.CJS_WITH_MODULE_EXPORTS, fixtures.NAMED_CJS_DEFINE, fixtures.CONDITIONAL_AMD_REQUIRE, fixtures.CONDITIONAL_CJS_REQUIRE, fixtures.CONDITIONAL_TERNARY_CJS_REQUIRE, fixtures.CONDITIONAL_NESTED_AMD_REQUIRE, fixtures.CONDITIONAL_AMD_REQUIREJS, fixtures.CONDITIONAL_CJS_REQUIREJS, fixtures.CONDITIONAL_TERNARY_CJS_REQUIREJS, fixtures.CONDITIONAL_NESTED_AMD_REQUIREJS ], invalid: [ { code: fixtures.DYNAMIC_MIXED_AMD_REQUIRE, errors: [ERROR] }, { code: fixtures.DYNAMIC_TERNARY_AMD_REQUIRE, errors: [ERROR] }, { code: fixtures.DYNAMIC_VARIABLE_AMD_REQUIRE, errors: [ERROR] }, { code: fixtures.DYNAMIC_TERNARY_CJS_REQUIRE, errors: [ERROR] }, { code: fixtures.DYNAMIC_VARIABLE_CJS_REQUIRE, errors: [ERROR] }, { code: fixtures.DYNAMIC_AMD_REQUIRE_WITH_ERRBACK, errors: [ERROR] }, { code: fixtures.DYNAMIC_MIXED_AMD_REQUIREJS, errors: [ERROR] }, { code: fixtures.DYNAMIC_TERNARY_AMD_REQUIREJS, errors: [ERROR] }, { code: fixtures.DYNAMIC_VARIABLE_AMD_REQUIREJS, errors: [ERROR] }, { code: fixtures.DYNAMIC_TERNARY_CJS_REQUIREJS, errors: [ERROR] }, { code: fixtures.DYNAMIC_VARIABLE_CJS_REQUIREJS, errors: [ERROR] }, { code: fixtures.DYNAMIC_AMD_REQUIREJS_WITH_ERRBACK, errors: [ERROR] } ] }); <|start_filename|>tests/lib/rules/amd-function-arity.js<|end_filename|> /** * @file Tests for `amd-function-arity` rule * @author <NAME> */ "use strict"; const testRule = require("../../rule-tester"); const fixtures = require("../../fixtures"); const rule = require("../../../lib/rules/amd-function-arity"); // ----------------------------------------------------------------------------- // Tests // ----------------------------------------------------------------------------- function tooManyParams(expected, actual) { return { message: `Too many parameters in callback (expected ${expected}, found ${actual}).` }; } function tooFewParams(expected, actual) { return { message: `Not enough parameters in callback (expected ${expected}, found ${actual}).` }; } testRule("amd-function-arity", rule, { valid: [ // Dependency count and parameter counts equal-- always valid fixtures.AMD_DEFINE, fixtures.AMD_EMPTY_DEFINE, fixtures.AMD_EMPTY_REQUIRE, fixtures.AMD_EMPTY_REQUIREJS, fixtures.AMD_REQUIRE, fixtures.AMD_REQUIRE_WITH_ERRBACK, fixtures.AMD_REQUIREJS, fixtures.AMD_REQUIREJS_WITH_ERRBACK, fixtures.NAMED_AMD_DEFINE, fixtures.NAMED_AMD_EMPTY_DEFINE, fixtures.DYNAMIC_AMD_REQUIRE_WITH_ERRBACK, fixtures.DYNAMIC_AMD_REQUIREJS_WITH_ERRBACK, fixtures.DYNAMIC_MIXED_AMD_REQUIRE, fixtures.DYNAMIC_MIXED_AMD_REQUIREJS, // Valid because dependency array arity is unknowable fixtures.DYNAMIC_VARIABLE_AMD_DEFINE, fixtures.DYNAMIC_VARIABLE_AMD_NAMED_DEFINE, fixtures.DYNAMIC_VARIABLE_AMD_REQUIRE, // Valid only if allowExtraDependencies is enabled { code: fixtures.AMD_DEFINE_TOO_FEW_CALLBACK_PARAMS, options: [{ allowExtraDependencies: true }] }, { code: fixtures.AMD_NAMED_DEFINE_TOO_FEW_CALLBACK_PARAMS, options: [{ allowExtraDependencies: true }] }, { code: fixtures.AMD_REQUIRE_TOO_FEW_CALLBACK_PARAMS, options: [{ allowExtraDependencies: true }] }, { code: fixtures.AMD_REQUIREJS_TOO_FEW_CALLBACK_PARAMS, options: [{ allowExtraDependencies: true }] }, { code: fixtures.AMD_REQUIRE_TOO_FEW_CALLBACK_PARAMS_WITH_ERRBACK, options: [{ allowExtraDependencies: true }] }, { code: fixtures.AMD_REQUIREJS_TOO_FEW_CALLBACK_PARAMS_WITH_ERRBACK, options: [{ allowExtraDependencies: true }] }, { code: fixtures.AMD_REQUIRE_SINGLEDEP_TOO_FEW_CALLBACK_PARAMS, options: [{ allowExtraDependencies: true }] }, { code: fixtures.AMD_REQUIREJS_SINGLEDEP_TOO_FEW_CALLBACK_PARAMS, options: [{ allowExtraDependencies: true }] }, { code: fixtures.AMD_REQUIRE_SINGLEDEP_TOO_FEW_CALLBACK_PARAMS_WITH_ERRBACK, options: [{ allowExtraDependencies: true }] }, { code: fixtures.AMD_REQUIREJS_SINGLEDEP_TOO_FEW_CALLBACK_PARAMS_WITH_ERRBACK, options: [{ allowExtraDependencies: true }] }, // Valid only if allowedExtraDependencies are specified { code: fixtures.AMD_DEFINE_TOO_FEW_CALLBACK_PARAMS, options: [{ allowExtraDependencies: ["b"] }] }, { code: fixtures.AMD_NAMED_DEFINE_TOO_FEW_CALLBACK_PARAMS, options: [{ allowExtraDependencies: ["b"] }] }, { code: fixtures.AMD_REQUIRE_TOO_FEW_CALLBACK_PARAMS, options: [{ allowExtraDependencies: ["b"] }] }, { code: fixtures.AMD_REQUIREJS_TOO_FEW_CALLBACK_PARAMS, options: [{ allowExtraDependencies: ["b"] }] }, { code: fixtures.AMD_REQUIRE_TOO_FEW_CALLBACK_PARAMS_WITH_ERRBACK, options: [{ allowExtraDependencies: ["b"] }] }, { code: fixtures.AMD_REQUIREJS_TOO_FEW_CALLBACK_PARAMS_WITH_ERRBACK, options: [{ allowExtraDependencies: ["b"] }] }, { code: fixtures.AMD_REQUIRE_SINGLEDEP_TOO_FEW_CALLBACK_PARAMS, options: [{ allowExtraDependencies: ["a"] }] }, { code: fixtures.AMD_REQUIREJS_SINGLEDEP_TOO_FEW_CALLBACK_PARAMS, options: [{ allowExtraDependencies: ["a"] }] }, { code: fixtures.AMD_REQUIRE_SINGLEDEP_TOO_FEW_CALLBACK_PARAMS_WITH_ERRBACK, options: [{ allowExtraDependencies: ["a"] }] }, { code: fixtures.AMD_REQUIREJS_SINGLEDEP_TOO_FEW_CALLBACK_PARAMS_WITH_ERRBACK, options: [{ allowExtraDependencies: ["a"] }] } ], invalid: [ // Too few dependencies (invalid even with allowExtraDependencies option) { code: fixtures.AMD_DEFINE_TOO_MANY_CALLBACK_PARAMS, options: [{ allowExtraDependencies: true }], errors: [tooManyParams(2, 3)] }, { code: fixtures.AMD_NAMED_DEFINE_TOO_MANY_CALLBACK_PARAMS, options: [{ allowExtraDependencies: true }], errors: [tooManyParams(2, 3)] }, { code: fixtures.AMD_REQUIRE_TOO_MANY_CALLBACK_PARAMS, options: [{ allowExtraDependencies: true }], errors: [tooManyParams(2, 3)] }, { code: fixtures.AMD_REQUIREJS_TOO_MANY_CALLBACK_PARAMS, options: [{ allowExtraDependencies: true }], errors: [tooManyParams(2, 3)] }, { code: fixtures.AMD_REQUIRE_TOO_MANY_CALLBACK_PARAMS_WITH_ERRBACK, options: [{ allowExtraDependencies: true }], errors: [tooManyParams(2, 3)] }, { code: fixtures.AMD_REQUIREJS_TOO_MANY_CALLBACK_PARAMS_WITH_ERRBACK, options: [{ allowExtraDependencies: true }], errors: [tooManyParams(2, 3)] }, { code: fixtures.AMD_REQUIRE_SINGLEDEP_TOO_MANY_CALLBACK_PARAMS, options: [{ allowExtraDependencies: true }], errors: [tooManyParams(1, 2)] }, { code: fixtures.AMD_REQUIREJS_SINGLEDEP_TOO_MANY_CALLBACK_PARAMS, options: [{ allowExtraDependencies: true }], errors: [tooManyParams(1, 2)] }, { code: fixtures.AMD_REQUIRE_SINGLEDEP_TOO_MANY_CALLBACK_PARAMS_WITH_ERRBACK, options: [{ allowExtraDependencies: true }], errors: [tooManyParams(1, 2)] }, { code: fixtures.AMD_REQUIREJS_SINGLEDEP_TOO_MANY_CALLBACK_PARAMS_WITH_ERRBACK, options: [{ allowExtraDependencies: true }], errors: [tooManyParams(1, 2)] }, // Extra dependencies (invalid since option not specified) { code: fixtures.AMD_DEFINE_TOO_FEW_CALLBACK_PARAMS, errors: [tooFewParams(2, 1)] }, { code: fixtures.AMD_NAMED_DEFINE_TOO_FEW_CALLBACK_PARAMS, errors: [tooFewParams(2, 1)] }, { code: fixtures.AMD_REQUIRE_TOO_FEW_CALLBACK_PARAMS, errors: [tooFewParams(2, 1)] }, { code: fixtures.AMD_REQUIREJS_TOO_FEW_CALLBACK_PARAMS, errors: [tooFewParams(2, 1)] }, { code: fixtures.AMD_REQUIRE_TOO_FEW_CALLBACK_PARAMS_WITH_ERRBACK, errors: [tooFewParams(2, 1)] }, { code: fixtures.AMD_REQUIREJS_TOO_FEW_CALLBACK_PARAMS_WITH_ERRBACK, errors: [tooFewParams(2, 1)] }, { code: fixtures.AMD_REQUIRE_SINGLEDEP_TOO_FEW_CALLBACK_PARAMS, errors: [tooFewParams(1, 0)] }, { code: fixtures.AMD_REQUIREJS_SINGLEDEP_TOO_FEW_CALLBACK_PARAMS, errors: [tooFewParams(1, 0)] }, { code: fixtures.AMD_REQUIRE_SINGLEDEP_TOO_FEW_CALLBACK_PARAMS_WITH_ERRBACK, errors: [tooFewParams(1, 0)] }, { code: fixtures.AMD_REQUIREJS_SINGLEDEP_TOO_FEW_CALLBACK_PARAMS_WITH_ERRBACK, errors: [tooFewParams(1, 0)] }, // Extra dependencies (invalid since option set to false) { code: fixtures.AMD_DEFINE_TOO_FEW_CALLBACK_PARAMS, options: [{ allowExtraDependencies: false }], errors: [tooFewParams(2, 1)] }, { code: fixtures.AMD_NAMED_DEFINE_TOO_FEW_CALLBACK_PARAMS, options: [{ allowExtraDependencies: false }], errors: [tooFewParams(2, 1)] }, { code: fixtures.AMD_REQUIRE_TOO_FEW_CALLBACK_PARAMS, options: [{ allowExtraDependencies: false }], errors: [tooFewParams(2, 1)] }, { code: fixtures.AMD_REQUIREJS_TOO_FEW_CALLBACK_PARAMS, options: [{ allowExtraDependencies: false }], errors: [tooFewParams(2, 1)] }, { code: fixtures.AMD_REQUIRE_TOO_FEW_CALLBACK_PARAMS_WITH_ERRBACK, options: [{ allowExtraDependencies: false }], errors: [tooFewParams(2, 1)] }, { code: fixtures.AMD_REQUIREJS_TOO_FEW_CALLBACK_PARAMS_WITH_ERRBACK, options: [{ allowExtraDependencies: false }], errors: [tooFewParams(2, 1)] }, { code: fixtures.AMD_REQUIRE_SINGLEDEP_TOO_FEW_CALLBACK_PARAMS, options: [{ allowExtraDependencies: false }], errors: [tooFewParams(1, 0)] }, { code: fixtures.AMD_REQUIREJS_SINGLEDEP_TOO_FEW_CALLBACK_PARAMS, options: [{ allowExtraDependencies: false }], errors: [tooFewParams(1, 0)] }, { code: fixtures.AMD_REQUIRE_SINGLEDEP_TOO_FEW_CALLBACK_PARAMS_WITH_ERRBACK, options: [{ allowExtraDependencies: false }], errors: [tooFewParams(1, 0)] }, { code: fixtures.AMD_REQUIREJS_SINGLEDEP_TOO_FEW_CALLBACK_PARAMS_WITH_ERRBACK, options: [{ allowExtraDependencies: false }], errors: [tooFewParams(1, 0)] }, // Extra dependencies (invalid since allowed paths are not the extra dependencies) { code: fixtures.AMD_DEFINE_TOO_FEW_CALLBACK_PARAMS, options: [{ allowExtraDependencies: ["x", "y"] }], errors: [tooFewParams(2, 1)] }, { code: fixtures.AMD_NAMED_DEFINE_TOO_FEW_CALLBACK_PARAMS, options: [{ allowExtraDependencies: ["x", "y"] }], errors: [tooFewParams(2, 1)] }, { code: fixtures.AMD_REQUIRE_TOO_FEW_CALLBACK_PARAMS, options: [{ allowExtraDependencies: ["x", "y"] }], errors: [tooFewParams(2, 1)] }, { code: fixtures.AMD_REQUIREJS_TOO_FEW_CALLBACK_PARAMS, options: [{ allowExtraDependencies: ["x", "y"] }], errors: [tooFewParams(2, 1)] }, { code: fixtures.AMD_REQUIRE_TOO_FEW_CALLBACK_PARAMS_WITH_ERRBACK, options: [{ allowExtraDependencies: ["x", "y"] }], errors: [tooFewParams(2, 1)] }, { code: fixtures.AMD_REQUIREJS_TOO_FEW_CALLBACK_PARAMS_WITH_ERRBACK, options: [{ allowExtraDependencies: ["x", "y"] }], errors: [tooFewParams(2, 1)] }, { code: fixtures.AMD_REQUIRE_SINGLEDEP_TOO_FEW_CALLBACK_PARAMS, options: [{ allowExtraDependencies: ["x", "y"] }], errors: [tooFewParams(1, 0)] }, { code: fixtures.AMD_REQUIREJS_SINGLEDEP_TOO_FEW_CALLBACK_PARAMS, options: [{ allowExtraDependencies: ["x", "y"] }], errors: [tooFewParams(1, 0)] }, { code: fixtures.AMD_REQUIRE_SINGLEDEP_TOO_FEW_CALLBACK_PARAMS_WITH_ERRBACK, options: [{ allowExtraDependencies: ["x", "y"] }], errors: [tooFewParams(1, 0)] }, { code: fixtures.AMD_REQUIREJS_SINGLEDEP_TOO_FEW_CALLBACK_PARAMS_WITH_ERRBACK, options: [{ allowExtraDependencies: ["x", "y"] }], errors: [tooFewParams(1, 0)] } ] }); <|start_filename|>tests/lib/rules/no-assign-require.js<|end_filename|> /** * @file Tests for `no-assign-require` rule * @author <NAME> <<EMAIL>> */ "use strict"; const testRule = require("../../rule-tester"); const rule = require("../../../lib/rules/no-assign-require"); // ----------------------------------------------------------------------------- // Fixtures // ----------------------------------------------------------------------------- const OK_PROPERTY_ASSIGNMENT = ` foo.require = { bar: 'bar' }; `; const OK_SIMILAR_VARIABLE = ` var required = true; `; const BAD_DECLARE_REQUIRE = ` var require = { deps: ['path/to/a', 'path/to/b'], callback: function (a, b) { a.foo(); b.bar(); } }; `; const BAD_ASSIGN_TO_REQUIRE = ` require = { deps: ['path/to/a', 'path/to/b'], callback: function (a, b) { a.foo(); b.bar(); } }; `; const BAD_ASSIGN_TO_WINDOW_REQUIRE = ` window.require = { deps: ['path/to/a', 'path/to/b'], callback: function (a, b) { a.foo(); b.bar(); } }; `; // ----------------------------------------------------------------------------- // Tests // ----------------------------------------------------------------------------- const ERROR_MSG = "Invalid assignment to `require`."; testRule("no-assign-require", rule, { valid: [ OK_PROPERTY_ASSIGNMENT, OK_SIMILAR_VARIABLE ], invalid: [ { code: BAD_DECLARE_REQUIRE, errors: [ { message: ERROR_MSG, type: "VariableDeclarator" } ] }, { code: BAD_ASSIGN_TO_REQUIRE, errors: [ { message: ERROR_MSG, type: "AssignmentExpression" } ] }, { code: BAD_ASSIGN_TO_WINDOW_REQUIRE, errors: [ { message: ERROR_MSG, type: "AssignmentExpression" } ] } ] }); <|start_filename|>makefile.js<|end_filename|> /** * @fileoverview Build file. Based in large part on functionality found in * eslint's own makefile, with necessary tweaks for building an * eslint plugin instead. * * @author <NAME> */ "use strict"; /* eslint-env shelljs */ require("shelljs/make"); const path = require("path"); const semver = require("semver"); const dateformat = require("dateformat"); const nodeCLI = require("shelljs-nodecli"); // Tools const MOCHA = path.normalize("./node_modules/mocha/bin/_mocha"); // Files const MAKEFILE = "./makefile.js"; const JS_FILES = find("lib/").filter(fileType("js")).join(" "); const TEST_FILES = find("tests/lib/").filter(fileType("js")).join(" "); /** * Generate a function that matches files with a particular extension. * * @private * @param {String} extension - the file extension (i.e. "js") * @returns {Function} function to pass into a filter method */ function fileType(extension) { return function (filename) { return filename.substring(filename.lastIndexOf(".") + 1) === extension; }; } /** * Execute a command and return the output instead of printing it to stdout. * * @private * @param {String} cmd - command to execute * @returns {String} result of executed command */ function execSilent(cmd) { return exec(cmd, { silent: true }).output; } /** * Push supplied `tag` to supplied `list` only if it is a valid semver. This is * a reducer function. * * @private * @param {Array} list - array of valid semver tags * @param {String} tag - tag to push if valid * @returns {Array} modified `list` */ function validSemverTag(list, tag) { if (semver.valid(tag)) { list.push(tag); } return list; } /** * Retrieve a list of semver tags in descending order. * * @private * @returns {Array} list of version tags */ function getVersionTags() { return execSilent("git tag") .trim() .split("\n") .reduce(validSemverTag, []) .sort(semver.compare); } /** * Create a release version, push tags and publish. * * @private * @param {String} type - type of release to do (patch, minor, major) * @returns {void} */ function release(type) { target.test(); echo("Generating new version"); const newVersion = execSilent("npm version " + type).trim(); target.changelog(); // add changelog to commit exec("git add CHANGELOG.md"); exec("git commit --amend --no-edit"); // replace existing tag exec("git tag -f " + newVersion); // push all the things echo("Publishing to git"); exec("git push origin master --tags"); echo("Publishing to npm"); exec("npm publish"); } target.lint = function () { let errors = 0; echo("Linting makefile"); errors += nodeCLI.exec("eslint", MAKEFILE).code; echo("Linting JavaScript files"); errors += nodeCLI.exec("eslint", JS_FILES).code; echo("Linting JavaScript test files"); errors += nodeCLI.exec("eslint", TEST_FILES).code; if (errors) { exit(1); } }; /** * Verify that each rule is defined in index.js with the correct default * setting, has documentation and has tests. * @returns {void} */ target.checkRules = function () { echo("Verifying rules"); const ruleFiles = find("lib/rules/").filter(fileType("js")); const configFile = require("./index"); const readmeText = cat("./README.md"); let errors = 0; function isDefinedInConfig(rule) { return configFile.rules.hasOwnProperty(rule); } function hasIdInTitle(docFile, id) { const docText = cat(docFile); const idInTitleRegExp = new RegExp("^# (.*?) \\(" + id + "\\)"); return idInTitleRegExp.test(docText); } ruleFiles.forEach(function (filename) { const basename = path.basename(filename, ".js"); const docFilename = "docs/rules/" + basename + ".md"; const testFilename = "tests/lib/rules/" + basename + ".js"; // Verify rule has documentation if (!test("-f", docFilename)) { console.error("Missing documentation for rule %s", basename); errors++; } else { if (readmeText.indexOf("(" + docFilename + ")") === -1) { console.error("Missing link to documentation for rule %s in index", basename); errors++; } // check for proper doc format if (!hasIdInTitle(docFilename, basename)) { console.error("Missing id in the doc page's title of rule %s", basename); errors++; } } // Verify rule has tests if (!test("-f", testFilename)) { console.error("Missing tests for rule %s", basename); errors++; } // Verify config if (!isDefinedInConfig(basename)) { console.error("Missing rule entry for %s in index.js", basename); errors++; } }); if (errors) { exit(1); } }; target.unit = function () { let errors = 0; echo("Running test suite"); errors += nodeCLI.exec("istanbul", "cover", MOCHA, "-- -R progress -t 3000 -c", TEST_FILES).code; errors += nodeCLI.exec("istanbul", "check-coverage", "--statement 100 --branch 95 --function 100 --lines 100").code; if (errors) { exit(1); } }; target.test = function () { target.lint(); target.checkRules(); target.unit(); }; target.changelog = function () { echo("Generating changelog"); // get most recent two tags const tags = getVersionTags(); const rangeTags = tags.slice(tags.length - 2); const timestamp = dateformat(new Date(), "mmmm d, yyyy"); const semverRe = /^\* \d+\.\d+.\d+/; // output header ("### " + rangeTags[1] + " - " + timestamp + "\n").to("CHANGELOG.tmp"); // get log statements let logs = execSilent("git log --pretty=format:\"* %s (%an)\" " + rangeTags.join("..")).split(/\n/g); logs = logs.filter(function (line) { return line.indexOf("Merge pull request") === -1 && line.indexOf("Merge branch") === -1 && !semverRe.test(line); }); logs.push(""); // to create empty lines logs.unshift(""); // output log statements logs.join("\n").toEnd("CHANGELOG.tmp"); cat("CHANGELOG.tmp", "CHANGELOG.md").to("CHANGELOG.md.tmp"); rm("CHANGELOG.tmp"); rm("CHANGELOG.md"); mv("CHANGELOG.md.tmp", "CHANGELOG.md"); }; target.patch = function () { release("patch"); }; target.minor = function () { release("minor"); }; target.major = function () { release("major"); }; <|start_filename|>tests/lib/rules/no-conditional-require.js<|end_filename|> /** * @file Tests for `no-conditional-require` rule * @author <NAME> <<EMAIL>> */ "use strict"; const testRule = require("../../rule-tester"); const fixtures = require("../../fixtures"); const rule = require("../../../lib/rules/no-conditional-require"); // ----------------------------------------------------------------------------- // Tests // ----------------------------------------------------------------------------- const ERROR = { message: "Conditional `require` calls are not allowed.", type: "CallExpression" }; testRule("no-conditional-require", rule, { valid: [ fixtures.AMD_REQUIRE, fixtures.AMD_REQUIRE_RELATIVE, fixtures.AMD_EMPTY_REQUIRE, fixtures.AMD_REQUIRE_WITH_ERRBACK, fixtures.AMD_REQUIREJS, fixtures.AMD_REQUIREJS_RELATIVE, fixtures.AMD_EMPTY_REQUIREJS, fixtures.AMD_REQUIREJS_WITH_ERRBACK, fixtures.NESTED_AMD_REQUIRE, fixtures.NESTED_AMD_REQUIREJS, fixtures.NESTED_AMD_REQUIRE_NO_CALLBACK, fixtures.NESTED_AMD_REQUIREJS_NO_CALLBACK, fixtures.CJS_WITH_RETURN, fixtures.CJS_WITH_EXPORTS, fixtures.CJS_WITH_MODULE_EXPORTS, fixtures.NAMED_CJS_DEFINE, fixtures.DYNAMIC_MIXED_AMD_REQUIRE, fixtures.DYNAMIC_TERNARY_AMD_REQUIRE, fixtures.DYNAMIC_VARIABLE_AMD_REQUIRE, fixtures.DYNAMIC_TERNARY_CJS_REQUIRE, fixtures.DYNAMIC_VARIABLE_CJS_REQUIRE, fixtures.DYNAMIC_AMD_REQUIRE_WITH_ERRBACK, fixtures.DYNAMIC_MIXED_AMD_REQUIREJS, fixtures.DYNAMIC_TERNARY_AMD_REQUIREJS, fixtures.DYNAMIC_VARIABLE_AMD_REQUIREJS, fixtures.DYNAMIC_TERNARY_CJS_REQUIREJS, fixtures.DYNAMIC_VARIABLE_CJS_REQUIREJS, fixtures.DYNAMIC_AMD_REQUIREJS_WITH_ERRBACK ], invalid: [ { code: fixtures.CONDITIONAL_AMD_REQUIRE, errors: [ERROR] }, { code: fixtures.CONDITIONAL_CJS_REQUIRE, errors: [ERROR] }, { code: fixtures.CONDITIONAL_TERNARY_CJS_REQUIRE, errors: [ERROR, ERROR] }, { code: fixtures.CONDITIONAL_NESTED_AMD_REQUIRE, errors: [ERROR] }, { code: fixtures.CONDITIONAL_AMD_REQUIREJS, errors: [ERROR] }, { code: fixtures.CONDITIONAL_CJS_REQUIREJS, errors: [ERROR] }, { code: fixtures.CONDITIONAL_TERNARY_CJS_REQUIREJS, errors: [ERROR, ERROR] }, { code: fixtures.CONDITIONAL_NESTED_AMD_REQUIREJS, errors: [ERROR] } ] }); <|start_filename|>tests/lib/rules/no-js-extension.js<|end_filename|> /** * @file Tests for `no-js-extension` rule * @author <NAME> <<EMAIL>> */ "use strict"; const testRule = require("../../rule-tester"); const fixtures = require("../../fixtures"); const rule = require("../../../lib/rules/no-js-extension"); // ----------------------------------------------------------------------------- // Fixtures // ----------------------------------------------------------------------------- const NON_REQUIREJS_DEFINE_WITH_JS_EXT = ` module([ 'aaa.js' ], function () { /* ... */ }); `; // ----------------------------------------------------------------------------- // Tests // ----------------------------------------------------------------------------- const ERROR = { message: "Don't use .js extension in dependency path.", type: "Literal" }; testRule("no-js-extension", rule, { valid: [ fixtures.BAD_REQUIRE_EMPTY, fixtures.AMD_DEFINE, fixtures.AMD_EMPTY_DEFINE, fixtures.AMD_EMPTY_REQUIRE, fixtures.AMD_EMPTY_REQUIREJS, fixtures.AMD_REQUIRE, fixtures.AMD_REQUIRE_RELATIVE, fixtures.AMD_REQUIRE_WITH_ERRBACK, fixtures.AMD_REQUIREJS, fixtures.AMD_REQUIREJS_RELATIVE, fixtures.AMD_REQUIREJS_WITH_ERRBACK, fixtures.CJS_WITH_EXPORTS, fixtures.CJS_WITH_MODULE_EXPORTS, fixtures.CJS_WITH_RETURN, fixtures.NAMED_AMD_DEFINE, fixtures.NAMED_AMD_EMPTY_DEFINE, fixtures.NAMED_CJS_DEFINE, fixtures.DYNAMIC_AMD_REQUIRE_WITH_ERRBACK, fixtures.DYNAMIC_AMD_REQUIREJS_WITH_ERRBACK, fixtures.DYNAMIC_MIXED_AMD_REQUIRE, fixtures.DYNAMIC_MIXED_AMD_REQUIREJS, fixtures.DYNAMIC_TERNARY_AMD_REQUIRE, fixtures.DYNAMIC_TERNARY_AMD_REQUIREJS, fixtures.DYNAMIC_TERNARY_CJS_REQUIRE, fixtures.DYNAMIC_TERNARY_CJS_REQUIREJS, fixtures.DYNAMIC_VARIABLE_AMD_REQUIRE, fixtures.DYNAMIC_VARIABLE_AMD_REQUIREJS, fixtures.DYNAMIC_VARIABLE_CJS_REQUIRE, fixtures.DYNAMIC_VARIABLE_CJS_REQUIREJS, fixtures.CONDITIONAL_AMD_REQUIRE, fixtures.CONDITIONAL_AMD_REQUIREJS, fixtures.CONDITIONAL_CJS_REQUIRE, fixtures.CONDITIONAL_CJS_REQUIREJS, fixtures.CONDITIONAL_NESTED_AMD_REQUIRE, fixtures.CONDITIONAL_NESTED_AMD_REQUIREJS, fixtures.CONDITIONAL_TERNARY_CJS_REQUIRE, fixtures.CONDITIONAL_TERNARY_CJS_REQUIREJS, NON_REQUIREJS_DEFINE_WITH_JS_EXT, // plugins check fixtures.AMD_DEFINE_WITH_FOO_PLUGIN_AND_JS_EXT, fixtures.AMD_REQUIRE_WITH_FOO_PLUGIN_AND_JS_EXT, fixtures.AMD_REQUIREJS_WITH_FOO_PLUGIN_AND_JS_EXT, fixtures.CJS_WITH_FOO_PLUGIN_AND_JS_EXT ], invalid: [ { code: fixtures.AMD_REQUIRE_WITH_JS_EXT, errors: [ERROR] }, { code: fixtures.AMD_REQUIREJS_WITH_JS_EXT, errors: [ERROR] }, { code: fixtures.AMD_REQUIRE_RELATIVE_WITH_JS_EXT, errors: [ERROR] }, { code: fixtures.AMD_DEFINE_WITH_JS_EXT, errors: [ERROR] }, { code: fixtures.CJS_WITH_JS_EXT, errors: [ERROR] }, { code: fixtures.NAMED_AMD_DEFINE_WITH_JS_EXT, errors: [ERROR] }, { code: fixtures.NAMED_CJS_DEFINE_WITH_JS_EXT, errors: [ERROR] }, // one plugin check { code: fixtures.AMD_DEFINE_WITH_FOO_PLUGIN_AND_JS_EXT, options: [[ "foo" ]], errors: [ERROR] }, { code: fixtures.AMD_REQUIRE_WITH_FOO_PLUGIN_AND_JS_EXT, options: [[ "foo" ]], errors: [ERROR] }, { code: fixtures.AMD_REQUIREJS_WITH_FOO_PLUGIN_AND_JS_EXT, options: [[ "foo" ]], errors: [ERROR] }, { code: fixtures.CJS_WITH_FOO_PLUGIN_AND_JS_EXT, options: [[ "foo" ]], errors: [ERROR] }, // more plugins check { code: fixtures.AMD_DEFINE_WITH_FOO_PLUGIN_AND_JS_EXT, options: [[ "more", "plugins", "foo" ]], errors: [ERROR] }, { code: fixtures.AMD_REQUIRE_WITH_FOO_PLUGIN_AND_JS_EXT, options: [[ "more", "plugins", "foo" ]], errors: [ERROR] }, { code: fixtures.AMD_REQUIREJS_WITH_FOO_PLUGIN_AND_JS_EXT, options: [[ "more", "plugins", "foo" ]], errors: [ERROR] }, { code: fixtures.CJS_WITH_FOO_PLUGIN_AND_JS_EXT, options: [[ "more", "plugins", "foo" ]], errors: [ERROR] } ] }); <|start_filename|>tests/lib/rules/no-commonjs-wrapper.js<|end_filename|> /** * @file Tests for `no-commonjs-wrapper` rule * @author <NAME> <<EMAIL>> */ "use strict"; const testRule = require("../../rule-tester"); const fixtures = require("../../fixtures"); const rule = require("../../../lib/rules/no-commonjs-wrapper"); // ----------------------------------------------------------------------------- // Tests // ----------------------------------------------------------------------------- const ERROR = { message: "Simplified CommonJS Wrapper form of `define` is not allowed", type: "CallExpression" }; testRule("no-commonjs-wrapper", rule, { valid: [ fixtures.OBJECT_DEFINE, fixtures.FUNCTION_DEFINE, fixtures.AMD_DEFINE, fixtures.AMD_EMPTY_DEFINE, fixtures.NAMED_OBJECT_DEFINE, fixtures.NAMED_FUNCTION_DEFINE, fixtures.NAMED_AMD_DEFINE, fixtures.NAMED_AMD_EMPTY_DEFINE ], invalid: [ { code: fixtures.CJS_WITH_RETURN, errors: [ERROR] }, { code: fixtures.CJS_WITH_EXPORTS, errors: [ERROR] }, { code: fixtures.CJS_WITH_MODULE_EXPORTS, errors: [ERROR] }, { code: fixtures.NAMED_CJS_DEFINE, errors: [ERROR] } ] }); <|start_filename|>tests/lib/rules/no-named-define.js<|end_filename|> /** * @file Tests for `no-named-define` rule * @author <NAME> <<EMAIL>> */ "use strict"; const testRule = require("../../rule-tester"); const fixtures = require("../../fixtures"); const rule = require("../../../lib/rules/no-named-define"); // ----------------------------------------------------------------------------- // Tests // ----------------------------------------------------------------------------- const ERROR = { message: "Named module form of `define` is not allowed", type: "CallExpression" }; testRule("no-named-define", rule, { valid: [ fixtures.OBJECT_DEFINE, fixtures.FUNCTION_DEFINE, fixtures.CJS_WITH_RETURN, fixtures.CJS_WITH_EXPORTS, fixtures.CJS_WITH_MODULE_EXPORTS, fixtures.AMD_DEFINE, fixtures.AMD_EMPTY_DEFINE ], invalid: [ { code: fixtures.NAMED_OBJECT_DEFINE, errors: [ERROR] }, { code: fixtures.NAMED_FUNCTION_DEFINE, errors: [ERROR] }, { code: fixtures.NAMED_AMD_DEFINE, errors: [ERROR] }, { code: fixtures.NAMED_AMD_EMPTY_DEFINE, errors: [ERROR] }, { code: fixtures.NAMED_CJS_DEFINE, errors: [ERROR] } ] }); <|start_filename|>tests/lib/rules/sort-amd-paths.js<|end_filename|> /** * @file Tests for `sort-amd-paths` rule * @author <NAME> <<EMAIL>> */ "use strict"; const testRule = require("../../rule-tester"); const fixtures = require("../../fixtures"); const rule = require("../../../lib/rules/sort-amd-paths"); // ----------------------------------------------------------------------------- // Fixtures // ----------------------------------------------------------------------------- const BASENAME_CAPITAL = ` define([ 'aaa/bbb/Xxx', 'aaa/bbb/ccc/ddd' ], function (ccc, aaa) { /* ... */ }); `; const NO_PATH = ` define(function () { /* ... */ }); `; const ONE_PATH_IN_ARRAY = ` define([ 'foo/bar/baz' ], function (baz) { /* ... */ }); `; const MORE_PATHS_IN_ARRAY = ` define([ 'base.dt/js/DesignerUtils', 'components.dt/js/deleters/DeletersRegistry', 'core/js/api/Listenable', 'core/js/api/utils/KeyConstants', 'pages.dt/js/api/Pages', 'pages.dt/js/api/ViewGeneratorModes' ], function (aaa, ccc, ddd, bbb, yyy) { /* ... */ }); `; const FULLPATH_INVALID = ` define([ 'aaa/bbb/xxx', 'aaa/bbb/ccc/ddd' ], function (ccc, aaa) { /* ... */ }); `; const DIRNAME_WRONG_ORDER = ` define([ 'aaa/bbb/ccc/ddd/aaa', 'aaa/bbb/ccc/xxx' ], function (ccc, aaa) { /* ... */ }); `; const IGNORED_PATHS = ` define([ 'aaa/bbb/xxx', 'aaa/bbb/yyy', 'aaa/bbb/zzz', // following lines should be ignored 'aaa/bbb/aaa', 'aaa/bbb/bbb' ], function (xxx, yyy, zzz) { /* ... */ }); `; const SLASH_PUNC_VALID = ` define([ 'foo/bar/baz/Bat', 'foo-bar/baz/Bat', 'foo.bar/baz/Bat' ], function (bat1, bat2, bat3) { /* ... */ }); `; const PLUGIN_PRESERVE = ` define([ 'aaa/aaa/aaa', 'bbb!fff/fff/fff', 'ccc/ccc/ccc', 'ggg/ggg/ggg', 'hhh!ddd/ddd/ddd' ], function (aaa, fff, ccc, ggg, ddd) { /* ... */ }); `; const FULLPATH_VALID = ` define([ 'aaa/bbb/ccc/ddd', 'aaa/bbb/xxx' ], function (ccc, aaa) { /* ... */ }); `; const BASENAME_VALID_ORDER = ` define([ 'xxx/aaa', 'aaa/xxx' ], function (ccc, aaa) { /* ... */ }); `; const BASENAME_PLUGIN_PRESERVE_IGNORE = ` define([ 'awhat/ever1/aaa', 'cwhat/ever3/ccc', 'hhh!dwhat/ever5/ddd', 'bbb!fwhat/ever2/fff', 'gwhat/ever4/ggg' ], function (aaa, ccc, ddd, fff, ggg) { /* ... */ }); `; const PLUGIN_IGNORE = ` define([ 'aaa/aaa/aaa', 'ccc/ccc/ccc', 'bbb!fff/fff/fff1', 'bbb!fff/fff/fff2', 'ggg/ggg/ggg' ], function (aaa, ccc, fff1, fff2, ggg) { /* ... */ }); `; const PLUGIN_FIRST = ` define([ 'bbb!fff/fff/fff1', 'bbb!fff/fff/fff2', 'aaa/aaa/aaa', 'ccc/ccc/ccc', 'ggg/ggg/ggg' ], function (fff1, fff2, aaa, ccc, ggg) { /* ... */ }); `; const BASENAME_PLUGIN_FIRST = ` define([ 'hhh!dwhat/ever5/ddd', 'bbb!fwhat/ever2/fff', 'awhat/ever1/aaa', 'cwhat/ever3/ccc', 'gwhat/ever4/ggg' ], function (ddd, fff, aaa, ccc, ggg) { /* ... */ }); `; const PLUGIN_LAST = ` define([ 'aaa/aaa/aaa', 'ccc/ccc/ccc', 'ggg/ggg/ggg', 'bbb!fff/fff/fff1', 'bbb!fff/fff/fff2' ], function (aaa, ccc, ggg, fff1, fff2) { /* ... */ }); `; const BASENAME_PLUGIN_LAST = ` define([ 'awhat/ever1/aaa', 'cwhat/ever3/ccc', 'gwhat/ever4/ggg', 'hhh!dwhat/ever5/ddd', 'bbb!fwhat/ever2/fff' ], function (aaa, ccc, ggg, ddd, fff) { /* ... */ }); `; const INVALID_ORDER = ` define([ 'aaa/bbb/ccc', 'aaa/bbb/Aaa' ], function (ccc, aaa) { /* ... */ }); `; const SLASH_PUNC_INVALID = ` define([ 'foo.bar/baz/Bat', 'foo/bar/baz/Bat', 'foo-bar/baz/Bat' ], function (bat1, bat2, bat3) { /* ... */ }); `; const FIRST_LONGER_INVALID = ` define([ 'foo/bar/baz/Batttt', 'foo/bar/baz/Bat' ], function (bat1, bat2) { /* ... */ }); `; const BASENAME_INVALID_ORDER = ` define([ 'aaa/xxx', 'xxx/aaa' ], function (ccc, aaa) { /* ... */ }); `; const BASENAME_IDENTICAL = ` define([ 'aaa/xxx', 'bbb/xxx', 'ccc/xxx' ], function (ccc, aaa) { /* ... */ }); `; // ----------------------------------------------------------------------------- // Tests // ----------------------------------------------------------------------------- const errorMsg = (expected) => ({ message: `Required paths are not in alphabetical order (expected '${expected}').`, type: "Literal" }); testRule("sort-amd-paths", rule, { valid: [ fixtures.AMD_EMPTY_DEFINE, NO_PATH, ONE_PATH_IN_ARRAY, MORE_PATHS_IN_ARRAY, BASENAME_CAPITAL, FULLPATH_INVALID, IGNORED_PATHS, SLASH_PUNC_VALID, PLUGIN_PRESERVE, { code: fixtures.AMD_EMPTY_DEFINE, options: [{ compare: "dirname-basename" }] }, { code: NO_PATH, options: [{ compare: "dirname-basename" }] }, { code: ONE_PATH_IN_ARRAY, options: [{ compare: "dirname-basename" }] }, { code: MORE_PATHS_IN_ARRAY, options: [{ compare: "dirname-basename" }] }, { code: BASENAME_CAPITAL, options: [{ compare: "dirname-basename" }] }, { code: FULLPATH_INVALID, options: [{ compare: "dirname-basename" }] }, { code: PLUGIN_PRESERVE, options: [{ compare: "dirname-basename" }] }, { code: fixtures.AMD_EMPTY_DEFINE, options: [{ compare: "dirname-basename", ignoreCase: true }] }, { code: NO_PATH, options: [{ compare: "dirname-basename", ignoreCase: true }] }, { code: ONE_PATH_IN_ARRAY, options: [{ compare: "dirname-basename", ignoreCase: true }] }, { code: MORE_PATHS_IN_ARRAY, options: [{ compare: "dirname-basename", ignoreCase: true }] }, { code: BASENAME_CAPITAL, options: [{ compare: "dirname-basename", ignoreCase: true }] }, { code: FULLPATH_INVALID, options: [{ compare: "dirname-basename", ignoreCase: true }] }, { code: PLUGIN_PRESERVE, options: [{ compare: "dirname-basename", ignoreCase: true }] }, { code: fixtures.AMD_EMPTY_DEFINE, options: [{ compare: "dirname-basename", ignoreCase: false }] }, { code: NO_PATH, options: [{ compare: "dirname-basename", ignoreCase: false }] }, { code: ONE_PATH_IN_ARRAY, options: [{ compare: "dirname-basename", ignoreCase: false }] }, { code: BASENAME_CAPITAL, options: [{ compare: "dirname-basename", ignoreCase: false }] }, { code: FULLPATH_INVALID, options: [{ compare: "dirname-basename", ignoreCase: false }] }, { code: FULLPATH_VALID, options: [{ compare: "fullpath" }] }, { code: FULLPATH_VALID, options: [{ compare: "fullpath", ignoreCase: true }] }, { code: BASENAME_CAPITAL, options: [{ compare: "fullpath", ignoreCase: false }] }, { code: FULLPATH_VALID, options: [{ compare: "fullpath", ignoreCase: false }] }, { code: BASENAME_VALID_ORDER, options: [{ compare: "basename" }] }, { code: BASENAME_IDENTICAL, options: [{ compare: "basename" }] }, { code: BASENAME_VALID_ORDER, options: [{ compare: "basename", ignoreCase: true }] }, { code: BASENAME_VALID_ORDER, options: [{ compare: "basename", ignoreCase: false }] }, { code: BASENAME_CAPITAL, options: [{ compare: "basename", ignoreCase: false }] }, { code: PLUGIN_PRESERVE, options: [{ compare: "dirname-basename", sortPlugins: "preserve" }] }, { code: PLUGIN_PRESERVE, options: [{ compare: "fullpath", sortPlugins: "preserve" }] }, { code: BASENAME_PLUGIN_PRESERVE_IGNORE, options: [{ compare: "basename", sortPlugins: "preserve" }] }, { code: PLUGIN_IGNORE, options: [{ compare: "dirname-basename", sortPlugins: "ignore" }] }, { code: PLUGIN_IGNORE, options: [{ compare: "fullpath", sortPlugins: "ignore" }] }, { code: BASENAME_PLUGIN_PRESERVE_IGNORE, options: [{ compare: "basename", sortPlugins: "ignore" }] }, { code: PLUGIN_FIRST, options: [{ compare: "dirname-basename", sortPlugins: "first" }] }, { code: PLUGIN_FIRST, options: [{ compare: "fullpath", sortPlugins: "first" }] }, { code: BASENAME_PLUGIN_FIRST, options: [{ compare: "basename", sortPlugins: "first" }] }, { code: PLUGIN_LAST, options: [{ compare: "dirname-basename", sortPlugins: "last" }] }, { code: PLUGIN_LAST, options: [{ compare: "fullpath", sortPlugins: "last" }] }, { code: BASENAME_PLUGIN_LAST, options: [{ compare: "basename", sortPlugins: "last" }] }, fixtures.AMD_REQUIRE, fixtures.AMD_REQUIREJS, fixtures.CJS_WITH_RETURN, fixtures.CJS_WITH_EXPORTS, fixtures.CJS_WITH_MODULE_EXPORTS, fixtures.CJS_WITH_FUNC_EXPR, fixtures.CJS_WITH_INVALID_EXPORTS, fixtures.DYNAMIC_AMD_REQUIRE_WITH_ERRBACK, fixtures.DYNAMIC_AMD_REQUIREJS_WITH_ERRBACK ], invalid: [ { code: INVALID_ORDER, errors: [errorMsg("aaa/bbb/Aaa")] }, { code: SLASH_PUNC_INVALID, errors: [errorMsg("foo/bar/baz/Bat")] }, { code: FIRST_LONGER_INVALID, errors: [errorMsg("foo/bar/baz/Bat")] }, { code: PLUGIN_IGNORE, errors: [errorMsg("bbb!fff/fff/fff1")] }, { code: PLUGIN_FIRST, errors: [errorMsg("aaa/aaa/aaa")] }, { code: PLUGIN_LAST, errors: [errorMsg("bbb!fff/fff/fff1")] }, { code: INVALID_ORDER, options: [{ compare: "dirname-basename" }], errors: [errorMsg("aaa/bbb/Aaa")] }, { code: DIRNAME_WRONG_ORDER, options: [{ compare: "dirname-basename" }], errors: [errorMsg("aaa/bbb/ccc/xxx")] }, { code: INVALID_ORDER, options: [{ compare: "dirname-basename", ignoreCase: true }], errors: [errorMsg("aaa/bbb/Aaa")] }, { code: INVALID_ORDER, options: [{ compare: "dirname-basename", ignoreCase: false }], errors: [errorMsg("aaa/bbb/Aaa")] }, { code: FULLPATH_INVALID, options: [{ compare: "fullpath" }], errors: [errorMsg("aaa/bbb/ccc/ddd")] }, { code: BASENAME_CAPITAL, options: [{ compare: "fullpath" }], errors: [errorMsg("aaa/bbb/ccc/ddd")] }, { code: FULLPATH_INVALID, options: [{ compare: "fullpath", ignoreCase: true }], errors: [errorMsg("aaa/bbb/ccc/ddd")] }, { code: BASENAME_CAPITAL, options: [{ compare: "fullpath", ignoreCase: true }], errors: [errorMsg("aaa/bbb/ccc/ddd")] }, { code: FULLPATH_INVALID, options: [{ compare: "fullpath", ignoreCase: false }], errors: [errorMsg("aaa/bbb/ccc/ddd")] }, { code: INVALID_ORDER, options: [{ compare: "fullpath", ignoreCase: false }], errors: [errorMsg("aaa/bbb/Aaa")] }, { code: BASENAME_INVALID_ORDER, errors: [errorMsg("xxx/aaa")], options: [{ compare: "basename" }] }, { code: BASENAME_INVALID_ORDER, errors: [errorMsg("xxx/aaa")], options: [{ compare: "basename", ignoreCase: true }] }, { code: BASENAME_INVALID_ORDER, errors: [errorMsg("xxx/aaa")], options: [{ compare: "basename", ignoreCase: false }] }, { code: INVALID_ORDER, options: [{ compare: "basename", ignoreCase: false }], errors: [errorMsg("aaa/bbb/Aaa")] }, { code: PLUGIN_IGNORE, options: [{ compare: "dirname-basename", sortPlugins: "preserve" }], errors: [errorMsg("bbb!fff/fff/fff1")] }, { code: PLUGIN_FIRST, options: [{ compare: "dirname-basename", sortPlugins: "preserve" }], errors: [errorMsg("aaa/aaa/aaa")] }, { code: PLUGIN_LAST, options: [{ compare: "dirname-basename", sortPlugins: "preserve" }], errors: [errorMsg("bbb!fff/fff/fff1")] }, { code: PLUGIN_IGNORE, options: [{ compare: "fullpath", sortPlugins: "preserve" }], errors: [errorMsg("bbb!fff/fff/fff1")] }, { code: PLUGIN_FIRST, options: [{ compare: "fullpath", sortPlugins: "preserve" }], errors: [errorMsg("aaa/aaa/aaa")] }, { code: PLUGIN_LAST, options: [{ compare: "fullpath", sortPlugins: "preserve" }], errors: [errorMsg("bbb!fff/fff/fff1")] }, { code: BASENAME_PLUGIN_FIRST, options: [{ compare: "basename", sortPlugins: "preserve" }], errors: [errorMsg("awhat/ever1/aaa")] }, { code: BASENAME_PLUGIN_LAST, options: [{ compare: "basename", sortPlugins: "preserve" }], errors: [errorMsg("hhh!dwhat/ever5/ddd")] }, { code: PLUGIN_PRESERVE, options: [{ compare: "dirname-basename", sortPlugins: "ignore" }], errors: [errorMsg("ccc/ccc/ccc")] }, { code: PLUGIN_FIRST, options: [{ compare: "dirname-basename", sortPlugins: "ignore" }], errors: [errorMsg("aaa/aaa/aaa")] }, { code: PLUGIN_LAST, options: [{ compare: "dirname-basename", sortPlugins: "ignore" }], errors: [errorMsg("bbb!fff/fff/fff1")] }, { code: PLUGIN_PRESERVE, options: [{ compare: "fullpath", sortPlugins: "ignore" }], errors: [errorMsg("ccc/ccc/ccc")] }, { code: PLUGIN_FIRST, options: [{ compare: "fullpath", sortPlugins: "ignore" }], errors: [errorMsg("aaa/aaa/aaa")] }, { code: PLUGIN_LAST, options: [{ compare: "fullpath", sortPlugins: "ignore" }], errors: [errorMsg("bbb!fff/fff/fff1")] }, { code: BASENAME_PLUGIN_FIRST, options: [{ compare: "basename", sortPlugins: "ignore" }], errors: [errorMsg("awhat/ever1/aaa")] }, { code: BASENAME_PLUGIN_LAST, options: [{ compare: "basename", sortPlugins: "ignore" }], errors: [errorMsg("hhh!dwhat/ever5/ddd")] }, { code: PLUGIN_PRESERVE, options: [{ compare: "dirname-basename", sortPlugins: "first" }], errors: [errorMsg("bbb!fff/fff/fff")] }, { code: PLUGIN_IGNORE, options: [{ compare: "dirname-basename", sortPlugins: "first" }], errors: [errorMsg("bbb!fff/fff/fff1")] }, { code: PLUGIN_LAST, options: [{ compare: "dirname-basename", sortPlugins: "first" }], errors: [errorMsg("bbb!fff/fff/fff1")] }, { code: PLUGIN_PRESERVE, options: [{ compare: "fullpath", sortPlugins: "first" }], errors: [errorMsg("bbb!fff/fff/fff")] }, { code: PLUGIN_IGNORE, options: [{ compare: "fullpath", sortPlugins: "first" }], errors: [errorMsg("bbb!fff/fff/fff1")] }, { code: PLUGIN_LAST, options: [{ compare: "fullpath", sortPlugins: "first" }], errors: [errorMsg("bbb!fff/fff/fff1")] }, { code: BASENAME_PLUGIN_PRESERVE_IGNORE, options: [{ compare: "basename", sortPlugins: "first" }], errors: [errorMsg("hhh!dwhat/ever5/ddd")] }, { code: BASENAME_PLUGIN_LAST, options: [{ compare: "basename", sortPlugins: "first" }], errors: [errorMsg("hhh!dwhat/ever5/ddd")] }, { code: PLUGIN_PRESERVE, options: [{ compare: "dirname-basename", sortPlugins: "last" }], errors: [errorMsg("ccc/ccc/ccc")] }, { code: PLUGIN_IGNORE, options: [{ compare: "dirname-basename", sortPlugins: "last" }], errors: [errorMsg("ggg/ggg/ggg")] }, { code: PLUGIN_FIRST, options: [{ compare: "dirname-basename", sortPlugins: "last" }], errors: [errorMsg("aaa/aaa/aaa")] }, { code: PLUGIN_PRESERVE, options: [{ compare: "fullpath", sortPlugins: "last" }], errors: [errorMsg("ccc/ccc/ccc")] }, { code: PLUGIN_IGNORE, options: [{ compare: "fullpath", sortPlugins: "last" }], errors: [errorMsg("ggg/ggg/ggg")] }, { code: PLUGIN_FIRST, options: [{ compare: "fullpath", sortPlugins: "last" }], errors: [errorMsg("aaa/aaa/aaa")] }, { code: BASENAME_PLUGIN_PRESERVE_IGNORE, options: [{ compare: "basename", sortPlugins: "last" }], errors: [errorMsg("gwhat/ever4/ggg")] }, { code: BASENAME_PLUGIN_FIRST, options: [{ compare: "basename", sortPlugins: "last" }], errors: [errorMsg("awhat/ever1/aaa")] } ] }); <|start_filename|>lib/rules/no-js-extension.js<|end_filename|> /** * @file Rule to disallow `.js` extension in dependency paths * @author <NAME> <<EMAIL>> */ "use strict"; const rjs = require("../utils/rjs"); const isAmdCall = rjs.isAmdCall; const getDependencyStringNodes = rjs.getDependencyStringNodes; // ----------------------------------------------------------------------------- // Configuration // ----------------------------------------------------------------------------- const docs = { description: "Disallow `.js` extension in dependency paths", category: "Possible Errors", recommended: true, url: "https://github.com/cvisco/eslint-plugin-requirejs/blob/master/docs/rules/no-js-extension.md" }; const schema = [ { type: "array", uniqueItems: true, items: { type: "string" } } ]; const message = "Don't use .js extension in dependency path."; // ----------------------------------------------------------------------------- // Helpers // ----------------------------------------------------------------------------- const append = (str) => (val) => val + str; const report = (context) => (node) => context.report(node, message); const hasJsExtension = (node) => node.value.trim().endsWith(".js"); const startsWithOneOf = (list, str) => list.some((val) => str.startsWith(val)); const hasNoPlugin = (str) => !str.includes("!"); const shouldBeChecked = (plugins) => (node) => startsWithOneOf(plugins, node.value) || hasNoPlugin(node.value); // ----------------------------------------------------------------------------- // Rule Definition // ----------------------------------------------------------------------------- function create(context) { const plugins = (context.options[0] || []).map(append("!")); return { CallExpression(node) { if (!isAmdCall(node)) return; getDependencyStringNodes(node) .filter(shouldBeChecked(plugins)) .filter(hasJsExtension) .forEach(report(context)); } }; } module.exports = { meta: { docs, schema }, create };
nagesh4193/eslint-plugin-requirejs
<|start_filename|>src/gromacs/applied_forces/awh/biassharing.cpp<|end_filename|> /* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2017,2018,2019,2020,2021, by the GROMACS development team, led by * <NAME>, <NAME>, <NAME>, and <NAME>, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS 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. * * GROMACS 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 GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ /*! \internal \file * \brief * Implements bias sharing checking functionality. * * \author <NAME> <<EMAIL>> * \ingroup module_awh */ #include "gmxpre.h" #include "biassharing.h" #include "config.h" #include <algorithm> #include <set> #include <vector> #include "gromacs/gmxlib/network.h" #include "gromacs/mdrunutility/multisim.h" #include "gromacs/mdtypes/awh_params.h" #include "gromacs/mdtypes/commrec.h" #include "gromacs/utility/arrayref.h" #include "gromacs/utility/exceptions.h" #include "gromacs/utility/gmxassert.h" #include "gromacs/utility/stringutil.h" namespace gmx { namespace { //! Determines and returns which of the local biases are shared with who how many other simulations std::multiset<int> getGlobalShareIndices(ArrayRef<const int> localShareIndices, MPI_Comm simulationMastersComm) { #if GMX_MPI int numSimulations; MPI_Comm_size(simulationMastersComm, &numSimulations); int ourRank; MPI_Comm_rank(simulationMastersComm, &ourRank); std::vector<int> biasCountsIn(numSimulations, 0); std::vector<int> biasCounts(numSimulations, 0); biasCountsIn[ourRank] = localShareIndices.size(); MPI_Allreduce(biasCountsIn.data(), biasCounts.data(), numSimulations, MPI_INT, MPI_SUM, simulationMastersComm); // Now we need to gather the share indices to all (master) ranks. // We could use MPI_Allgatherv, but thread-MPI does not support that and using // MPI_Allreduce produces simpler code, so we use that. int totNumBiases = 0; int ourOffset = 0; for (int rank = 0; rank < numSimulations; rank++) { if (rank == ourRank) { ourOffset = totNumBiases; } totNumBiases += biasCounts[rank]; } // Fill a buffer with zeros and our part of sharing indices std::vector<int> shareIndicesAllIn(totNumBiases, 0); std::copy(localShareIndices.begin(), localShareIndices.end(), shareIndicesAllIn.begin() + ourOffset); // Gather all sharing indices to all (master) ranks std::vector<int> shareIndicesAll(totNumBiases); MPI_Allreduce(shareIndicesAllIn.data(), shareIndicesAll.data(), totNumBiases, MPI_INT, MPI_SUM, simulationMastersComm); #else GMX_UNUSED_VALUE(simulationMastersComm); ArrayRef<const int> shareIndicesAll = localShareIndices; #endif // GMX_MPI std::multiset<int> shareIndicesSet; for (int shareIndex : shareIndicesAll) { if (shareIndex > 0) { shareIndicesSet.insert(shareIndex); } } return shareIndicesSet; } } // namespace BiasSharing::BiasSharing(const AwhParams& awhParams, const t_commrec& commRecord, MPI_Comm simulationMastersComm) : commRecord_(commRecord) { if (MASTER(&commRecord)) { std::vector<int> localShareIndices; int shareGroupPrev = 0; for (int k = 0; k < awhParams.numBias(); k++) { const int shareGroup = awhParams.awhBiasParams()[k].shareGroup(); GMX_RELEASE_ASSERT(shareGroup >= 0, "Bias share group values should be >= 0"); localShareIndices.push_back(shareGroup); if (shareGroup > 0) { if (shareGroup <= shareGroupPrev) { GMX_THROW( InvalidInputError("AWH biases that are shared should use increasing " "share-group values")); } shareGroupPrev = shareGroup; } } std::multiset<int> globalShareIndices = getGlobalShareIndices(localShareIndices, simulationMastersComm); int numSimulations = 1; #if GMX_MPI MPI_Comm_size(simulationMastersComm, &numSimulations); int myRank; MPI_Comm_rank(simulationMastersComm, &myRank); #endif // GMX_MPI numSharingSimulations_.resize(awhParams.numBias(), 1); sharingSimulationIndices_.resize(awhParams.numBias(), 0); multiSimCommPerBias_.resize(awhParams.numBias(), MPI_COMM_NULL); for (int shareIndex : globalShareIndices) { if (globalShareIndices.count(shareIndex) > 1) { const auto& findBiasIndex = std::find(localShareIndices.begin(), localShareIndices.end(), shareIndex); const index localBiasIndex = (findBiasIndex == localShareIndices.end() ? -1 : findBiasIndex - localShareIndices.begin()); MPI_Comm splitComm; if (static_cast<int>(globalShareIndices.count(shareIndex)) == numSimulations) { splitComm = simulationMastersComm; } else { #if GMX_MPI const int haveLocally = (localBiasIndex >= 0 ? 1 : 0); MPI_Comm_split(simulationMastersComm, haveLocally, myRank, &splitComm); createdCommList_.push_back(splitComm); #else GMX_RELEASE_ASSERT(false, "Can not have sharing without MPI"); #endif // GMX_MPI } if (localBiasIndex >= 0) { numSharingSimulations_[localBiasIndex] = globalShareIndices.count(shareIndex); #if GMX_MPI MPI_Comm_rank(splitComm, &sharingSimulationIndices_[localBiasIndex]); #endif // GMX_MPI multiSimCommPerBias_[localBiasIndex] = splitComm; } } } } #if GMX_MPI if (commRecord.nnodes > 1) { numSharingSimulations_.resize(awhParams.numBias()); MPI_Bcast( numSharingSimulations_.data(), numSharingSimulations_.size(), MPI_INT, 0, commRecord.mpi_comm_mygroup); } #endif // GMX_MPI } BiasSharing::~BiasSharing() { #if GMX_MPI for (MPI_Comm comm : createdCommList_) { MPI_Comm_free(&comm); } #endif // GMX_MPI } namespace { #if GMX_MPI template<typename T> std::enable_if_t<std::is_same_v<T, int>, MPI_Datatype> mpiType() { return MPI_INT; } template<typename T> std::enable_if_t<std::is_same_v<T, long>, MPI_Datatype> mpiType() { return MPI_LONG; } template<typename T> std::enable_if_t<std::is_same_v<T, double>, MPI_Datatype> mpiType() { return MPI_DOUBLE; } #endif // GMX_MPI } // namespace /*! \brief * Sum an array over all simulations on master ranks or all ranks of each simulation. * * This assumes the data is identical on all ranks within each simulation. * * \param[in,out] data The data to sum. * \param[in] multiSimComm Communicator for the master ranks of sharing simulations. * \param[in] broadcastWithinSimulation Broadcast the result to all ranks within the simulation * \param[in] commRecord Struct for intra-simulation communication. */ template<typename T> void sumOverSimulations(ArrayRef<T> data, MPI_Comm multiSimComm, const bool broadcastWithinSimulation, const t_commrec& commRecord) { #if GMX_MPI if (MASTER(&commRecord)) { MPI_Allreduce(MPI_IN_PLACE, data.data(), data.size(), mpiType<T>(), MPI_SUM, multiSimComm); } if (broadcastWithinSimulation && commRecord.nnodes > 1) { gmx_bcast(data.size() * sizeof(T), data.data(), commRecord.mpi_comm_mygroup); } #else GMX_UNUSED_VALUE(data); GMX_UNUSED_VALUE(commRecord); GMX_UNUSED_VALUE(broadcastWithinSimulation); GMX_UNUSED_VALUE(multiSimComm); #endif // GMX_MPI } void BiasSharing::sumOverMasterRanks(ArrayRef<int> data, const int biasIndex) const { sumOverSimulations(data, multiSimCommPerBias_[biasIndex], false, commRecord_); } void BiasSharing::sumOverMasterRanks(ArrayRef<long> data, const int biasIndex) const { sumOverSimulations(data, multiSimCommPerBias_[biasIndex], false, commRecord_); } void BiasSharing::sum(ArrayRef<int> data, const int biasIndex) const { sumOverSimulations(data, multiSimCommPerBias_[biasIndex], true, commRecord_); } void BiasSharing::sum(ArrayRef<double> data, const int biasIndex) const { sumOverSimulations(data, multiSimCommPerBias_[biasIndex], true, commRecord_); } bool haveBiasSharingWithinSimulation(const AwhParams& awhParams) { bool haveSharing = false; for (int k = 0; k < awhParams.numBias(); k++) { int shareGroup = awhParams.awhBiasParams()[k].shareGroup(); if (shareGroup > 0) { for (int i = k + 1; i < awhParams.numBias(); i++) { if (awhParams.awhBiasParams()[i].shareGroup() == shareGroup) { haveSharing = true; } } } } return haveSharing; } void biasesAreCompatibleForSharingBetweenSimulations(const AwhParams& awhParams, ArrayRef<const size_t> pointSize, const BiasSharing& biasSharing) { /* Check the point sizes. This is a sufficient condition for running * as shared multi-sim run. No physics checks are performed here. */ const auto& awhBiasParams = awhParams.awhBiasParams(); for (int b = 0; b < gmx::ssize(awhBiasParams); b++) { if (awhBiasParams[b].shareGroup() > 0) { const int numSim = biasSharing.numSharingSimulations(b); if (numSim == 1) { // This bias is not actually shared continue; } const int simIndex = biasSharing.sharingSimulationIndex(b); std::vector<int> intervals(numSim * 2); intervals[numSim * 0 + simIndex] = awhParams.nstSampleCoord(); intervals[numSim * 1 + simIndex] = awhParams.numSamplesUpdateFreeEnergy(); biasSharing.sumOverMasterRanks(intervals, b); for (int sim = 1; sim < numSim; sim++) { if (intervals[sim] != intervals[0]) { GMX_THROW(InvalidInputError( "All simulations should have the same AWH sample interval")); } if (intervals[numSim + sim] != intervals[numSim]) { GMX_THROW( InvalidInputError("All simulations should have the same AWH " "free-energy update interval")); } } std::vector<long> pointSizes(numSim); pointSizes[simIndex] = pointSize[b]; biasSharing.sumOverMasterRanks(pointSizes, b); for (int sim = 1; sim < numSim; sim++) { if (pointSizes[sim] != pointSizes[0]) { GMX_THROW(InvalidInputError( gmx::formatString("Shared AWH bias %d has different grid sizes in " "different simulations\n", b + 1))); } } } } } } // namespace gmx <|start_filename|>src/gromacs/mdrunutility/tests/threadaffinity_mpi.cpp<|end_filename|> /* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2016,2017,2019,2020, by the GROMACS development team, led by * <NAME>, <NAME>, <NAME>, and <NAME>, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS 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. * * GROMACS 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 GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ #include "gmxpre.h" #include <array> #include <gtest/gtest.h> #include "gromacs/utility/basenetwork.h" #include "testutils/mpitest.h" #include "threadaffinitytest.h" namespace { using gmx::test::ThreadAffinityTestHelper; TEST(ThreadAffinityMultiRankTest, PinsWholeNode) { GMX_MPI_TEST(4); ThreadAffinityTestHelper helper; helper.setLogicalProcessorCount(4); helper.expectPinningMessage(false, 1); helper.expectAffinitySet(gmx_node_rank()); helper.setAffinity(1); } TEST(ThreadAffinityMultiRankTest, PinsWithOffsetAndStride) { GMX_MPI_TEST(4); ThreadAffinityTestHelper helper; helper.setAffinityOption(ThreadAffinity::On); helper.setOffsetAndStride(1, 2); helper.setLogicalProcessorCount(8); helper.expectWarningMatchingRegex("Applying core pinning offset 1"); helper.expectPinningMessage(true, 2); helper.expectAffinitySet(1 + 2 * gmx_node_rank()); helper.setAffinity(1); } TEST(ThreadAffinityMultiRankTest, PinsTwoNodes) { GMX_MPI_TEST(4); ThreadAffinityTestHelper helper; helper.setPhysicalNodeId(gmx_node_rank() / 2); helper.setLogicalProcessorCount(2); helper.expectPinningMessage(false, 1); helper.expectAffinitySet(gmx_node_rank() % 2); helper.setAffinity(1); } TEST(ThreadAffinityMultiRankTest, DoesNothingWhenDisabled) { GMX_MPI_TEST(4); ThreadAffinityTestHelper helper; helper.setAffinityOption(ThreadAffinity::Off); helper.setLogicalProcessorCount(4); helper.setAffinity(1); } TEST(ThreadAffinityMultiRankTest, HandlesTooManyThreadsWithAuto) { GMX_MPI_TEST(4); ThreadAffinityTestHelper helper; helper.setLogicalProcessorCount(6); helper.expectWarningMatchingRegex("Oversubscribing the CPU"); helper.setAffinity(2); } TEST(ThreadAffinityMultiRankTest, HandlesTooManyThreadsWithForce) { GMX_MPI_TEST(4); ThreadAffinityTestHelper helper; helper.setAffinityOption(ThreadAffinity::On); helper.setLogicalProcessorCount(6); helper.expectWarningMatchingRegex("Oversubscribing the CPU"); helper.setAffinity(2); } class ThreadAffinityHeterogeneousNodesTest : public ::testing::Test { public: static int currentNode() { return gmx_node_rank() / 2; } static int indexInNode() { return gmx_node_rank() % 2; } static bool isMaster() { return gmx_node_rank() == 0; } static void setupNodes(ThreadAffinityTestHelper* helper, std::array<int, 2> cores) { const int node = currentNode(); helper->setPhysicalNodeId(node); helper->setLogicalProcessorCount(cores[node]); } static void expectNodeAffinitySet(ThreadAffinityTestHelper* helper, int node, int core) { if (currentNode() == node) { helper->expectAffinitySet(core); } } }; TEST_F(ThreadAffinityHeterogeneousNodesTest, PinsOnMasterOnly) { GMX_MPI_TEST(4); ThreadAffinityTestHelper helper; helper.setAffinityOption(ThreadAffinity::On); setupNodes(&helper, { { 2, 1 } }); helper.expectWarningMatchingRegexIf("Oversubscribing the CPU", isMaster() || currentNode() == 1); if (currentNode() == 0) { helper.expectPinningMessage(false, 1); } expectNodeAffinitySet(&helper, 0, indexInNode()); helper.setAffinity(1); } TEST_F(ThreadAffinityHeterogeneousNodesTest, PinsOnNonMasterOnly) { GMX_MPI_TEST(4); ThreadAffinityTestHelper helper; helper.setAffinityOption(ThreadAffinity::On); setupNodes(&helper, { { 1, 2 } }); helper.expectWarningMatchingRegexIf("Oversubscribing the CPU", currentNode() == 0); if (currentNode() == 1) { helper.expectPinningMessage(false, 1); } expectNodeAffinitySet(&helper, 1, indexInNode()); helper.setAffinity(1); } TEST_F(ThreadAffinityHeterogeneousNodesTest, HandlesUnknownHardwareOnNonMaster) { GMX_MPI_TEST(4); ThreadAffinityTestHelper helper; helper.setAffinityOption(ThreadAffinity::On); setupNodes(&helper, { { 2, 0 } }); helper.expectWarningMatchingRegexIf("No information on available cores", isMaster() || currentNode() == 1); if (currentNode() == 0) { helper.expectPinningMessage(false, 1); } expectNodeAffinitySet(&helper, 0, indexInNode()); helper.setAffinity(1); } TEST_F(ThreadAffinityHeterogeneousNodesTest, PinsAutomaticallyOnMasterOnly) { GMX_MPI_TEST(4); ThreadAffinityTestHelper helper; setupNodes(&helper, { { 2, 1 } }); helper.expectWarningMatchingRegexIf("Oversubscribing the CPU", isMaster() || currentNode() == 1); if (currentNode() == 0) { helper.expectPinningMessage(false, 1); } expectNodeAffinitySet(&helper, 0, indexInNode()); helper.setAffinity(1); } TEST_F(ThreadAffinityHeterogeneousNodesTest, PinsAutomaticallyOnNonMasterOnly) { GMX_MPI_TEST(4); ThreadAffinityTestHelper helper; setupNodes(&helper, { { 1, 2 } }); helper.expectWarningMatchingRegexIf("Oversubscribing the CPU", currentNode() == 0); if (currentNode() == 1) { helper.expectPinningMessage(false, 1); } expectNodeAffinitySet(&helper, 1, indexInNode()); helper.setAffinity(1); } TEST_F(ThreadAffinityHeterogeneousNodesTest, HandlesInvalidOffsetOnNonMasterOnly) { GMX_MPI_TEST(4); ThreadAffinityTestHelper helper; helper.setAffinityOption(ThreadAffinity::On); helper.setOffsetAndStride(2, 0); setupNodes(&helper, { { 4, 2 } }); helper.expectWarningMatchingRegex("Applying core pinning offset 2"); helper.expectWarningMatchingRegexIf("Requested offset too large", isMaster() || currentNode() == 1); if (currentNode() == 0) { helper.expectPinningMessage(false, 1); } expectNodeAffinitySet(&helper, 0, indexInNode() + 2); helper.setAffinity(1); } TEST_F(ThreadAffinityHeterogeneousNodesTest, HandlesInvalidStrideOnNonMasterOnly) { GMX_MPI_TEST(4); ThreadAffinityTestHelper helper; helper.setAffinityOption(ThreadAffinity::On); helper.setOffsetAndStride(0, 2); setupNodes(&helper, { { 4, 2 } }); helper.expectWarningMatchingRegexIf("Requested stride too large", isMaster() || currentNode() == 1); if (currentNode() == 0) { helper.expectPinningMessage(true, 2); } expectNodeAffinitySet(&helper, 0, 2 * indexInNode()); helper.setAffinity(1); } } // namespace <|start_filename|>src/gromacs/mdrun/rerun.cpp<|end_filename|> /* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2018,2019,2020,2021, by the GROMACS development team, led by * <NAME>, <NAME>, <NAME>, and <NAME>, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS 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. * * GROMACS 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 GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ /*! \internal \file * * \brief Implements the loop for simulation reruns * * \author <NAME> <<EMAIL>> * \ingroup module_mdrun */ #include "gmxpre.h" #include <cinttypes> #include <cmath> #include <cstdio> #include <cstdlib> #include <algorithm> #include <memory> #include "gromacs/applied_forces/awh/awh.h" #include "gromacs/commandline/filenm.h" #include "gromacs/domdec/collect.h" #include "gromacs/domdec/dlbtiming.h" #include "gromacs/domdec/domdec.h" #include "gromacs/domdec/domdec_network.h" #include "gromacs/domdec/domdec_struct.h" #include "gromacs/domdec/localtopologychecker.h" #include "gromacs/domdec/mdsetup.h" #include "gromacs/domdec/partition.h" #include "gromacs/essentialdynamics/edsam.h" #include "gromacs/ewald/pme_load_balancing.h" #include "gromacs/ewald/pme_pp.h" #include "gromacs/fileio/trxio.h" #include "gromacs/gmxlib/network.h" #include "gromacs/gmxlib/nrnb.h" #include "gromacs/gpu_utils/gpu_utils.h" #include "gromacs/listed_forces/listed_forces.h" #include "gromacs/math/functions.h" #include "gromacs/math/utilities.h" #include "gromacs/math/vec.h" #include "gromacs/math/vectypes.h" #include "gromacs/mdlib/checkpointhandler.h" #include "gromacs/mdlib/compute_io.h" #include "gromacs/mdlib/constr.h" #include "gromacs/mdlib/ebin.h" #include "gromacs/mdlib/enerdata_utils.h" #include "gromacs/mdlib/energyoutput.h" #include "gromacs/mdlib/expanded.h" #include "gromacs/mdlib/force.h" #include "gromacs/mdlib/force_flags.h" #include "gromacs/mdlib/forcerec.h" #include "gromacs/mdlib/freeenergyparameters.h" #include "gromacs/mdlib/md_support.h" #include "gromacs/mdlib/mdatoms.h" #include "gromacs/mdlib/mdoutf.h" #include "gromacs/mdlib/membed.h" #include "gromacs/mdlib/resethandler.h" #include "gromacs/mdlib/sighandler.h" #include "gromacs/mdlib/simulationsignal.h" #include "gromacs/mdlib/stat.h" #include "gromacs/mdlib/stophandler.h" #include "gromacs/mdlib/tgroup.h" #include "gromacs/mdlib/trajectory_writing.h" #include "gromacs/mdlib/update.h" #include "gromacs/mdlib/vcm.h" #include "gromacs/mdlib/vsite.h" #include "gromacs/mdrunutility/handlerestart.h" #include "gromacs/mdrunutility/multisim.h" #include "gromacs/mdrunutility/printtime.h" #include "gromacs/mdtypes/awh_history.h" #include "gromacs/mdtypes/awh_params.h" #include "gromacs/mdtypes/commrec.h" #include "gromacs/mdtypes/df_history.h" #include "gromacs/mdtypes/energyhistory.h" #include "gromacs/mdtypes/forcebuffers.h" #include "gromacs/mdtypes/forcerec.h" #include "gromacs/mdtypes/group.h" #include "gromacs/mdtypes/inputrec.h" #include "gromacs/mdtypes/interaction_const.h" #include "gromacs/mdtypes/md_enums.h" #include "gromacs/mdtypes/mdatom.h" #include "gromacs/mdtypes/mdrunoptions.h" #include "gromacs/mdtypes/observableshistory.h" #include "gromacs/mdtypes/observablesreducer.h" #include "gromacs/mdtypes/simulation_workload.h" #include "gromacs/mdtypes/state.h" #include "gromacs/mimic/utilities.h" #include "gromacs/pbcutil/pbc.h" #include "gromacs/pulling/output.h" #include "gromacs/pulling/pull.h" #include "gromacs/swap/swapcoords.h" #include "gromacs/timing/wallcycle.h" #include "gromacs/timing/walltime_accounting.h" #include "gromacs/topology/atoms.h" #include "gromacs/topology/idef.h" #include "gromacs/topology/mtop_util.h" #include "gromacs/topology/topology.h" #include "gromacs/trajectory/trajectoryframe.h" #include "gromacs/utility/basedefinitions.h" #include "gromacs/utility/cstringutil.h" #include "gromacs/utility/fatalerror.h" #include "gromacs/utility/logger.h" #include "gromacs/utility/real.h" #include "legacysimulator.h" #include "replicaexchange.h" #include "shellfc.h" using gmx::SimulationSignaller; using gmx::VirtualSitesHandler; /*! \brief Copy the state from \p rerunFrame to \p globalState and, if requested, construct vsites * * \param[in] rerunFrame The trajectory frame to compute energy/forces for * \param[in,out] globalState The global state container * \param[in] constructVsites When true, vsite coordinates are constructed * \param[in] vsite Vsite setup, can be nullptr when \p constructVsites = false */ static void prepareRerunState(const t_trxframe& rerunFrame, t_state* globalState, bool constructVsites, const VirtualSitesHandler* vsite) { auto x = makeArrayRef(globalState->x); auto rerunX = arrayRefFromArray(reinterpret_cast<gmx::RVec*>(rerunFrame.x), globalState->natoms); std::copy(rerunX.begin(), rerunX.end(), x.begin()); copy_mat(rerunFrame.box, globalState->box); if (constructVsites) { GMX_ASSERT(vsite, "Need valid vsite for constructing vsites"); vsite->construct(globalState->x, globalState->v, globalState->box, gmx::VSiteOperation::PositionsAndVelocities); } } void gmx::LegacySimulator::do_rerun() { // TODO Historically, the EM and MD "integrators" used different // names for the t_inputrec *parameter, but these must have the // same name, now that it's a member of a struct. We use this ir // alias to avoid a large ripple of nearly useless changes. // t_inputrec is being replaced by IMdpOptionsProvider, so this // will go away eventually. const t_inputrec* ir = inputrec; double t; bool isLastStep = false; bool doFreeEnergyPerturbation = false; unsigned int force_flags; tensor force_vir, shake_vir, total_vir, pres; t_trxstatus* status = nullptr; rvec mu_tot; t_trxframe rerun_fr; ForceBuffers f; gmx_global_stat_t gstat; gmx_shellfc_t* shellfc; double cycles; SimulationSignals signals; // Most global communnication stages don't propagate mdrun // signals, and will use this object to achieve that. SimulationSignaller nullSignaller(nullptr, nullptr, nullptr, false, false); GMX_LOG(mdlog.info) .asParagraph() .appendText( "Note that it is planned that the command gmx mdrun -rerun will " "be available in a different form in a future version of GROMACS, " "e.g. gmx rerun -f."); if (ir->efep != FreeEnergyPerturbationType::No && (mdAtoms->mdatoms()->nMassPerturbed > 0 || (constr && constr->havePerturbedConstraints()))) { gmx_fatal(FARGS, "Perturbed masses or constraints are not supported by rerun. " "Either make a .tpr without mass and constraint perturbation, " "or use GROMACS 2018.4, 2018.5 or later 2018 version."); } if (ir->bExpanded) { gmx_fatal(FARGS, "Expanded ensemble not supported by rerun."); } if (ir->bSimTemp) { gmx_fatal(FARGS, "Simulated tempering not supported by rerun."); } if (ir->bDoAwh) { gmx_fatal(FARGS, "AWH not supported by rerun."); } if (replExParams.exchangeInterval > 0) { gmx_fatal(FARGS, "Replica exchange not supported by rerun."); } if (opt2bSet("-ei", nfile, fnm) || observablesHistory->edsamHistory != nullptr) { gmx_fatal(FARGS, "Essential dynamics not supported by rerun."); } if (ir->bIMD) { gmx_fatal(FARGS, "Interactive MD not supported by rerun."); } if (isMultiSim(ms)) { gmx_fatal(FARGS, "Multiple simulations not supported by rerun."); } if (std::any_of(ir->opts.annealing, ir->opts.annealing + ir->opts.ngtc, [](SimulatedAnnealing i) { return i != SimulatedAnnealing::No; })) { gmx_fatal(FARGS, "Simulated annealing not supported by rerun."); } /* Rerun can't work if an output file name is the same as the input file name. * If this is the case, the user will get an error telling them what the issue is. */ if (strcmp(opt2fn("-rerun", nfile, fnm), opt2fn("-o", nfile, fnm)) == 0 || strcmp(opt2fn("-rerun", nfile, fnm), opt2fn("-x", nfile, fnm)) == 0) { gmx_fatal(FARGS, "When using mdrun -rerun, the name of the input trajectory file " "%s cannot be identical to the name of an output file (whether " "given explicitly with -o or -x, or by default)", opt2fn("-rerun", nfile, fnm)); } /* Settings for rerun */ { // TODO: Avoid changing inputrec (#3854) auto* nonConstInputrec = const_cast<t_inputrec*>(inputrec); nonConstInputrec->nstlist = 1; nonConstInputrec->nstcalcenergy = 1; nonConstInputrec->nstxout_compressed = 0; } int nstglobalcomm = 1; const bool bNS = true; ObservablesReducer observablesReducer = observablesReducerBuilder->build(); const SimulationGroups* groups = &top_global.groups; if (ir->eI == IntegrationAlgorithm::Mimic) { auto* nonConstGlobalTopology = const_cast<gmx_mtop_t*>(&top_global); nonConstGlobalTopology->intermolecularExclusionGroup = genQmmmIndices(top_global); } int* fep_state = MASTER(cr) ? &state_global->fep_state : nullptr; gmx::ArrayRef<real> lambda = MASTER(cr) ? state_global->lambda : gmx::ArrayRef<real>(); initialize_lambdas(fplog, ir->efep, ir->bSimTemp, *ir->fepvals, ir->simtempvals->temperatures, gmx::arrayRefFromArray(ir->opts.ref_t, ir->opts.ngtc), MASTER(cr), fep_state, lambda); const bool simulationsShareState = false; gmx_mdoutf* outf = init_mdoutf(fplog, nfile, fnm, mdrunOptions, cr, outputProvider, mdModulesNotifiers, ir, top_global, oenv, wcycle, StartingBehavior::NewSimulation, simulationsShareState, ms); gmx::EnergyOutput energyOutput(mdoutf_get_fp_ene(outf), top_global, *ir, pull_work, mdoutf_get_fp_dhdl(outf), true, StartingBehavior::NewSimulation, simulationsShareState, mdModulesNotifiers); gstat = global_stat_init(ir); /* Check for polarizable models and flexible constraints */ shellfc = init_shell_flexcon(fplog, top_global, constr ? constr->numFlexibleConstraints() : 0, ir->nstcalcenergy, haveDDAtomOrdering(*cr), runScheduleWork->simulationWork.useGpuPme); { double io = compute_io(ir, top_global.natoms, *groups, energyOutput.numEnergyTerms(), 1); if ((io > 2000) && MASTER(cr)) { fprintf(stderr, "\nWARNING: This run will generate roughly %.0f Mb of data\n\n", io); } } if (haveDDAtomOrdering(*cr)) { // Local state only becomes valid now. dd_init_local_state(*cr->dd, state_global, state); /* Distribute the charge groups over the nodes from the master node */ dd_partition_system(fplog, mdlog, ir->init_step, cr, TRUE, 1, state_global, top_global, *ir, imdSession, pull_work, state, &f, mdAtoms, top, fr, vsite, constr, nrnb, nullptr, FALSE); } else { state_change_natoms(state_global, state_global->natoms); /* Copy the pointer to the global state */ state = state_global; mdAlgorithmsSetupAtomData(cr, *ir, top_global, top, fr, &f, mdAtoms, constr, vsite, shellfc); } auto* mdatoms = mdAtoms->mdatoms(); fr->longRangeNonbondeds->updateAfterPartition(*mdatoms); // NOTE: The global state is no longer used at this point. // But state_global is still used as temporary storage space for writing // the global state to file and potentially for replica exchange. // (Global topology should persist.) update_mdatoms(mdatoms, state->lambda[FreeEnergyPerturbationCouplingType::Mass]); if (ir->efep != FreeEnergyPerturbationType::No && ir->fepvals->nstdhdl != 0) { doFreeEnergyPerturbation = true; } int64_t step = ir->init_step; int64_t step_rel = 0; { int cglo_flags = CGLO_GSTAT; bool bSumEkinhOld = false; t_vcm* vcm = nullptr; compute_globals(gstat, cr, ir, fr, ekind, makeConstArrayRef(state->x), makeConstArrayRef(state->v), state->box, mdatoms, nrnb, vcm, nullptr, enerd, force_vir, shake_vir, total_vir, pres, &nullSignaller, state->box, &bSumEkinhOld, cglo_flags, step, &observablesReducer); // Clean up after pre-step use of compute_globals() observablesReducer.markAsReadyToReduce(); } if (MASTER(cr)) { fprintf(stderr, "starting md rerun '%s', reading coordinates from" " input trajectory '%s'\n\n", *(top_global.name), opt2fn("-rerun", nfile, fnm)); if (mdrunOptions.verbose) { fprintf(stderr, "Calculated time to finish depends on nsteps from " "run input file,\nwhich may not correspond to the time " "needed to process input trajectory.\n\n"); } fprintf(fplog, "\n"); } walltime_accounting_start_time(walltime_accounting); wallcycle_start(wcycle, WallCycleCounter::Run); print_start(fplog, cr, walltime_accounting, "mdrun"); /*********************************************************** * * Loop over MD steps * ************************************************************/ if (constr) { GMX_LOG(mdlog.info) .asParagraph() .appendText("Simulations has constraints. Rerun does not recalculate constraints."); } rerun_fr.natoms = 0; if (MASTER(cr)) { isLastStep = !read_first_frame(oenv, &status, opt2fn("-rerun", nfile, fnm), &rerun_fr, TRX_NEED_X); if (rerun_fr.natoms != top_global.natoms) { gmx_fatal(FARGS, "Number of atoms in trajectory (%d) does not match the " "run input file (%d)\n", rerun_fr.natoms, top_global.natoms); } if (ir->pbcType != PbcType::No) { if (!rerun_fr.bBox) { gmx_fatal(FARGS, "Rerun trajectory frame step %" PRId64 " time %f " "does not contain a box, while pbc is used", rerun_fr.step, rerun_fr.time); } if (max_cutoff2(ir->pbcType, rerun_fr.box) < gmx::square(fr->rlist)) { gmx_fatal(FARGS, "Rerun trajectory frame step %" PRId64 " time %f " "has too small box dimensions", rerun_fr.step, rerun_fr.time); } } } GMX_LOG(mdlog.info) .asParagraph() .appendText( "Rerun does not report kinetic energy, total energy, temperature, virial and " "pressure."); if (PAR(cr)) { rerun_parallel_comm(cr, &rerun_fr, &isLastStep); } if (ir->pbcType != PbcType::No) { /* Set the shift vectors. * Necessary here when have a static box different from the tpr box. */ calc_shifts(rerun_fr.box, fr->shift_vec); } auto stopHandler = stopHandlerBuilder->getStopHandlerMD( compat::not_null<SimulationSignal*>(&signals[eglsSTOPCOND]), false, MASTER(cr), ir->nstlist, mdrunOptions.reproducible, nstglobalcomm, mdrunOptions.maximumHoursToRun, ir->nstlist == 0, fplog, step, bNS, walltime_accounting); // we don't do counter resetting in rerun - finish will always be valid walltime_accounting_set_valid_finish(walltime_accounting); const DDBalanceRegionHandler ddBalanceRegionHandler(cr); /* and stop now if we should */ isLastStep = (isLastStep || (ir->nsteps >= 0 && step_rel > ir->nsteps)); while (!isLastStep) { wallcycle_start(wcycle, WallCycleCounter::Step); if (rerun_fr.bStep) { step = rerun_fr.step; step_rel = step - ir->init_step; } if (rerun_fr.bTime) { t = rerun_fr.time; } else { t = step; } if (ir->efep != FreeEnergyPerturbationType::No && MASTER(cr)) { if (rerun_fr.bLambda) { ir->fepvals->init_lambda = rerun_fr.lambda; } else { if (rerun_fr.bFepState) { state->fep_state = rerun_fr.fep_state; } } state_global->lambda = currentLambdas(step, *(ir->fepvals), state->fep_state); } if (MASTER(cr)) { const bool constructVsites = ((vsite != nullptr) && mdrunOptions.rerunConstructVsites); if (constructVsites && haveDDAtomOrdering(*cr)) { gmx_fatal(FARGS, "Vsite recalculation with -rerun is not implemented with domain " "decomposition, " "use a single rank"); } prepareRerunState(rerun_fr, state_global, constructVsites, vsite); } isLastStep = isLastStep || stopHandler->stoppingAfterCurrentStep(bNS); if (haveDDAtomOrdering(*cr)) { /* Repartition the domain decomposition */ const bool bMasterState = true; dd_partition_system(fplog, mdlog, step, cr, bMasterState, nstglobalcomm, state_global, top_global, *ir, imdSession, pull_work, state, &f, mdAtoms, top, fr, vsite, constr, nrnb, wcycle, mdrunOptions.verbose); } if (MASTER(cr)) { EnergyOutput::printHeader(fplog, step, t); /* can we improve the information printed here? */ } if (ir->efep != FreeEnergyPerturbationType::No) { update_mdatoms(mdatoms, state->lambda[FreeEnergyPerturbationCouplingType::Mass]); } fr->longRangeNonbondeds->updateAfterPartition(*mdatoms); force_flags = (GMX_FORCE_STATECHANGED | GMX_FORCE_DYNAMICBOX | GMX_FORCE_ALLFORCES | GMX_FORCE_VIRIAL | // TODO: Get rid of this once #2649 and #3400 are solved GMX_FORCE_ENERGY | (doFreeEnergyPerturbation ? GMX_FORCE_DHDL : 0)); if (shellfc) { /* Now is the time to relax the shells */ relax_shell_flexcon(fplog, cr, ms, mdrunOptions.verbose, enforcedRotation, step, ir, imdSession, pull_work, bNS, force_flags, top, constr, enerd, state->natoms, state->x.arrayRefWithPadding(), state->v.arrayRefWithPadding(), state->box, state->lambda, &state->hist, &f.view(), force_vir, *mdatoms, fr->longRangeNonbondeds.get(), nrnb, wcycle, shellfc, fr, runScheduleWork, t, mu_tot, vsite, ddBalanceRegionHandler); } else { /* The coordinates (x) are shifted (to get whole molecules) * in do_force. * This is parallellized as well, and does communication too. * Check comments in sim_util.c */ Awh* awh = nullptr; gmx_edsam* ed = nullptr; do_force(fplog, cr, ms, *ir, awh, enforcedRotation, imdSession, pull_work, step, nrnb, wcycle, top, state->box, state->x.arrayRefWithPadding(), &state->hist, &f.view(), force_vir, mdatoms, enerd, state->lambda, fr, runScheduleWork, vsite, mu_tot, t, ed, fr->longRangeNonbondeds.get(), GMX_FORCE_NS | force_flags, ddBalanceRegionHandler); } /* Now we have the energies and forces corresponding to the * coordinates at time t. */ { const bool isCheckpointingStep = false; const bool doRerun = true; const bool bSumEkinhOld = false; do_md_trajectory_writing(fplog, cr, nfile, fnm, step, step_rel, t, ir, state, state_global, observablesHistory, top_global, fr, outf, energyOutput, ekind, f.view().force(), isCheckpointingStep, doRerun, isLastStep, mdrunOptions.writeConfout, bSumEkinhOld); } stopHandler->setSignal(); { const bool doInterSimSignal = false; const bool doIntraSimSignal = true; bool bSumEkinhOld = false; t_vcm* vcm = nullptr; SimulationSignaller signaller(&signals, cr, ms, doInterSimSignal, doIntraSimSignal); int cglo_flags = CGLO_GSTAT | CGLO_ENERGY; compute_globals(gstat, cr, ir, fr, ekind, makeConstArrayRef(state->x), makeConstArrayRef(state->v), state->box, mdatoms, nrnb, vcm, wcycle, enerd, force_vir, shake_vir, total_vir, pres, &signaller, state->box, &bSumEkinhOld, cglo_flags, step, &observablesReducer); // Clean up after pre-step use of compute_globals() observablesReducer.markAsReadyToReduce(); } /* Note: this is OK, but there are some numerical precision issues with using the convergence of the virial that should probably be addressed eventually. state->veta has better properies, but what we actually need entering the new cycle is the new shake_vir value. Ideally, we could generate the new shake_vir, but test the veta value for convergence. This will take some thought. */ /* Output stuff */ if (MASTER(cr)) { const bool bCalcEnerStep = true; energyOutput.addDataAtEnergyStep(doFreeEnergyPerturbation, bCalcEnerStep, t, mdatoms->tmass, enerd, ir->fepvals.get(), ir->expandedvals.get(), state->box, PTCouplingArrays({ state->boxv, state->nosehoover_xi, state->nosehoover_vxi, state->nhpres_xi, state->nhpres_vxi }), state->fep_state, total_vir, pres, ekind, mu_tot, constr); const bool do_ene = true; const bool do_log = true; Awh* awh = nullptr; const bool do_dr = ir->nstdisreout != 0; const bool do_or = ir->nstorireout != 0; EnergyOutput::printAnnealingTemperatures(do_log ? fplog : nullptr, groups, &(ir->opts)); energyOutput.printStepToEnergyFile(mdoutf_get_fp_ene(outf), do_ene, do_dr, do_or, do_log ? fplog : nullptr, step, t, fr->fcdata.get(), awh); if (ir->bPull) { pull_print_output(pull_work, step, t); } if (do_per_step(step, ir->nstlog)) { if (fflush(fplog) != 0) { gmx_fatal(FARGS, "Cannot flush logfile - maybe you are out of disk space?"); } } } /* Print the remaining wall clock time for the run */ if (isMasterSimMasterRank(ms, MASTER(cr)) && (mdrunOptions.verbose || gmx_got_usr_signal())) { if (shellfc) { fprintf(stderr, "\n"); } print_time(stderr, walltime_accounting, step, ir, cr); } /* Ion/water position swapping. * Not done in last step since trajectory writing happens before this call * in the MD loop and exchanges would be lost anyway. */ if ((ir->eSwapCoords != SwapType::No) && (step > 0) && !isLastStep && do_per_step(step, ir->swap->nstswap)) { const bool doRerun = true; do_swapcoords(cr, step, t, ir, swap, wcycle, rerun_fr.x, rerun_fr.box, MASTER(cr) && mdrunOptions.verbose, doRerun); } if (MASTER(cr)) { /* read next frame from input trajectory */ isLastStep = !read_next_frame(oenv, status, &rerun_fr); } if (PAR(cr)) { rerun_parallel_comm(cr, &rerun_fr, &isLastStep); } cycles = wallcycle_stop(wcycle, WallCycleCounter::Step); if (haveDDAtomOrdering(*cr) && wcycle) { dd_cycles_add(cr->dd, cycles, ddCyclStep); } if (!rerun_fr.bStep) { /* increase the MD step number */ step++; step_rel++; } observablesReducer.markAsReadyToReduce(); } /* End of main MD loop */ /* Closing TNG files can include compressing data. Therefore it is good to do that * before stopping the time measurements. */ mdoutf_tng_close(outf); /* Stop measuring walltime */ walltime_accounting_end_time(walltime_accounting); if (MASTER(cr)) { close_trx(status); } if (!thisRankHasDuty(cr, DUTY_PME)) { /* Tell the PME only node to finish */ gmx_pme_send_finish(cr); } done_mdoutf(outf); done_shellfc(fplog, shellfc, step_rel); walltime_accounting_set_nsteps_done(walltime_accounting, step_rel); } <|start_filename|>src/gromacs/trajectoryanalysis/tests/msd.cpp<|end_filename|> /* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2020,2021, by the GROMACS development team, led by * <NAME>, <NAME>, <NAME>, and <NAME>, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS 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. * * GROMACS 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 GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ /*! \internal \file * \brief * Tests for functionality of the "msd" trajectory analysis module. * * \author <NAME> <<EMAIL>> * \ingroup module_trajectoryanalysis */ #include "gmxpre.h" #include "gromacs/trajectoryanalysis/modules/msd.h" #include <gtest/gtest.h> #include "gromacs/gmxpreprocess/grompp.h" #include "gromacs/utility/path.h" #include "gromacs/utility/stringutil.h" #include "gromacs/utility/textstream.h" #include "gromacs/utility/textwriter.h" #include "testutils/cmdlinetest.h" #include "testutils/refdata.h" #include "testutils/testasserts.h" #include "testutils/testfilemanager.h" #include "testutils/textblockmatchers.h" #include "moduletest.h" namespace gmx::test { namespace { using gmx::test::CommandLine; /*! \brief Returns whether or not we care about a header line in an xvg file, for matching purposes. * * \todo This is mostly taken from xvgtest.cpp. We could probably create some modular checker * functionality where each line is compared against a set of subcheckers automatically. Then we * could build matchers like this out of the modular components. */ bool isRelevantXvgHeader(const std::string& line) { return startsWith(line, "@") && (contains(line, " title ") || contains(line, " subtitle ") || contains(line, " label ") || contains(line, "@TYPE ") || contains(line, " legend \"")); } //! Helper function to check a single xvg value in a sequence. void checkXvgDataPoint(TestReferenceChecker* checker, const std::string& value) { checker->checkRealFromString(value, nullptr); } /*! \brief MsdMatcher is effectively an extension of XvgMatcher for gmx msd results. * * In addition to the usual fields XvgMatcher checks, MsdMatcher checks for properly reported * diffusion coefficients. */ class MsdMatcher : public ITextBlockMatcher { public: MsdMatcher() = default; void checkStream(TextInputStream* stream, TestReferenceChecker* checker) override { checker->setDefaultTolerance( gmx::test::FloatingPointTolerance(gmx::test::absoluteTolerance(1.0e-5))); TestReferenceChecker dCoefficientChecker( checker->checkCompound("XvgLegend", "DiffusionCoefficient")); TestReferenceChecker legendChecker(checker->checkCompound("XvgLegend", "Legend")); TestReferenceChecker dataChecker(checker->checkCompound("XvgData", "Data")); std::string line; int rowCount = 0; while (stream->readLine(&line)) { // Legend and titles. if (isRelevantXvgHeader(line)) { legendChecker.checkString(stripString(line.substr(1)), nullptr); continue; } // All other comment lines we don't care about. if (startsWith(line, "#") || startsWith(line, "@")) { continue; } // Actual data. const std::vector<std::string> columns = splitString(line); const std::string id = formatString("Row%d", rowCount); dataChecker.checkSequence(columns.begin(), columns.end(), id.c_str(), &checkXvgDataPoint); rowCount++; } } }; class MsdMatch : public ITextBlockMatcherSettings { public: [[nodiscard]] TextBlockMatcherPointer createMatcher() const override { return std::make_unique<MsdMatcher>(); } }; class MsdModuleTest : public gmx::test::TrajectoryAnalysisModuleTestFixture<gmx::analysismodules::MsdInfo> { public: MsdModuleTest() { setOutputFile("-o", "msd.xvg", MsdMatch()); } // Creates a TPR for the given starting structure and topology. Builds an mdp in place prior // to calling grompp. sets the -s input to the generated tpr void createTpr(const std::string& structure, const std::string& topology, const std::string& index) { std::string tpr = fileManager().getTemporaryFilePath(".tpr"); std::string mdp = fileManager().getTemporaryFilePath(".mdp"); std::string mdpFileContents = gmx::formatString( "cutoff-scheme = verlet\n" "rcoulomb = 0.85\n" "rvdw = 0.85\n" "rlist = 0.85\n"); gmx::TextWriter::writeFileFromString(mdp, mdpFileContents); // Prepare a .tpr file CommandLine caller; const auto* simDB = gmx::test::TestFileManager::getTestSimulationDatabaseDirectory(); caller.append("grompp"); caller.addOption("-maxwarn", 0); caller.addOption("-f", mdp.c_str()); std::string gro = gmx::Path::join(simDB, structure); caller.addOption("-c", gro.c_str()); std::string top = gmx::Path::join(simDB, topology); caller.addOption("-p", top.c_str()); std::string ndx = gmx::Path::join(simDB, index); caller.addOption("-n", ndx.c_str()); caller.addOption("-o", tpr.c_str()); ASSERT_EQ(0, gmx_grompp(caller.argc(), caller.argv())); // setInputFile() doesn't like the temporary tpr path. CommandLine& cmdline = commandLine(); cmdline.addOption("-s", tpr.c_str()); } // Convenience function to set input trajectory, tpr, and index, if all of the input files // share a common prefix. void setAllInputs(const std::string& prefix) { setInputFile("-f", prefix + ".xtc"); setInputFile("-n", prefix + ".ndx"); createTpr(prefix + ".gro", prefix + ".top", prefix + ".ndx"); } }; // ---------------------------------------------- // These tests check the basic MSD and diffusion coefficient reporting capabilities on toy systems. // Trestart is set to larger than the size of the trajectory so that all frames are only compared // against the first frame and diffusion coefficients can be predicted exactly. // ---------------------------------------------- // for 3D, (8 + 4 + 0) / 3 should yield 4 cm^2 / s TEST_F(MsdModuleTest, threeDimensionalDiffusion) { setInputFile("-f", "msd_traj.xtc"); setInputFile("-s", "msd_coords.gro"); setInputFile("-n", "msd.ndx"); const char* const cmdline[] = { "-trestart", "200", "-sel", "0", }; runTest(CommandLine(cmdline)); } // for lateral z, (8 + 4) / 2 should yield 6 cm^2 /s TEST_F(MsdModuleTest, twoDimensionalDiffusion) { setInputFile("-f", "msd_traj.xtc"); setInputFile("-s", "msd_coords.gro"); setInputFile("-n", "msd.ndx"); const char* const cmdline[] = { "-trestart", "200", "-lateral", "z", "-sel", "0" }; runTest(CommandLine(cmdline)); } // for type x, should yield 8 cm^2 / s TEST_F(MsdModuleTest, oneDimensionalDiffusion) { setInputFile("-f", "msd_traj.xtc"); setInputFile("-s", "msd_coords.gro"); setInputFile("-n", "msd.ndx"); const char* const cmdline[] = { "-trestart", "200", "-type", "x", "-sel", "0" }; runTest(CommandLine(cmdline)); } // ------------------------------------------------------------------------- // These tests operate on a more realistic trajectory, with a solvated protein, // with 20 frames at a 2 ps dt. Note that this box is also non-square, so we're validating // non-trivial pbc removal. // Group 1 = protein, 2 = all waters, 3 = a subset of 6 water molecules // ------------------------------------------------------------------------ TEST_F(MsdModuleTest, multipleGroupsWork) { setAllInputs("alanine_vsite_solvated"); // Restart every frame, select protein and water separately. Note that the reported diffusion // coefficient for protein is not well-sampled and doesn't correspond to anything physical. const char* const cmdline[] = { "-trestart", "2", "-sel", "1;2" }; runTest(CommandLine(cmdline)); } TEST_F(MsdModuleTest, trestartLessThanDt) { setAllInputs("alanine_vsite_solvated"); const char* const cmdline[] = { "-trestart", "1", "-sel", "2" }; runTest(CommandLine(cmdline)); } TEST_F(MsdModuleTest, trestartGreaterThanDt) { setAllInputs("alanine_vsite_solvated"); const char* const cmdline[] = { "-trestart", "10", "-sel", "2" }; runTest(CommandLine(cmdline)); } TEST_F(MsdModuleTest, molTest) { setAllInputs("alanine_vsite_solvated"); setOutputFile("-mol", "diff_mol.xvg", MsdMatch()); const char* const cmdline[] = { "-trestart", "10", "-sel", "3" }; runTest(CommandLine(cmdline)); } TEST_F(MsdModuleTest, beginFit) { setAllInputs("alanine_vsite_solvated"); const char* const cmdline[] = { "-trestart", "2", "-sel", "3", "-beginfit", "20" }; runTest(CommandLine(cmdline)); } TEST_F(MsdModuleTest, endFit) { setAllInputs("alanine_vsite_solvated"); const char* const cmdline[] = { "-trestart", "2", "-sel", "3", "-endfit", "25" }; runTest(CommandLine(cmdline)); } TEST_F(MsdModuleTest, notEnoughPointsForFitErrorEstimate) { setAllInputs("alanine_vsite_solvated"); const char* const cmdline[] = { "-trestart", "2", "-beginfit", "5", "-endfit", "9", "-lateral", "x", "-sel", "all" }; runTest(CommandLine(cmdline)); } } // namespace } // namespace gmx::test <|start_filename|>api/nblib/listed_forces/helpers.hpp<|end_filename|> /* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2020, by the GROMACS development team, led by * <NAME>, <NAME>, <NAME>, and <NAME>, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS 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. * * GROMACS 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 GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ /*! \internal \file * \brief * Helper data structures and utility functions for the nblib force calculator. * Intended for internal use. * * \author <NAME> <<EMAIL>> * \author <NAME> <<EMAIL>> * \author <NAME> <<EMAIL>> * \author <NAME> <<EMAIL>> * \author <NAME> <<EMAIL>> */ #ifndef NBLIB_LISTEDFORCSES_HELPERS_HPP #define NBLIB_LISTEDFORCSES_HELPERS_HPP #include <unordered_map> #include "nblib/pbc.hpp" #include "definitions.h" #include "nblib/util/util.hpp" #define NBLIB_ALWAYS_INLINE __attribute((always_inline)) namespace nblib { namespace detail { template<class T> inline void gmxRVecZeroWorkaround([[maybe_unused]] T& value) { } template<> inline void gmxRVecZeroWorkaround<gmx::RVec>(gmx::RVec& value) { for (int i = 0; i < dimSize; ++i) { value[i] = 0; } } } // namespace detail /*! \internal \brief object to store forces for multithreaded listed forces computation * */ template<class T> class ForceBuffer { using HashMap = std::unordered_map<int, T>; public: ForceBuffer() : rangeStart(0), rangeEnd(0) { } ForceBuffer(T* mbuf, int rs, int re) : masterForceBuffer(mbuf), rangeStart(rs), rangeEnd(re) { } void clear() { outliers.clear(); } inline NBLIB_ALWAYS_INLINE T& operator[](int i) { if (i >= rangeStart && i < rangeEnd) { return masterForceBuffer[i]; } else { if (outliers.count(i) == 0) { T zero = T(); // if T = gmx::RVec, need to explicitly initialize it to zeros detail::gmxRVecZeroWorkaround(zero); outliers[i] = zero; } return outliers[i]; } } typename HashMap::const_iterator begin() { return outliers.begin(); } typename HashMap::const_iterator end() { return outliers.end(); } [[nodiscard]] bool inRange(int index) const { return (index >= rangeStart && index < rangeEnd); } private: T* masterForceBuffer; int rangeStart; int rangeEnd; HashMap outliers; }; namespace detail { static int computeChunkIndex(int index, int totalRange, int nSplits) { if (totalRange < nSplits) { // if there's more threads than particles return index; } int splitLength = totalRange / nSplits; return std::min(index / splitLength, nSplits - 1); } } // namespace detail /*! \internal \brief splits an interaction tuple into nSplits interaction tuples * * \param interactions * \param totalRange the number of particle sequence coordinates * \param nSplits number to divide the total work by * \return */ inline std::vector<ListedInteractionData> splitListedWork(const ListedInteractionData& interactions, int totalRange, int nSplits) { std::vector<ListedInteractionData> workDivision(nSplits); auto splitOneElement = [totalRange, nSplits, &workDivision](const auto& inputElement) { // the index of inputElement in the ListedInteractionsTuple constexpr int elementIndex = FindIndex<std::decay_t<decltype(inputElement)>, ListedInteractionData>{}; // for now, copy all parameters to each split // Todo: extract only the parameters needed for this split for (auto& workDivisionSplit : workDivision) { std::get<elementIndex>(workDivisionSplit).parameters = inputElement.parameters; } // loop over all interactions in inputElement for (const auto& interactionIndex : inputElement.indices) { // each interaction has multiple coordinate indices // we must pick one of them to assign this interaction to one of the output index ranges // Todo: count indices outside the current split range in order to minimize the buffer size int representativeIndex = *std::min_element(begin(interactionIndex), end(interactionIndex) - 1); int splitIndex = detail::computeChunkIndex(representativeIndex, totalRange, nSplits); std::get<elementIndex>(workDivision[splitIndex]).indices.push_back(interactionIndex); } }; // split each interaction type in the input interaction tuple for_each_tuple(splitOneElement, interactions); return workDivision; } } // namespace nblib #undef NBLIB_ALWAYS_INLINE #endif // NBLIB_LISTEDFORCSES_HELPERS_HPP <|start_filename|>api/legacy/include/gromacs/math/functions.h<|end_filename|> /* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2015,2016,2018,2019,2020 by the GROMACS development team. * Copyright (c) 2021, by the GROMACS development team, led by * <NAME>, <NAME>, <NAME>, and <NAME>, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS 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. * * GROMACS 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 GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ /*! \file * \brief * Declares simple math functions * * \author <NAME> <<EMAIL>> * \inpublicapi * \ingroup module_math */ #ifndef GMX_MATH_FUNCTIONS_H #define GMX_MATH_FUNCTIONS_H #include <cmath> #include <cstdint> #include "gromacs/utility/gmxassert.h" #include "gromacs/utility/real.h" namespace gmx { /*! \brief Evaluate log2(n) for integer n statically at compile time. * * Use as staticLog2<n>::value, where n must be a positive integer. * Negative n will be reinterpreted as the corresponding unsigned integer, * and you will get a compile-time error if n==0. * The calculation is done by recursively dividing n by 2 (until it is 1), * and incrementing the result by 1 in each step. * * \tparam n Value to recursively calculate log2(n) for */ template<std::uint64_t n> struct StaticLog2 { static const int value = StaticLog2<n / 2>::value + 1; //!< Variable value used for recursive static calculation of Log2(int) }; /*! \brief Specialization of StaticLog2<n> for n==1. * * This specialization provides the final value in the recursion; never * call it directly, but use StaticLog2<n>::value. */ template<> struct StaticLog2<1> { static const int value = 0; //!< Base value for recursive static calculation of Log2(int) }; /*! \brief Specialization of StaticLog2<n> for n==0. * * This specialization should never actually be used since log2(0) is * negative infinity. However, since Log2() is often used to calculate the number * of bits needed for a number, we might be using the value 0 with a conditional * statement around the logarithm. Depending on the compiler the expansion of * the template can occur before the conditional statement, so to avoid infinite * recursion we need a specialization for the case n==0. */ template<> struct StaticLog2<0> { static const int value = -1; //!< Base value for recursive static calculation of Log2(int) }; /*! \brief Compute floor of logarithm to base 2, 32 bit signed argument * * \param x 32-bit signed argument * * \return log2(x) * * \note This version of the overloaded function will assert that x is * not negative. */ unsigned int log2I(std::int32_t x); /*! \brief Compute floor of logarithm to base 2, 64 bit signed argument * * \param x 64-bit signed argument * * \return log2(x) * * \note This version of the overloaded function will assert that x is * not negative. */ unsigned int log2I(std::int64_t x); /*! \brief Compute floor of logarithm to base 2, 32 bit unsigned argument * * \param x 32-bit unsigned argument * * \return log2(x) * * \note This version of the overloaded function uses unsigned arguments to * be able to handle arguments using all 32 bits. */ unsigned int log2I(std::uint32_t x); /*! \brief Compute floor of logarithm to base 2, 64 bit unsigned argument * * \param x 64-bit unsigned argument * * \return log2(x) * * \note This version of the overloaded function uses unsigned arguments to * be able to handle arguments using all 64 bits. */ unsigned int log2I(std::uint64_t x); /*! \brief Find greatest common divisor of two numbers * * \param p First number, positive * \param q Second number, positive * * \return Greatest common divisor of p and q */ std::int64_t greatestCommonDivisor(std::int64_t p, std::int64_t q); /*! \brief Calculate 1.0/sqrt(x) in single precision * * \param x Positive value to calculate inverse square root for * * For now this is implemented with std::sqrt(x) since gcc seems to do a * decent job optimizing it. However, we might decide to use instrinsics * or compiler-specific functions in the future. * * \return 1.0/sqrt(x) */ static inline float invsqrt(float x) { return 1.0F / std::sqrt(x); } /*! \brief Calculate 1.0/sqrt(x) in double precision, but single range * * \param x Positive value to calculate inverse square root for, must be * in the input domain valid for single precision. * * For now this is implemented with std::sqrt(x). However, we might * decide to use instrinsics or compiler-specific functions in the future, and * then we want to have the freedom to do the first step in single precision. * * \return 1.0/sqrt(x) */ static inline double invsqrt(double x) { return 1.0 / std::sqrt(x); } /*! \brief Calculate 1.0/sqrt(x) for integer x in double precision. * * \param x Positive value to calculate inverse square root for. * * \return 1.0/sqrt(x) */ static inline double invsqrt(int x) { return invsqrt(static_cast<double>(x)); } /*! \brief Calculate inverse cube root of x in single precision * * \param x Argument * * \return x^(-1/3) * * This routine is typically faster than using std::pow(). */ static inline float invcbrt(float x) { return 1.0F / std::cbrt(x); } /*! \brief Calculate inverse sixth root of x in double precision * * \param x Argument * * \return x^(-1/3) * * This routine is typically faster than using std::pow(). */ static inline double invcbrt(double x) { return 1.0 / std::cbrt(x); } /*! \brief Calculate inverse sixth root of integer x in double precision * * \param x Argument * * \return x^(-1/3) * * This routine is typically faster than using std::pow(). */ static inline double invcbrt(int x) { return 1.0 / std::cbrt(x); } /*! \brief Calculate sixth root of x in single precision. * * \param x Argument, must be greater than or equal to zero. * * \return x^(1/6) * * This routine is typically faster than using std::pow(). */ static inline float sixthroot(float x) { return std::sqrt(std::cbrt(x)); } /*! \brief Calculate sixth root of x in double precision. * * \param x Argument, must be greater than or equal to zero. * * \return x^(1/6) * * This routine is typically faster than using std::pow(). */ static inline double sixthroot(double x) { return std::sqrt(std::cbrt(x)); } /*! \brief Calculate sixth root of integer x, return double. * * \param x Argument, must be greater than or equal to zero. * * \return x^(1/6) * * This routine is typically faster than using std::pow(). */ static inline double sixthroot(int x) { return std::sqrt(std::cbrt(x)); } /*! \brief Calculate inverse sixth root of x in single precision * * \param x Argument, must be greater than zero. * * \return x^(-1/6) * * This routine is typically faster than using std::pow(). */ static inline float invsixthroot(float x) { return invsqrt(std::cbrt(x)); } /*! \brief Calculate inverse sixth root of x in double precision * * \param x Argument, must be greater than zero. * * \return x^(-1/6) * * This routine is typically faster than using std::pow(). */ static inline double invsixthroot(double x) { return invsqrt(std::cbrt(x)); } /*! \brief Calculate inverse sixth root of integer x in double precision * * \param x Argument, must be greater than zero. * * \return x^(-1/6) * * This routine is typically faster than using std::pow(). */ static inline double invsixthroot(int x) { return invsqrt(std::cbrt(x)); } /*! \brief calculate x^2 * * \tparam T Type of argument and return value * \param x argument * * \return x^2 */ template<typename T> T square(T x) { return x * x; } /*! \brief calculate x^3 * * \tparam T Type of argument and return value * \param x argument * * \return x^3 */ template<typename T> T power3(T x) { return x * square(x); } /*! \brief calculate x^4 * * \tparam T Type of argument and return value * \param x argument * * \return x^4 */ template<typename T> T power4(T x) { return square(square(x)); } /*! \brief calculate x^5 * * \tparam T Type of argument and return value * \param x argument * * \return x^5 */ template<typename T> T power5(T x) { return x * power4(x); } /*! \brief calculate x^6 * * \tparam T Type of argument and return value * \param x argument * * \return x^6 */ template<typename T> T power6(T x) { return square(power3(x)); } /*! \brief calculate x^12 * * \tparam T Type of argument and return value * \param x argument * * \return x^12 */ template<typename T> T power12(T x) { return square(power6(x)); } /*! \brief Maclaurin series for sinh(x)/x. * * Used for NH chains and MTTK pressure control. * Here, we compute it to 10th order, which might be an overkill. * 8th is probably enough, but it's not very much more expensive. */ static inline real series_sinhx(real x) { real x2 = x * x; return (1 + (x2 / 6.0_real) * (1 + (x2 / 20.0_real) * (1 + (x2 / 42.0_real) * (1 + (x2 / 72.0_real) * (1 + (x2 / 110.0_real)))))); } /*! \brief Inverse error function, double precision. * * \param x Argument, should be in the range -1.0 < x < 1.0 * * \return The inverse of the error function if the argument is inside the * range, +/- infinity if it is exactly 1.0 or -1.0, and NaN otherwise. */ double erfinv(double x); /*! \brief Inverse error function, single precision. * * \param x Argument, should be in the range -1.0 < x < 1.0 * * \return The inverse of the error function if the argument is inside the * range, +/- infinity if it is exactly 1.0 or -1.0, and NaN otherwise. */ float erfinv(float x); /*! \brief Exact integer division, 32bit. * * \param a dividend. Function asserts that it is a multiple of divisor * \param b divisor * * \return quotient of division */ constexpr int32_t exactDiv(int32_t a, int32_t b) { return GMX_ASSERT(a % b == 0, "exactDiv called with non-divisible arguments"), a / b; } //! Exact integer division, 64bit. constexpr int64_t exactDiv(int64_t a, int64_t b) { return GMX_ASSERT(a % b == 0, "exactDiv called with non-divisible arguments"), a / b; } /*! \brief Round float to int * * Rounding behavior is round to nearest. Rounding of halfway cases is implemention defined * (either halway to even or halway away from zero). */ /* Implementation details: It is assumed that FE_TONEAREST is default and not changed by anyone. * Currently the implementation is using rint(f) because 1) on all known HW that is faster than * lround and 2) some compilers (e.g. clang (#22944) and icc) don't optimize (l)lrint(f) well. * GCC(>=4.7) optimizes (l)lrint(f) well but with "-fno-math-errno -funsafe-math-optimizations" * rint(f) is optimized as well. This avoids using intrinsics. * rint(f) followed by float/double to int/int64 conversion produces the same result as directly * rounding to int/int64. */ static inline int roundToInt(float x) { return static_cast<int>(rintf(x)); } //! Round double to int static inline int roundToInt(double x) { return static_cast<int>(rint(x)); } //! Round float to int64_t static inline int64_t roundToInt64(float x) { return static_cast<int>(rintf(x)); } //! Round double to int64_t static inline int64_t roundToInt64(double x) { return static_cast<int>(rint(x)); } //! \brief Check whether \p v is an integer power of 2. template<typename T, typename = std::enable_if_t<std::is_integral<T>::value>> #if defined(__NVCC__) && !defined(__CUDACC_RELAXED_CONSTEXPR__) /* In CUDA 11, a constexpr function cannot be called from a function with incompatible execution * space, unless --expt-relaxed-constexpr flag is set */ __host__ __device__ #endif static inline constexpr bool isPowerOfTwo(const T v) { return (v > 0) && ((v & (v - 1)) == 0); } } // namespace gmx #endif // GMX_MATH_FUNCTIONS_H <|start_filename|>src/gromacs/applied_forces/awh/biassharing.h<|end_filename|> /* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2017,2019,2020,2021, by the GROMACS development team, led by * <NAME>, <NAME>, <NAME>, and <NAME>, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS 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. * * GROMACS 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 GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ /*! \internal \file * * \brief * Declares functions to check bias sharing properties. * * This actual sharing of biases is currently implemeted in BiasState. * * \author <NAME> <<EMAIL>> * \ingroup module_awh */ #ifndef GMX_AWH_BIASSHARING_H #define GMX_AWH_BIASSHARING_H #include <cstddef> #include <memory> #include <vector> #include "gromacs/utility/arrayref.h" #include "gromacs/utility/classhelpers.h" #include "gromacs/utility/gmxmpi.h" struct gmx_multisim_t; struct t_commrec; namespace gmx { template<typename> class ArrayRef; class AwhParams; class BiasSharing { public: /*! \brief Constructor * * \param[in] awhParams Parameters for all biases in this simulation * \param[in] commRecord Intra-simulation communication record * \param[in] simulationMastersComm MPI communicator for all master ranks of all simulations that share this bias */ BiasSharing(const AwhParams& awhParams, const t_commrec& commRecord, MPI_Comm simulationMastersComm); ~BiasSharing(); //! Returns the number of simulations sharing bias \p biasIndex int numSharingSimulations(int biasIndex) const { return numSharingSimulations_[biasIndex]; } //! Returns the index of our simulation in the simulations sharing bias \p biasIndex int sharingSimulationIndex(int biasIndex) const { return sharingSimulationIndices_[biasIndex]; } //! Sums data over the master ranks of all simulations sharing bias \p biasIndex void sumOverMasterRanks(ArrayRef<int> data, int biasIndex) const; //! Sums data over the master ranks of all simulations sharing bias \p biasIndex void sumOverMasterRanks(ArrayRef<long> data, int biasIndex) const; //! Sums data over all simulations sharing bias \p biasIndex and broadcasts to all ranks within the simulation void sum(ArrayRef<int> data, int biasIndex) const; //! Sums data over all simulations sharing bias \p biasIndex and broadcasts to all ranks within the simulation void sum(ArrayRef<double> data, int biasIndex) const; private: //! The number of simulations sharing for each bias std::vector<int> numSharingSimulations_; //! The index of our simulations in the simulations for each bias std::vector<int> sharingSimulationIndices_; //! Reference to the intra-simulation communication record const t_commrec& commRecord_; //! Communicator between master ranks sharing a bias, for each bias std::vector<MPI_Comm> multiSimCommPerBias_; //! List of MPI communicators created by this object so we can destroy them on distruction std::vector<MPI_Comm> createdCommList_; GMX_DISALLOW_COPY_AND_ASSIGN(BiasSharing); }; /*! \brief Returns if any bias is sharing within a simulation. * * \param[in] awhParams The AWH parameters. */ bool haveBiasSharingWithinSimulation(const AwhParams& awhParams); /*! \brief Checks whether biases are compatible for sharing between simulations, throws when not. * * Should be called simultaneously on the master rank of every simulation. * Note that this only checks for technical compatibility. It is up to * the user to check that the sharing physically makes sense. * Throws an exception when shared biases are not compatible. * * \param[in] awhParams The AWH parameters. * \param[in] pointSize Vector of grid-point sizes for each bias. * \param[in] biasSharing Object for communication for sharing bias data over simulations. */ void biasesAreCompatibleForSharingBetweenSimulations(const AwhParams& awhParams, ArrayRef<const size_t> pointSize, const BiasSharing& biasSharing); } // namespace gmx #endif /* GMX_AWH_BIASSHARING_H */ <|start_filename|>src/gromacs/mdlib/gpuforcereduction_impl.cpp<|end_filename|> /* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2020,2021, by the GROMACS development team, led by * <NAME>, <NAME>, <NAME>, and <NAME>, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS 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. * * GROMACS 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 GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ /*! \internal \file * * \brief Implements backend-agnostic GPU Force Reduction functions * * \author <NAME> <<EMAIL>> * * \ingroup module_mdlib */ #include "gmxpre.h" #include "gpuforcereduction_impl.h" #include "gromacs/gpu_utils/device_stream.h" #include "gromacs/gpu_utils/devicebuffer.h" #include "gromacs/gpu_utils/gpueventsynchronizer.h" #include "gromacs/mdlib/gpuforcereduction_impl_internal.h" #include "gromacs/utility/gmxassert.h" namespace gmx { GpuForceReduction::Impl::Impl(const DeviceContext& deviceContext, const DeviceStream& deviceStream, gmx_wallcycle* wcycle) : baseForce_(), deviceContext_(deviceContext), deviceStream_(deviceStream), nbnxmForceToAdd_(), rvecForceToAdd_(), wcycle_(wcycle) { } void GpuForceReduction::Impl::reinit(DeviceBuffer<Float3> baseForcePtr, const int numAtoms, ArrayRef<const int> cell, const int atomStart, const bool accumulate, GpuEventSynchronizer* completionMarker) { GMX_ASSERT(baseForcePtr, "Input base force for reduction has no data"); baseForce_ = baseForcePtr; numAtoms_ = numAtoms; atomStart_ = atomStart; accumulate_ = accumulate; completionMarker_ = completionMarker; cellInfo_.cell = cell.data(); wallcycle_start_nocount(wcycle_, WallCycleCounter::LaunchGpu); reallocateDeviceBuffer( &cellInfo_.d_cell, numAtoms_, &cellInfo_.cellSize, &cellInfo_.cellSizeAlloc, deviceContext_); copyToDeviceBuffer(&cellInfo_.d_cell, &(cellInfo_.cell[atomStart]), 0, numAtoms_, deviceStream_, GpuApiCallBehavior::Async, nullptr); wallcycle_stop(wcycle_, WallCycleCounter::LaunchGpu); dependencyList_.clear(); }; void GpuForceReduction::Impl::registerNbnxmForce(DeviceBuffer<RVec> forcePtr) { GMX_ASSERT(forcePtr, "Input force for reduction has no data"); nbnxmForceToAdd_ = forcePtr; }; void GpuForceReduction::Impl::registerRvecForce(DeviceBuffer<RVec> forcePtr) { GMX_ASSERT(forcePtr, "Input force for reduction has no data"); rvecForceToAdd_ = forcePtr; }; void GpuForceReduction::Impl::addDependency(GpuEventSynchronizer* dependency) { dependencyList_.push_back(dependency); } void GpuForceReduction::Impl::execute() { wallcycle_start_nocount(wcycle_, WallCycleCounter::LaunchGpu); wallcycle_sub_start(wcycle_, WallCycleSubCounter::LaunchGpuNBFBufOps); if (numAtoms_ != 0) { GMX_ASSERT(nbnxmForceToAdd_, "Nbnxm force for reduction has no data"); // Enqueue wait on all dependencies passed for (auto* synchronizer : dependencyList_) { synchronizer->enqueueWaitEvent(deviceStream_); } const bool addRvecForce = static_cast<bool>(rvecForceToAdd_); // True iff initialized launchForceReductionKernel(numAtoms_, atomStart_, addRvecForce, accumulate_, nbnxmForceToAdd_, rvecForceToAdd_, baseForce_, cellInfo_.d_cell, deviceStream_); // Mark that kernel has been launched if (completionMarker_ != nullptr) { completionMarker_->markEvent(deviceStream_); } } wallcycle_sub_stop(wcycle_, WallCycleSubCounter::LaunchGpuNBFBufOps); wallcycle_stop(wcycle_, WallCycleCounter::LaunchGpu); } GpuForceReduction::GpuForceReduction(const DeviceContext& deviceContext, const DeviceStream& deviceStream, gmx_wallcycle* wcycle) : impl_(new Impl(deviceContext, deviceStream, wcycle)) { } void GpuForceReduction::registerNbnxmForce(DeviceBuffer<RVec> forcePtr) { impl_->registerNbnxmForce(forcePtr); } void GpuForceReduction::registerRvecForce(DeviceBuffer<RVec> forcePtr) { impl_->registerRvecForce(forcePtr); } void GpuForceReduction::addDependency(GpuEventSynchronizer* dependency) { impl_->addDependency(dependency); } void GpuForceReduction::reinit(DeviceBuffer<RVec> baseForcePtr, const int numAtoms, ArrayRef<const int> cell, const int atomStart, const bool accumulate, GpuEventSynchronizer* completionMarker) { impl_->reinit(baseForcePtr, numAtoms, cell, atomStart, accumulate, completionMarker); } void GpuForceReduction::execute() { impl_->execute(); } GpuForceReduction::~GpuForceReduction() = default; } // namespace gmx <|start_filename|>src/gromacs/taskassignment/decidegpuusage.h<|end_filename|> /* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2017,2018,2019,2020,2021, by the GROMACS development team, led by * <NAME>, <NAME>, <NAME>, and <NAME>, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS 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. * * GROMACS 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 GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ /*! \libinternal \file * \brief Declares functionality for deciding whether tasks will run on GPUs. * * \author <NAME> <<EMAIL> <EMAIL>> * \ingroup module_taskassignment * \inlibraryapi */ #ifndef GMX_TASKASSIGNMENT_DECIDEGPUUSAGE_H #define GMX_TASKASSIGNMENT_DECIDEGPUUSAGE_H #include <vector> struct gmx_hw_info_t; struct gmx_mtop_t; struct t_inputrec; enum class PmeRunMode; namespace gmx { class MDLogger; //! Record where a compute task is targetted. enum class TaskTarget : int { Auto, Cpu, Gpu }; //! Help pass GPU-emulation parameters with type safety. enum class EmulateGpuNonbonded : bool { //! Do not emulate GPUs. No, //! Do emulate GPUs. Yes }; /*! \libinternal * \brief Structure that holds boolean flags corresponding to the development * features present enabled through environment variables. * */ struct DevelopmentFeatureFlags { //! True if the Buffer ops development feature is enabled // TODO: when the trigger of the buffer ops offload is fully automated this should go away bool enableGpuBufferOps = false; //! If true, forces 'mdrun -update auto' default to 'gpu' bool forceGpuUpdateDefault = false; //! True if the GPU halo exchange development feature is enabled bool enableGpuHaloExchange = false; //! True if the PME PP direct communication GPU development feature is enabled bool enableGpuPmePPComm = false; //! True if the CUDA-aware MPI is being used for GPU direct communication feature bool usingCudaAwareMpi = false; }; class MDAtoms; /*! \brief Decide whether this thread-MPI simulation will run * nonbonded tasks on GPUs. * * The number of GPU tasks and devices influences both the choice of * the number of ranks, and checks upon any such choice made by the * user. So we need to consider this before any automated choice of * the number of thread-MPI ranks. * * \param[in] nonbondedTarget The user's choice for mdrun -nb for where to assign * short-ranged nonbonded interaction tasks. * \param[in] haveAvailableDevices Whether there are available devices. * \param[in] userGpuTaskAssignment The user-specified assignment of GPU tasks to device IDs. * \param[in] emulateGpuNonbonded Whether we will emulate GPU calculation of nonbonded * interactions. * \param[in] buildSupportsNonbondedOnGpu Whether GROMACS was built with GPU support. * \param[in] nonbondedOnGpuIsUseful Whether computing nonbonded interactions on a GPU is * useful for this calculation. * \param[in] numRanksPerSimulation The number of ranks in each simulation. * * \returns Whether the simulation will run nonbonded tasks on GPUs. * * \throws std::bad_alloc If out of memory * InconsistentInputError If the user requirements are inconsistent. */ bool decideWhetherToUseGpusForNonbondedWithThreadMpi(TaskTarget nonbondedTarget, bool haveAvailableDevices, const std::vector<int>& userGpuTaskAssignment, EmulateGpuNonbonded emulateGpuNonbonded, bool buildSupportsNonbondedOnGpu, bool nonbondedOnGpuIsUseful, int numRanksPerSimulation); /*! \brief Decide whether this thread-MPI simulation will run * PME tasks on GPUs. * * The number of GPU tasks and devices influences both the choice of * the number of ranks, and checks upon any such choice made by the * user. So we need to consider this before any automated choice of * the number of thread-MPI ranks. * * \param[in] useGpuForNonbonded Whether GPUs will be used for nonbonded interactions. * \param[in] pmeTarget The user's choice for mdrun -pme for where to assign * long-ranged PME nonbonded interaction tasks. * \param[in] pmeFftTarget The user's choice for mdrun -pmefft for where to run FFT. * \param[in] numDevicesToUse The number of compatible GPUs that the user permitted us to use. * \param[in] userGpuTaskAssignment The user-specified assignment of GPU tasks to device IDs. * \param[in] hardwareInfo Hardware information * \param[in] inputrec The user input * \param[in] numRanksPerSimulation The number of ranks in each simulation. * \param[in] numPmeRanksPerSimulation The number of PME ranks in each simulation. * * \returns Whether the simulation will run PME tasks on GPUs. * * \throws std::bad_alloc If out of memory * InconsistentInputError If the user requirements are inconsistent. */ bool decideWhetherToUseGpusForPmeWithThreadMpi(bool useGpuForNonbonded, TaskTarget pmeTarget, TaskTarget pmeFftTarget, int numDevicesToUse, const std::vector<int>& userGpuTaskAssignment, const gmx_hw_info_t& hardwareInfo, const t_inputrec& inputrec, int numRanksPerSimulation, int numPmeRanksPerSimulation); /*! \brief Decide whether the simulation will try to run nonbonded * tasks on GPUs. * * The final decision cannot be made until after the duty of the rank * is known. But we need to know if nonbonded will run on GPUs for * setting up DD (particularly rlist) and determining duty. If the * user requires GPUs for the tasks of that duty, then it will be an * error when none are found. * * With thread-MPI, calls have been made to * decideWhetherToUseGpusForNonbondedWithThreadMpi() and * decideWhetherToUseGpusForPmeWithThreadMpi() to help determine * the number of ranks and run some checks, but the final * decision is made in this routine, along with many more * consistency checks. * * \param[in] nonbondedTarget The user's choice for mdrun -nb for where to assign short-ranged nonbonded interaction tasks. * \param[in] userGpuTaskAssignment The user-specified assignment of GPU tasks to device IDs. * \param[in] emulateGpuNonbonded Whether we will emulate GPU calculation of nonbonded interactions. * \param[in] buildSupportsNonbondedOnGpu Whether GROMACS was build with GPU support. * \param[in] nonbondedOnGpuIsUseful Whether computing nonbonded interactions on a GPU is useful for this calculation. * \param[in] gpusWereDetected Whether compatible GPUs were detected on any node. * * \returns Whether the simulation will run nonbonded and PME tasks, respectively, on GPUs. * * \throws std::bad_alloc If out of memory * InconsistentInputError If the user requirements are inconsistent. */ bool decideWhetherToUseGpusForNonbonded(TaskTarget nonbondedTarget, const std::vector<int>& userGpuTaskAssignment, EmulateGpuNonbonded emulateGpuNonbonded, bool buildSupportsNonbondedOnGpu, bool nonbondedOnGpuIsUseful, bool gpusWereDetected); /*! \brief Decide whether the simulation will try to run tasks of * different types on GPUs. * * The final decision cannot be made until after the duty of the rank * is known. But we need to know if nonbonded will run on GPUs for * setting up DD (particularly rlist) and determining duty. If the * user requires GPUs for the tasks of that duty, then it will be an * error when none are found. * * With thread-MPI, calls have been made to * decideWhetherToUseGpusForNonbondedWithThreadMpi() and * decideWhetherToUseGpusForPmeWithThreadMpi() to help determine * the number of ranks and run some checks, but the final * decision is made in this routine, along with many more * consistency checks. * * \param[in] useGpuForNonbonded Whether GPUs will be used for nonbonded interactions. * \param[in] pmeTarget The user's choice for mdrun -pme for where to assign long-ranged PME nonbonded interaction tasks. * \param[in] pmeFftTarget The user's choice for mdrun -pmefft for where to do FFT for PME. * \param[in] userGpuTaskAssignment The user-specified assignment of GPU tasks to device IDs. * \param[in] hardwareInfo Hardware information * \param[in] inputrec The user input * \param[in] numRanksPerSimulation The number of ranks in each simulation. * \param[in] numPmeRanksPerSimulation The number of PME ranks in each simulation. * \param[in] gpusWereDetected Whether compatible GPUs were detected on any node. * * \returns Whether the simulation will run nonbonded and PME tasks, respectively, on GPUs. * * \throws std::bad_alloc If out of memory * InconsistentInputError If the user requirements are inconsistent. */ bool decideWhetherToUseGpusForPme(bool useGpuForNonbonded, TaskTarget pmeTarget, TaskTarget pmeFftTarget, const std::vector<int>& userGpuTaskAssignment, const gmx_hw_info_t& hardwareInfo, const t_inputrec& inputrec, int numRanksPerSimulation, int numPmeRanksPerSimulation, bool gpusWereDetected); /*! \brief Determine PME run mode. * * Given the PME task assignment in \p useGpuForPme and the user-provided * FFT task target in \p pmeFftTarget, returns a PME run mode for the * current run. It also checks the compatibility of the two. * * \note Aborts the run upon incompatible values of \p useGpuForPme and \p pmeFftTarget. * * \param[in] useGpuForPme PME task assignment, true if PME task is mapped to the GPU. * \param[in] pmeFftTarget The user's choice for -pmefft for where to assign the FFT * work of the PME task. \param[in] inputrec The user input record * */ PmeRunMode determinePmeRunMode(bool useGpuForPme, const TaskTarget& pmeFftTarget, const t_inputrec& inputrec); /*! \brief Decide whether the simulation will try to run bonded tasks on GPUs. * * \param[in] useGpuForNonbonded Whether GPUs will be used for nonbonded interactions. * \param[in] useGpuForPme Whether GPUs will be used for PME interactions. * \param[in] bondedTarget The user's choice for mdrun -bonded for where to assign tasks. * \param[in] inputrec The user input. * \param[in] mtop The global topology. * \param[in] numPmeRanksPerSimulation The number of PME ranks in each simulation, can be -1 for auto. * \param[in] gpusWereDetected Whether compatible GPUs were detected on any node. * * \returns Whether the simulation will run bondeded tasks on GPUs. * * \throws std::bad_alloc If out of memory * InconsistentInputError If the user requirements are inconsistent. */ bool decideWhetherToUseGpusForBonded(bool useGpuForNonbonded, bool useGpuForPme, TaskTarget bondedTarget, const t_inputrec& inputrec, const gmx_mtop_t& mtop, int numPmeRanksPerSimulation, bool gpusWereDetected); /*! \brief Decide whether to use GPU for update. * * \param[in] isDomainDecomposition Whether there more than one domain. * \param[in] useUpdateGroups If the constraints can be split across domains. * \param[in] pmeRunMode PME running mode: CPU, GPU or mixed. * \param[in] havePmeOnlyRank If there is a PME-only rank in the simulation. * \param[in] useGpuForNonbonded Whether GPUs will be used for nonbonded interactions. * \param[in] updateTarget User choice for running simulation on GPU. * \param[in] gpusWereDetected Whether compatible GPUs were detected on any node. * \param[in] inputrec The user input. * \param[in] mtop The global topology. * \param[in] useEssentialDynamics If essential dynamics is active. * \param[in] doOrientationRestraints If orientation restraints are enabled. * \param[in] haveFrozenAtoms If this simulation has frozen atoms (see Issue #3920). * \param[in] doRerun It this is a rerun. * \param[in] devFlags GPU development / experimental feature flags. * \param[in] mdlog MD logger. * * \returns Whether complete simulation can be run on GPU. * \throws std::bad_alloc If out of memory * InconsistentInputError If the user requirements are inconsistent. */ bool decideWhetherToUseGpuForUpdate(bool isDomainDecomposition, bool useUpdateGroups, PmeRunMode pmeRunMode, bool havePmeOnlyRank, bool useGpuForNonbonded, TaskTarget updateTarget, bool gpusWereDetected, const t_inputrec& inputrec, const gmx_mtop_t& mtop, bool useEssentialDynamics, bool doOrientationRestraints, bool haveFrozenAtoms, bool doRerun, const DevelopmentFeatureFlags& devFlags, const gmx::MDLogger& mdlog); /*! \brief Decide whether to use GPU for halo exchange. * * \param[in] devFlags GPU development / experimental feature flags. * \param[in] havePPDomainDecomposition Whether PP domain decomposition is in use. * \param[in] useGpuForNonbonded Whether GPUs will be used for nonbonded interactions. * \param[in] useModularSimulator Whether modularsimulator is in use. * \param[in] doRerun Whether this is a rerun. * \param[in] haveEnergyMinimization Whether energy minimization is in use. * * \returns Whether halo exchange can be run on GPU. */ bool decideWhetherToUseGpuForHalo(const DevelopmentFeatureFlags& devFlags, bool havePPDomainDecomposition, bool useGpuForNonbonded, bool useModularSimulator, bool doRerun, bool haveEnergyMinimization); } // namespace gmx #endif <|start_filename|>api/nblib/gmxcalculatorcpu.cpp<|end_filename|> /* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2020,2021, by the GROMACS development team, led by * <NAME>, <NAME>, <NAME>, and <NAME>, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS 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. * * GROMACS 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 GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ /*! \internal \file * \brief Implements a force calculator based on GROMACS data structures. * * \author <NAME> <<EMAIL>> * \author <NAME> <<EMAIL>> * \author <NAME> <<EMAIL>> * \author <NAME> <<EMAIL>> */ #include "gromacs/ewald/ewald_utils.h" #include "gromacs/mdtypes/enerdata.h" #include "gromacs/mdtypes/interaction_const.h" #include "gromacs/nbnxm/atomdata.h" #include "gromacs/nbnxm/nbnxm.h" #include "gromacs/nbnxm/pairlistset.h" #include "gromacs/nbnxm/pairlistsets.h" #include "gromacs/nbnxm/pairsearch.h" #include "gromacs/utility/listoflists.h" #include "gromacs/utility/range.h" #include "nblib/exception.h" #include "nblib/gmxbackenddata.h" #include "nblib/gmxcalculatorcpu.h" #include "nblib/nbnxmsetuphelpers.h" #include "nblib/pbc.hpp" #include "nblib/systemdescription.h" #include "nblib/topology.h" #include "nblib/tpr.h" #include "nblib/virials.h" namespace nblib { class GmxNBForceCalculatorCpu::CpuImpl final { public: CpuImpl(gmx::ArrayRef<int> particleTypeIdOfAllParticles, gmx::ArrayRef<real> nonBondedParams, gmx::ArrayRef<real> charges, gmx::ArrayRef<int64_t> particleInteractionFlags, gmx::ArrayRef<int> exclusionRanges, gmx::ArrayRef<int> exclusionElements, const NBKernelOptions& options); //! calculates a new pair list based on new coordinates (for every NS step) void updatePairlist(gmx::ArrayRef<const gmx::RVec> coordinates, const Box& box); //! Compute forces and return void compute(gmx::ArrayRef<const gmx::RVec> coordinateInput, const Box& box, gmx::ArrayRef<gmx::RVec> forceOutput); //! Compute forces and virial tensor void compute(gmx::ArrayRef<const gmx::RVec> coordinateInput, const Box& box, gmx::ArrayRef<gmx::RVec> forceOutput, gmx::ArrayRef<real> virialOutput); //! Compute forces, virial tensor and potential energies void compute(gmx::ArrayRef<const gmx::RVec> coordinateInput, const Box& box, gmx::ArrayRef<gmx::RVec> forceOutput, gmx::ArrayRef<real> virialOutput, gmx::ArrayRef<real> energyOutput); private: //! \brief client-side provided system description data SystemDescription system_; //! \brief Gmx backend objects, employed for calculating the forces GmxBackendData backend_; }; GmxNBForceCalculatorCpu::CpuImpl::CpuImpl(gmx::ArrayRef<int> particleTypeIdOfAllParticles, gmx::ArrayRef<real> nonBondedParams, gmx::ArrayRef<real> charges, gmx::ArrayRef<int64_t> particleInteractionFlags, gmx::ArrayRef<int> exclusionRanges, gmx::ArrayRef<int> exclusionElements, const NBKernelOptions& options) : system_(SystemDescription(particleTypeIdOfAllParticles, nonBondedParams, charges, particleInteractionFlags)), backend_(GmxBackendData(options, findNumEnergyGroups(particleInteractionFlags), exclusionRanges, exclusionElements)) { // Set up non-bonded verlet in the backend backend_.nbv_ = createNbnxmCPU(system_.numParticleTypes_, options, findNumEnergyGroups(particleInteractionFlags), system_.nonBondedParams_); } void GmxNBForceCalculatorCpu::CpuImpl::updatePairlist(gmx::ArrayRef<const gmx::RVec> coordinates, const Box& box) { if (coordinates.size() != system_.numParticles_) { throw InputException( "Coordinate array containing different number of entries than particles in the " "system"); } const auto* legacyBox = box.legacyMatrix(); system_.box_ = box; updateForcerec(&backend_.forcerec_, box.legacyMatrix()); if (TRICLINIC(legacyBox)) { throw InputException("Only rectangular unit-cells are supported here"); } const rvec lowerCorner = { 0, 0, 0 }; const rvec upperCorner = { legacyBox[dimX][dimX], legacyBox[dimY][dimY], legacyBox[dimZ][dimZ] }; const real particleDensity = static_cast<real>(coordinates.size()) / det(legacyBox); // Put particles on a grid based on bounds specified by the box nbnxn_put_on_grid(backend_.nbv_.get(), legacyBox, 0, lowerCorner, upperCorner, nullptr, { 0, int(coordinates.size()) }, particleDensity, system_.particleInfo_, coordinates, 0, nullptr); backend_.nbv_->constructPairlist( gmx::InteractionLocality::Local, backend_.exclusions_, 0, &backend_.nrnb_); // Set Particle Types and Charges and VdW params backend_.nbv_->setAtomProperties( system_.particleTypeIdOfAllParticles_, system_.charges_, system_.particleInfo_); backend_.updatePairlistCalled = true; } void GmxNBForceCalculatorCpu::CpuImpl::compute(gmx::ArrayRef<const gmx::RVec> coordinateInput, const Box& box, gmx::ArrayRef<gmx::RVec> forceOutput, gmx::ArrayRef<real> virialOutput, gmx::ArrayRef<real> energyOutput) { if (coordinateInput.size() != forceOutput.size()) { throw InputException("coordinate array and force buffer size mismatch"); } if (!backend_.updatePairlistCalled) { throw InputException("compute called without updating pairlist at least once"); } // update the box if changed if (!(system_.box_ == box)) { system_.box_ = box; updateForcerec(&backend_.forcerec_, box.legacyMatrix()); } bool computeVirial = !virialOutput.empty(); bool computeEnergies = !energyOutput.empty(); backend_.stepWork_.computeVirial = computeVirial; backend_.stepWork_.computeEnergy = computeEnergies; // update the coordinates in the backend backend_.nbv_->convertCoordinates(gmx::AtomLocality::Local, coordinateInput); backend_.nbv_->dispatchNonbondedKernel( gmx::InteractionLocality::Local, backend_.interactionConst_, backend_.stepWork_, enbvClearFYes, backend_.forcerec_.shift_vec, backend_.enerd_.grpp.energyGroupPairTerms[backend_.forcerec_.haveBuckingham ? NonBondedEnergyTerms::BuckinghamSR : NonBondedEnergyTerms::LJSR], backend_.enerd_.grpp.energyGroupPairTerms[NonBondedEnergyTerms::CoulombSR], &backend_.nrnb_); backend_.nbv_->atomdata_add_nbat_f_to_f(gmx::AtomLocality::All, forceOutput); if (computeVirial) { // calculate shift forces and turn into an array ref std::vector<Vec3> shiftForcesVector(gmx::c_numShiftVectors, Vec3(0.0, 0.0, 0.0)); nbnxn_atomdata_add_nbat_fshift_to_fshift(*backend_.nbv_->nbat, shiftForcesVector); auto shiftForcesRef = constArrayRefFromArray(shiftForcesVector.data(), shiftForcesVector.size()); std::vector<Vec3> shiftVectorsArray(gmx::c_numShiftVectors); // copy shift vectors from ForceRec std::copy(backend_.forcerec_.shift_vec.begin(), backend_.forcerec_.shift_vec.end(), shiftVectorsArray.begin()); computeVirialTensor( coordinateInput, forceOutput, shiftVectorsArray, shiftForcesRef, box, virialOutput); } // extract term energies (per interaction type) if (computeEnergies) { int nGroupPairs = backend_.enerd_.grpp.nener; if (int(energyOutput.size()) != int(NonBondedEnergyTerms::Count) * nGroupPairs) { throw InputException("Array size for energy output is wrong\n"); } for (int eg = 0; eg < int(NonBondedEnergyTerms::Count); ++eg) { std::copy(begin(backend_.enerd_.grpp.energyGroupPairTerms[eg]), end(backend_.enerd_.grpp.energyGroupPairTerms[eg]), energyOutput.begin() + eg * nGroupPairs); } } } void GmxNBForceCalculatorCpu::CpuImpl::compute(gmx::ArrayRef<const gmx::RVec> coordinateInput, const Box& box, gmx::ArrayRef<gmx::RVec> forceOutput) { // compute forces and fill in force buffer compute(coordinateInput, box, forceOutput, gmx::ArrayRef<real>{}, gmx::ArrayRef<real>{}); } void GmxNBForceCalculatorCpu::CpuImpl::compute(gmx::ArrayRef<const gmx::RVec> coordinateInput, const Box& box, gmx::ArrayRef<gmx::RVec> forceOutput, gmx::ArrayRef<real> virialOutput) { // compute forces and fill in force buffer compute(coordinateInput, box, forceOutput, virialOutput, gmx::ArrayRef<real>{}); } GmxNBForceCalculatorCpu::GmxNBForceCalculatorCpu(gmx::ArrayRef<int> particleTypeIdOfAllParticles, gmx::ArrayRef<real> nonBondedParams, gmx::ArrayRef<real> charges, gmx::ArrayRef<int64_t> particleInteractionFlags, gmx::ArrayRef<int> exclusionRanges, gmx::ArrayRef<int> exclusionElements, const NBKernelOptions& options) { if (options.useGpu) { throw InputException("Use GmxNBForceCalculatorGpu for GPU support"); } impl_ = std::make_unique<CpuImpl>(particleTypeIdOfAllParticles, nonBondedParams, charges, particleInteractionFlags, exclusionRanges, exclusionElements, options); } GmxNBForceCalculatorCpu::~GmxNBForceCalculatorCpu() = default; //! calculates a new pair list based on new coordinates (for every NS step) void GmxNBForceCalculatorCpu::updatePairlist(gmx::ArrayRef<const gmx::RVec> coordinates, const Box& box) { impl_->updatePairlist(coordinates, box); } //! Compute forces and return void GmxNBForceCalculatorCpu::compute(gmx::ArrayRef<const gmx::RVec> coordinateInput, const Box& box, gmx::ArrayRef<gmx::RVec> forceOutput) { impl_->compute(coordinateInput, box, forceOutput); } //! Compute forces and virial tensor void GmxNBForceCalculatorCpu::compute(gmx::ArrayRef<const gmx::RVec> coordinateInput, const Box& box, gmx::ArrayRef<gmx::RVec> forceOutput, gmx::ArrayRef<real> virialOutput) { impl_->compute(coordinateInput, box, forceOutput, virialOutput); } //! Compute forces, virial tensor and potential energies void GmxNBForceCalculatorCpu::compute(gmx::ArrayRef<const gmx::RVec> coordinateInput, const Box& box, gmx::ArrayRef<gmx::RVec> forceOutput, gmx::ArrayRef<real> virialOutput, gmx::ArrayRef<real> energyOutput) { impl_->compute(coordinateInput, box, forceOutput, virialOutput, energyOutput); } std::unique_ptr<GmxNBForceCalculatorCpu> setupGmxForceCalculatorCpu(const Topology& topology, const NBKernelOptions& options) { std::vector<real> nonBondedParameters = createNonBondedParameters( topology.getParticleTypes(), topology.getNonBondedInteractionMap()); std::vector<int64_t> particleInteractionFlags = createParticleInfoAllVdw(topology.numParticles()); return std::make_unique<GmxNBForceCalculatorCpu>(topology.getParticleTypeIdOfAllParticles(), nonBondedParameters, topology.getCharges(), particleInteractionFlags, topology.exclusionLists().ListRanges, topology.exclusionLists().ListElements, options); } std::unique_ptr<GmxNBForceCalculatorCpu> setupGmxForceCalculatorCpu(TprReader& tprReader, const NBKernelOptions& options) { return std::make_unique<GmxNBForceCalculatorCpu>(tprReader.particleTypeIdOfAllParticles_, tprReader.nonbondedParameters_, tprReader.charges_, tprReader.particleInteractionFlags_, tprReader.exclusionListRanges_, tprReader.exclusionListElements_, options); } } // namespace nblib <|start_filename|>src/gromacs/gpu_utils/gpuregiontimer.h<|end_filename|> /* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2016,2017,2018,2019,2020, by the GROMACS development team, led by * <NAME>, <NAME>, <NAME>, and <NAME>, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS 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. * * GROMACS 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 GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ /*! \libinternal \file * \brief Defines the GPU region timer implementation/wrapper classes. * The implementations live in gpuregiontimer.cuh for CUDA and gpuregiontimer_ocl.h for OpenCL. * * \author <NAME> <<EMAIL>> */ #ifndef GMX_GPU_UTILS_GPUREGIONTIMER_H #define GMX_GPU_UTILS_GPUREGIONTIMER_H #include <string> #include "gromacs/utility/gmxassert.h" //! Debug GPU timers in debug builds only #if defined(NDEBUG) static const bool c_debugTimerState = false; #else static const bool c_debugTimerState = true; #endif /*! \libinternal \brief * This is a GPU region timing wrapper class. * It allows for host-side tracking of the accumulated execution timespans in GPU code * (measuring kernel or transfers duration). * It also partially tracks the correctness of the timer state transitions, * as far as current implementation allows (see TODO in getLastRangeTime() for a disabled check). * Internally it uses GpuRegionTimerImpl for measuring regions. */ template<typename GpuRegionTimerImpl> class GpuRegionTimerWrapper { //! The timer state used for debug-only assertions enum class TimerState { Idle, Recording, Stopped } debugState_ = TimerState::Idle; //! The number of times the timespan has been measured unsigned int callCount_ = 0; //! The accumulated duration of the timespans measured (milliseconds) double totalMilliseconds_ = 0.0; //! The underlying region timer implementation GpuRegionTimerImpl impl_; public: /*! \brief * To be called before the region start. * * \param[in] deviceStream The GPU command stream where the event being measured takes place. */ void openTimingRegion(const DeviceStream& deviceStream) { if (c_debugTimerState) { std::string error = "GPU timer should be idle, but is " + std::string((debugState_ == TimerState::Stopped) ? "stopped" : "recording") + "."; GMX_ASSERT(debugState_ == TimerState::Idle, error.c_str()); debugState_ = TimerState::Recording; } impl_.openTimingRegion(deviceStream); } /*! \brief * To be called after the region end. * * \param[in] deviceStream The GPU command stream where the event being measured takes place. */ void closeTimingRegion(const DeviceStream& deviceStream) { if (c_debugTimerState) { std::string error = "GPU timer should be recording, but is " + std::string((debugState_ == TimerState::Idle) ? "idle" : "stopped") + "."; GMX_ASSERT(debugState_ == TimerState::Recording, error.c_str()); debugState_ = TimerState::Stopped; } callCount_++; impl_.closeTimingRegion(deviceStream); } /*! \brief * Accumulates the last timespan of all the events used into the total duration, * and resets the internal timer state. * To be called after closeTimingRegion() and the command stream of the event having been * synchronized. \returns The last timespan (in milliseconds). */ double getLastRangeTime() { if (c_debugTimerState) { /* The assertion below is commented because it is currently triggered on a special case: * the early return before the local non-bonded kernel launch if there is nothing to do. * This can be reproduced in OpenCL build by running * mdrun-mpi-test -ntmpi 2 --gtest_filter=*Empty* * Similarly, the GpuRegionTimerImpl suffers from non-nullptr * cl_event conditionals which ideally should only be asserts. * TODO: improve internal task scheduling, re-enable the assert, turn conditionals into asserts */ /* std::string error = "GPU timer should be stopped, but is " + std::string((debugState_ == TimerState::Idle) ? "idle" : "recording") + "."; GMX_ASSERT(debugState_ == TimerState::Stopped, error.c_str()); */ debugState_ = TimerState::Idle; } double milliseconds = impl_.getLastRangeTime(); totalMilliseconds_ += milliseconds; return milliseconds; } /*! \brief Resets the implementation and total time/call count to zeroes. */ void reset() { if (c_debugTimerState) { debugState_ = TimerState::Idle; } totalMilliseconds_ = 0.0; callCount_ = 0; impl_.reset(); } /*! \brief Gets total time recorded (in milliseconds). */ double getTotalTime() const { return totalMilliseconds_; } /*! \brief Gets total call count recorded. */ unsigned int getCallCount() const { return callCount_; } /*! \brief * Gets a pointer to a new timing event for passing into individual GPU API calls * within the region if they require it (e.g. on OpenCL). * \returns The pointer to the underlying single command timing event. */ CommandEvent* fetchNextEvent() { if (c_debugTimerState) { std::string error = "GPU timer should be recording, but is " + std::string((debugState_ == TimerState::Idle) ? "idle" : "stopped") + "."; GMX_ASSERT(debugState_ == TimerState::Recording, error.c_str()); } return impl_.fetchNextEvent(); } }; #endif <|start_filename|>src/gromacs/taskassignment/decidesimulationworkload.cpp<|end_filename|> /* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2019,2020,2021, by the GROMACS development team, led by * <NAME>, <NAME>, <NAME>, and <NAME>, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS 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. * * GROMACS 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 GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ /*! \internal \file * \brief * Defines routine for building simulation workload task description. * * \author <NAME> <<EMAIL>> * \ingroup module_taskassignment */ #include "gmxpre.h" #include "decidesimulationworkload.h" #include "gromacs/ewald/pme.h" #include "gromacs/mdtypes/multipletimestepping.h" #include "gromacs/taskassignment/decidegpuusage.h" #include "gromacs/taskassignment/taskassignment.h" #include "gromacs/utility/arrayref.h" namespace gmx { SimulationWorkload createSimulationWorkload(const t_inputrec& inputrec, const bool disableNonbondedCalculation, const DevelopmentFeatureFlags& devFlags, bool havePpDomainDecomposition, bool haveSeparatePmeRank, bool useGpuForNonbonded, PmeRunMode pmeRunMode, bool useGpuForBonded, bool useGpuForUpdate, bool useGpuDirectHalo) { SimulationWorkload simulationWorkload; simulationWorkload.computeNonbonded = !disableNonbondedCalculation; simulationWorkload.computeNonbondedAtMtsLevel1 = simulationWorkload.computeNonbonded && inputrec.useMts && inputrec.mtsLevels.back().forceGroups[static_cast<int>(MtsForceGroups::Nonbonded)]; simulationWorkload.computeMuTot = inputrecNeedMutot(&inputrec); simulationWorkload.useCpuNonbonded = !useGpuForNonbonded; simulationWorkload.useGpuNonbonded = useGpuForNonbonded; simulationWorkload.useCpuPme = (pmeRunMode == PmeRunMode::CPU); simulationWorkload.useGpuPme = (pmeRunMode == PmeRunMode::GPU || pmeRunMode == PmeRunMode::Mixed); simulationWorkload.useGpuPmeFft = (pmeRunMode == PmeRunMode::Mixed); simulationWorkload.useGpuBonded = useGpuForBonded; simulationWorkload.useGpuUpdate = useGpuForUpdate; simulationWorkload.useGpuBufferOps = (devFlags.enableGpuBufferOps || useGpuForUpdate) && !simulationWorkload.computeNonbondedAtMtsLevel1; simulationWorkload.havePpDomainDecomposition = havePpDomainDecomposition; simulationWorkload.useCpuHaloExchange = havePpDomainDecomposition && !useGpuDirectHalo; simulationWorkload.useGpuHaloExchange = useGpuDirectHalo; if (pmeRunMode == PmeRunMode::None) { GMX_RELEASE_ASSERT(!haveSeparatePmeRank, "Can not have separate PME rank(s) without PME."); } simulationWorkload.haveSeparatePmeRank = haveSeparatePmeRank; simulationWorkload.useGpuPmePpCommunication = haveSeparatePmeRank && devFlags.enableGpuPmePPComm && (pmeRunMode == PmeRunMode::GPU); simulationWorkload.useCpuPmePpCommunication = haveSeparatePmeRank && !simulationWorkload.useGpuPmePpCommunication; GMX_RELEASE_ASSERT(!(simulationWorkload.useGpuPmePpCommunication && simulationWorkload.useCpuPmePpCommunication), "Cannot do PME-PP communication on both CPU and GPU"); simulationWorkload.useGpuDirectCommunication = devFlags.enableGpuHaloExchange || devFlags.enableGpuPmePPComm; simulationWorkload.haveEwaldSurfaceContribution = haveEwaldSurfaceContribution(inputrec); simulationWorkload.useMts = inputrec.useMts; return simulationWorkload; } } // namespace gmx <|start_filename|>src/gromacs/ewald/tests/pmesolvetest.cpp<|end_filename|> /* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2016,2017,2018,2019,2020,2021, by the GROMACS development team, led by * <NAME>, <NAME>, <NAME>, and <NAME>, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS 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. * * GROMACS 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 GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ /*! \internal \file * \brief * Implements PME solving tests. * * \author <NAME> <<EMAIL>> * \ingroup module_ewald */ #include "gmxpre.h" #include <string> #include <gmock/gmock.h> #include "gromacs/mdtypes/inputrec.h" #include "gromacs/utility/stringutil.h" #include "testutils/refdata.h" #include "testutils/test_hardware_environment.h" #include "testutils/testasserts.h" #include "pmetestcommon.h" namespace gmx { namespace test { namespace { /*! \brief Convenience typedef of the test input parameters - unit cell box, complex grid dimensions, complex grid values, * electrostatic constant epsilon_r, Ewald splitting parameters ewaldcoeff_q and ewaldcoeff_lj, solver type * Output: transformed local grid (Fourier space); optionally reciprocal energy and virial matrix. * TODO: * Implement and test Lorentz-Berthelot */ typedef std::tuple<Matrix3x3, IVec, SparseComplexGridValuesInput, double, double, double, PmeSolveAlgorithm> SolveInputParameters; //! Test fixture class PmeSolveTest : public ::testing::TestWithParam<SolveInputParameters> { public: PmeSolveTest() = default; //! Sets the programs once static void SetUpTestSuite() { s_pmeTestHardwareContexts = createPmeTestHardwareContextList(); g_allowPmeWithSyclForTesting = true; // We support PmeSolve with SYCL } static void TearDownTestSuite() { // Revert the value back. g_allowPmeWithSyclForTesting = false; } //! The test static void runTest() { /* Getting the input */ Matrix3x3 box; IVec gridSize; SparseComplexGridValuesInput nonZeroGridValues; double epsilon_r; double ewaldCoeff_q; double ewaldCoeff_lj; PmeSolveAlgorithm method; std::tie(box, gridSize, nonZeroGridValues, epsilon_r, ewaldCoeff_q, ewaldCoeff_lj, method) = GetParam(); /* Storing the input where it's needed, running the test */ t_inputrec inputRec; inputRec.nkx = gridSize[XX]; inputRec.nky = gridSize[YY]; inputRec.nkz = gridSize[ZZ]; inputRec.pme_order = 4; inputRec.coulombtype = CoulombInteractionType::Pme; inputRec.epsilon_r = epsilon_r; switch (method) { case PmeSolveAlgorithm::Coulomb: break; case PmeSolveAlgorithm::LennardJones: inputRec.vdwtype = VanDerWaalsType::Pme; break; default: GMX_THROW(InternalError("Unknown PME solver")); } TestReferenceData refData; for (const auto& pmeTestHardwareContext : s_pmeTestHardwareContexts) { pmeTestHardwareContext->activate(); CodePath codePath = pmeTestHardwareContext->codePath(); const bool supportedInput = pmeSupportsInputForMode( *getTestHardwareEnvironment()->hwinfo(), &inputRec, codePath); if (!supportedInput) { /* Testing the failure for the unsupported input */ EXPECT_THROW_GMX( pmeInitWrapper(&inputRec, codePath, nullptr, nullptr, nullptr, box, ewaldCoeff_q, ewaldCoeff_lj), NotImplementedError); continue; } std::map<GridOrdering, std::string> gridOrderingsToTest = { { GridOrdering::YZX, "YZX" } }; if (codePath == CodePath::GPU) { gridOrderingsToTest[GridOrdering::XYZ] = "XYZ"; } for (const auto& gridOrdering : gridOrderingsToTest) { for (bool computeEnergyAndVirial : { false, true }) { /* Describing the test*/ SCOPED_TRACE(formatString( "Testing solving (%s, %s, %s energy/virial) on %s for PME grid " "size %d %d %d, Ewald coefficients %g %g", (method == PmeSolveAlgorithm::LennardJones) ? "Lennard-Jones" : "Coulomb", gridOrdering.second.c_str(), computeEnergyAndVirial ? "with" : "without", pmeTestHardwareContext->description().c_str(), gridSize[XX], gridSize[YY], gridSize[ZZ], ewaldCoeff_q, ewaldCoeff_lj)); /* Running the test */ PmeSafePointer pmeSafe = pmeInitWrapper(&inputRec, codePath, pmeTestHardwareContext->deviceContext(), pmeTestHardwareContext->deviceStream(), pmeTestHardwareContext->pmeGpuProgram(), box, ewaldCoeff_q, ewaldCoeff_lj); pmeSetComplexGrid(pmeSafe.get(), codePath, gridOrdering.first, nonZeroGridValues); const real cellVolume = box[0] * box[4] * box[8]; // FIXME - this is box[XX][XX] * box[YY][YY] * box[ZZ][ZZ], should be stored in the PME structure pmePerformSolve(pmeSafe.get(), codePath, method, cellVolume, gridOrdering.first, computeEnergyAndVirial); pmeFinalizeTest(pmeSafe.get(), codePath); /* Check the outputs */ TestReferenceChecker checker(refData.rootChecker()); SparseComplexGridValuesOutput nonZeroGridValuesOutput = pmeGetComplexGrid(pmeSafe.get(), codePath, gridOrdering.first); /* Transformed grid */ TestReferenceChecker gridValuesChecker( checker.checkCompound("NonZeroGridValues", "ComplexSpaceGrid")); real gridValuesMagnitude = 1.0; for (const auto& point : nonZeroGridValuesOutput) { gridValuesMagnitude = std::max(std::fabs(point.second.re), gridValuesMagnitude); gridValuesMagnitude = std::max(std::fabs(point.second.im), gridValuesMagnitude); } // Spline moduli participate 3 times in the computation; 2 is an additional factor for SIMD exp() precision uint64_t gridUlpToleranceFactor = DIM * 2; if (method == PmeSolveAlgorithm::LennardJones) { // <NAME> is more complex and also uses erfc(), relax more gridUlpToleranceFactor *= 2; } const uint64_t splineModuliDoublePrecisionUlps = getSplineModuliDoublePrecisionUlps(inputRec.pme_order + 1); auto gridTolerance = relativeToleranceAsPrecisionDependentUlp( gridValuesMagnitude, gridUlpToleranceFactor * c_splineModuliSinglePrecisionUlps, gridUlpToleranceFactor * splineModuliDoublePrecisionUlps); gridValuesChecker.setDefaultTolerance(gridTolerance); for (const auto& point : nonZeroGridValuesOutput) { // we want an additional safeguard for denormal numbers as they cause an exception in string conversion; // however, using GMX_REAL_MIN causes an "unused item warning" for single precision builds if (fabs(point.second.re) >= GMX_FLOAT_MIN) { gridValuesChecker.checkReal(point.second.re, (point.first + " re").c_str()); } if (fabs(point.second.im) >= GMX_FLOAT_MIN) { gridValuesChecker.checkReal(point.second.im, (point.first + " im").c_str()); } } if (computeEnergyAndVirial) { // Extract the energy and virial const auto output = pmeGetReciprocalEnergyAndVirial(pmeSafe.get(), codePath, method); const auto& energy = (method == PmeSolveAlgorithm::Coulomb) ? output.coulombEnergy_ : output.lennardJonesEnergy_; const auto& virial = (method == PmeSolveAlgorithm::Coulomb) ? output.coulombVirial_ : output.lennardJonesVirial_; // These quantities are computed based on the grid values, so must have // checking relative tolerances at least as large. Virial needs more flops // than energy, so needs a larger tolerance. /* Energy */ double energyMagnitude = 10.0; // TODO This factor is arbitrary, do a proper error-propagation analysis uint64_t energyUlpToleranceFactor = gridUlpToleranceFactor * 2; auto energyTolerance = relativeToleranceAsPrecisionDependentUlp( energyMagnitude, energyUlpToleranceFactor * c_splineModuliSinglePrecisionUlps, energyUlpToleranceFactor * splineModuliDoublePrecisionUlps); TestReferenceChecker energyChecker(checker); energyChecker.setDefaultTolerance(energyTolerance); energyChecker.checkReal(energy, "Energy"); /* Virial */ double virialMagnitude = 1000.0; // TODO This factor is arbitrary, do a proper error-propagation analysis uint64_t virialUlpToleranceFactor = energyUlpToleranceFactor * 2; auto virialTolerance = relativeToleranceAsPrecisionDependentUlp( virialMagnitude, virialUlpToleranceFactor * c_splineModuliSinglePrecisionUlps, virialUlpToleranceFactor * splineModuliDoublePrecisionUlps); TestReferenceChecker virialChecker( checker.checkCompound("Matrix", "Virial")); virialChecker.setDefaultTolerance(virialTolerance); for (int i = 0; i < DIM; i++) { for (int j = 0; j <= i; j++) { std::string valueId = formatString("Cell %d %d", i, j); virialChecker.checkReal(virial[i][j], valueId.c_str()); } } } } } } } static std::vector<std::unique_ptr<PmeTestHardwareContext>> s_pmeTestHardwareContexts; }; std::vector<std::unique_ptr<PmeTestHardwareContext>> PmeSolveTest::s_pmeTestHardwareContexts; /*! \brief Test for PME solving */ TEST_P(PmeSolveTest, ReproducesOutputs) { EXPECT_NO_THROW_GMX(runTest()); } /* Valid input instances */ //! A couple of valid inputs for boxes. std::vector<Matrix3x3> const c_sampleBoxes{ // normal box Matrix3x3{ { 8.0F, 0.0F, 0.0F, 0.0F, 3.4F, 0.0F, 0.0F, 0.0F, 2.0F } }, // triclinic box Matrix3x3{ { 7.0F, 0.0F, 0.0F, 0.0F, 4.1F, 0.0F, 3.5F, 2.0F, 12.2F } }, }; //! A couple of valid inputs for grid sizes std::vector<IVec> const c_sampleGridSizes{ IVec{ 16, 12, 28 }, IVec{ 9, 7, 23 } }; //! Moved out from instantiations for readability const auto c_inputBoxes = ::testing::ValuesIn(c_sampleBoxes); //! Moved out from instantiations for readability const auto c_inputGridSizes = ::testing::ValuesIn(c_sampleGridSizes); //! 2 sample complex grids - only non-zero values have to be listed std::vector<SparseComplexGridValuesInput> const c_sampleGrids{ SparseComplexGridValuesInput{ { IVec{ 0, 0, 0 }, t_complex{ 3.5F, 6.7F } }, { IVec{ 7, 0, 0 }, t_complex{ -2.5F, -0.7F } }, { IVec{ 3, 5, 7 }, t_complex{ -0.006F, 1e-8F } }, { IVec{ 3, 1, 2 }, t_complex{ 0.6F, 7.9F } }, { IVec{ 6, 2, 4 }, t_complex{ 30.1F, 2.45F } }, }, SparseComplexGridValuesInput{ { IVec{ 0, 4, 0 }, t_complex{ 0.0F, 0.3F } }, { IVec{ 4, 2, 7 }, t_complex{ 13.76F, -40.0F } }, { IVec{ 0, 6, 7 }, t_complex{ 3.6F, 0.0F } }, { IVec{ 2, 5, 10 }, t_complex{ 3.6F, 10.65F } }, } }; //! Moved out from instantiations for readability const auto c_inputGrids = ::testing::ValuesIn(c_sampleGrids); //! Moved out from instantiations for readability const auto c_inputEpsilon_r = ::testing::Values(1.2); //! Moved out from instantiations for readability const auto c_inputEwaldCoeff_q = ::testing::Values(2.0); //! Moved out from instantiations for readability const auto c_inputEwaldCoeff_lj = ::testing::Values(0.7); //! Moved out from instantiations for readability const auto c_inputMethods = ::testing::Values(PmeSolveAlgorithm::Coulomb, PmeSolveAlgorithm::LennardJones); //! Instantiation of the PME solving test INSTANTIATE_TEST_SUITE_P(SaneInput, PmeSolveTest, ::testing::Combine(c_inputBoxes, c_inputGridSizes, c_inputGrids, c_inputEpsilon_r, c_inputEwaldCoeff_q, c_inputEwaldCoeff_lj, c_inputMethods)); //! A few more instances to check that different ewaldCoeff_q actually affects results of the Coulomb solver INSTANTIATE_TEST_SUITE_P(DifferentEwaldCoeffQ, PmeSolveTest, ::testing::Combine(c_inputBoxes, c_inputGridSizes, c_inputGrids, c_inputEpsilon_r, ::testing::Values(0.4), c_inputEwaldCoeff_lj, ::testing::Values(PmeSolveAlgorithm::Coulomb))); //! A few more instances to check that different ewaldCoeff_lj actually affects results of the Lennard-Jones solver. //! The value has to be approximately larger than 1 / (box dimensions) to have a meaningful output grid. //! Previous value of 0.3 caused one of the grid cells to be less or greater than GMX_FLOAT_MIN, depending on the architecture. INSTANTIATE_TEST_SUITE_P(DifferentEwaldCoeffLJ, PmeSolveTest, ::testing::Combine(c_inputBoxes, c_inputGridSizes, c_inputGrids, c_inputEpsilon_r, c_inputEwaldCoeff_q, ::testing::Values(2.35), ::testing::Values(PmeSolveAlgorithm::LennardJones))); //! A few more instances to check that different epsilon_r actually affects results of all solvers INSTANTIATE_TEST_SUITE_P(DifferentEpsilonR, PmeSolveTest, ::testing::Combine(c_inputBoxes, c_inputGridSizes, c_inputGrids, testing::Values(1.9), c_inputEwaldCoeff_q, c_inputEwaldCoeff_lj, c_inputMethods)); } // namespace } // namespace test } // namespace gmx <|start_filename|>api/legacy/include/gromacs/fileio/confio.h<|end_filename|> /* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 1991-2000, University of Groningen, The Netherlands. * Copyright (c) 2001-2004, The GROMACS development team. * Copyright (c) 2013,2014,2015,2016,2017 by the GROMACS development team. * Copyright (c) 2018,2019,2020,2021, by the GROMACS development team, led by * <NAME>, <NAME>, <NAME>, and <NAME>, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS 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. * * GROMACS 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 GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ #ifndef GMX_FILEIO_CONFIO_H #define GMX_FILEIO_CONFIO_H #include "gromacs/math/vectypes.h" #include "gromacs/utility/basedefinitions.h" /* For reading coordinate files it is assumed that enough memory * has been allocated beforehand. */ struct gmx_mtop_t; struct t_atoms; struct t_symtab; struct t_topology; enum class PbcType : int; void write_sto_conf_indexed(const char* outfile, const char* title, const t_atoms* atoms, const rvec x[], const rvec* v, PbcType pbcType, const matrix box, int nindex, int index[]); /* like write_sto_conf, but indexed */ void write_sto_conf(const char* outfile, const char* title, const t_atoms* atoms, const rvec x[], const rvec* v, PbcType pbcType, const matrix box); /* write atoms, x, v (if .gro and not NULL) and box (if not NULL) * to an STO (.gro or .pdb) file */ void write_sto_conf_mtop(const char* outfile, const char* title, const gmx_mtop_t& mtop, const rvec x[], const rvec* v, PbcType pbcType, const matrix box); /* As write_sto_conf, but uses a gmx_mtop_t struct */ /*! \brief Read a configuration and, when available, a topology from a tpr or structure file. * * When reading from a tpr file, the complete topology is returned in \p mtop. * When reading from a structure file, only the atoms struct in \p mtop contains data. * * \param[in] infile Input file name * \param[out] haveTopology true when a topology was read and stored in mtop * \param[out] mtop The topology, either complete or only atom data * \param[out] pbcType Enum reporting the type of PBC * \param[in,out] x Coordinates will be stored when *x!=NULL * \param[in,out] v Velocities will be stored when *v!=NULL * \param[out] box Box dimensions */ void readConfAndTopology(const char* infile, bool* haveTopology, gmx_mtop_t* mtop, PbcType* pbcType, rvec** x, rvec** v, matrix box); /*! \brief Read a configuration from a structure file. * * This should eventually be superseded by TopologyInformation * * \param[in] infile Input file name * \param[out] symtab The symbol table * \param[out] name The title of the molecule, e.g. from pdb TITLE record * \param[out] atoms The global t_atoms struct * \param[out] pbcType Enum reporting the type of PBC * \param[in,out] x Coordinates will be stored when *x!=NULL * \param[in,out] v Velocities will be stored when *v!=NULL * \param[out] box Box dimensions */ void readConfAndAtoms(const char* infile, t_symtab* symtab, char** name, t_atoms* atoms, PbcType* pbcType, rvec** x, rvec** v, matrix box); /*! \brief Read a configuration and, when available, a topology from a tpr or structure file. * * Deprecated, superseded by readConfAndTopology(). * When \p requireMasses = TRUE, this routine must return a topology with * mass data. Masses are either read from a tpr input file, or otherwise * looked up from the mass database, and when such lookup fails a fatal error * results. * When \p requireMasses = FALSE, masses will still be read from tpr input and * their presence is signaled with the \p haveMass flag in t_atoms of \p top. * * \param[in] infile Input file name * \param[out] top The topology, either complete or only atom data. Caller is * responsible for calling done_top(). * \param[out] pbcType Enum reporting the type of PBC * \param[in,out] x Coordinates will be stored when *x!=NULL * \param[in,out] v Velocities will be stored when *v!=NULL * \param[out] box Box dimensions * \param[in] requireMasses Require masses to be present, either from tpr or from the mass * database \returns if a topology is available */ gmx_bool read_tps_conf(const char* infile, struct t_topology* top, PbcType* pbcType, rvec** x, rvec** v, matrix box, gmx_bool requireMasses); #endif <|start_filename|>python_packaging/src/gmxapi/export_tprfile.cpp<|end_filename|> /* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2019,2020, by the GROMACS development team, led by * <NAME>, <NAME>, <NAME>, and <NAME>, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS 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. * * GROMACS 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 GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ /*! \file * \brief Exports TPR I/O tools during Python module initialization. * * Provides _gmxapi.SimulationParameters and _gmxapi.TprFile classes, as well * as module functions read_tprfile, write_tprfile, copy_tprfile, and rewrite_tprfile. * * TprFile is a Python object that holds a gmxapicompat::TprReadHandle. * * SimulationParameters is the Python type for data sources providing the * simulation parameters aspect of input to simulation operations. * * \author <NAME> <<EMAIL>> * \ingroup module_python */ #include "gmxapi/exceptions.h" #include "gmxapi/gmxapicompat.h" #include "gmxapi/compat/mdparams.h" #include "gmxapi/compat/tpr.h" #include "module.h" using gmxapi::GmxapiType; namespace gmxpy { void detail::export_tprfile(pybind11::module& module) { namespace py = pybind11; using gmxapicompat::GmxMdParams; using gmxapicompat::readTprFile; using gmxapicompat::TprReadHandle; py::class_<GmxMdParams> mdparams(module, "SimulationParameters"); // We don't want Python users to create invalid params objects, so don't // export a constructor until we can default initialize a valid one. // mdparams.def(py::init()); mdparams.def("extract", [](const GmxMdParams& self) { py::dict dictionary; for (const auto& key : gmxapicompat::keys(self)) { try { // TODO: More complete typing and dispatching. // This only handles the two types described in the initial implementation. // Less trivial types (strings, maps, arrays) warrant additional // design discussion before being exposed through an interface // like this one. // Also reference https://gitlab.com/gromacs/gromacs/-/issues/2993 // We can use templates and/or tag dispatch in a more complete // future implementation. const auto& paramType = gmxapicompat::mdParamToType(key); if (paramType == GmxapiType::FLOAT64) { dictionary[key.c_str()] = extractParam(self, key, double()); } else if (paramType == GmxapiType::INT64) { dictionary[key.c_str()] = extractParam(self, key, int64_t()); } } catch (const gmxapicompat::ValueError& e) { throw gmxapi::ProtocolError(std::string("Unknown parameter: ") + key); } } return dictionary; }, "Get a dictionary of the parameters."); // Overload a setter for each known type and None mdparams.def("set", [](GmxMdParams* self, const std::string& key, int64_t value) { gmxapicompat::setParam(self, key, value); }, py::arg("key").none(false), py::arg("value").none(false), "Use a dictionary to update simulation parameters."); mdparams.def("set", [](GmxMdParams* self, const std::string& key, double value) { gmxapicompat::setParam(self, key, value); }, py::arg("key").none(false), py::arg("value").none(false), "Use a dictionary to update simulation parameters."); mdparams.def("set", [](GmxMdParams* self, const std::string& key, py::none) { // unsetParam(self, key); }, py::arg("key").none(false), py::arg("value"), "Use a dictionary to update simulation parameters."); py::class_<TprReadHandle> tprfile(module, "TprFile"); tprfile.def("params", [](const TprReadHandle& self) { auto params = gmxapicompat::getMdParams(self); return params; }); module.def("read_tprfile", &readTprFile, py::arg("filename"), "Get a handle to a TPR file resource for a given file name."); module.def("write_tprfile", [](std::string filename, const GmxMdParams& parameterObject) { auto tprReadHandle = gmxapicompat::getSourceFileHandle(parameterObject); auto params = gmxapicompat::getMdParams(tprReadHandle); auto structure = gmxapicompat::getStructureSource(tprReadHandle); auto state = gmxapicompat::getSimulationState(tprReadHandle); auto topology = gmxapicompat::getTopologySource(tprReadHandle); gmxapicompat::writeTprFile(filename, *params, *structure, *state, *topology); }, py::arg("filename").none(false), py::arg("parameters"), "Write a new TPR file with the provided data."); module.def("copy_tprfile", [](const gmxapicompat::TprReadHandle& input, std::string outFile) { return gmxapicompat::copy_tprfile(input, outFile); }, py::arg("source"), py::arg("destination"), "Copy a TPR file from ``source`` to ``destination``."); module.def("rewrite_tprfile", [](std::string input, std::string output, double end_time) { return gmxapicompat::rewrite_tprfile(input, output, end_time); }, py::arg("source"), py::arg("destination"), py::arg("end_time"), "Copy a TPR file from ``source`` to ``destination``, replacing `nsteps` with " "``end_time``."); } } // end namespace gmxpy <|start_filename|>src/gromacs/utility/message_string_collector.cpp<|end_filename|> /* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2011,2012,2014,2016,2019,2021, by the GROMACS development team, led by * <NAME>, <NAME>, <NAME>, and <NAME>, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS 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. * * GROMACS 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 GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ /*! \internal \file * \brief * Implements gmx::MessageStringCollector. * * \author <NAME> <<EMAIL>> * \ingroup module_utility */ #include "gmxpre.h" #include "message_string_collector.h" #include <vector> #include "gromacs/utility/gmxassert.h" namespace gmx { class MessageStringCollector::Impl { public: Impl() : prevContext_(0) {} std::vector<std::string> contexts_; std::string text_; size_t prevContext_; }; MessageStringCollector::MessageStringCollector() : impl_(new Impl) {} MessageStringCollector::~MessageStringCollector() {} void MessageStringCollector::startContext(const char* name) { impl_->contexts_.emplace_back(name); } void MessageStringCollector::append(const std::string& message) { int indent = static_cast<int>(impl_->prevContext_ * 2); if (!impl_->contexts_.empty()) { std::vector<std::string>::const_iterator ci; for (ci = impl_->contexts_.begin() + impl_->prevContext_; ci != impl_->contexts_.end(); ++ci) { impl_->text_.append(indent, ' '); impl_->text_.append(*ci); impl_->text_.append("\n"); indent += 2; } } impl_->prevContext_ = impl_->contexts_.size(); // TODO: Put this into a more generic helper, could be useful elsewhere size_t pos = 0; while (pos < message.size()) { size_t nextpos = message.find_first_of('\n', pos); impl_->text_.append(indent, ' '); impl_->text_.append(message.substr(pos, nextpos - pos)); impl_->text_.append("\n"); if (nextpos == std::string::npos) { break; } pos = nextpos + 1; } } void MessageStringCollector::appendIf(bool condition, const char* message) { if (condition) { append(std::string(message)); } } void MessageStringCollector::appendIf(bool condition, const std::string& message) { if (condition) { append(message); } } void MessageStringCollector::finishContext() { GMX_RELEASE_ASSERT(!impl_->contexts_.empty(), "finishContext() called without context"); impl_->contexts_.pop_back(); if (impl_->prevContext_ > impl_->contexts_.size()) { impl_->prevContext_ = impl_->contexts_.size(); } } void MessageStringCollector::clear() { impl_->contexts_.clear(); impl_->text_.clear(); impl_->prevContext_ = 0; } bool MessageStringCollector::isEmpty() const { return impl_->text_.empty(); } std::string MessageStringCollector::toString() const { return impl_->text_; } } // namespace gmx <|start_filename|>api/nblib/listed_forces/tests/calculator.cpp<|end_filename|> /* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2020,2021, by the GROMACS development team, led by * <NAME>, <NAME>, <NAME>, and <NAME>, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS 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. * * GROMACS 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 GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ /*! \internal \file * \brief * This implements basic nblib utility tests * * \author <NAME> <<EMAIL>> * \author <NAME> <<EMAIL>> * \author <NAME> <<EMAIL>> * \author <NAME> <<EMAIL>> */ #include "gmxpre.h" // includesorter/check-source want this include here. IMO a bug #include <valarray> #include <gtest/gtest.h> #include "nblib/listed_forces/calculator.h" #include "nblib/listed_forces/dataflow.hpp" #include "nblib/listed_forces/tests/linear_chain_input.hpp" #include "nblib/tests/testhelpers.h" #include "testutils/refdata.h" #include "testutils/testasserts.h" namespace nblib { namespace test { namespace { TEST(NBlibTest, ListedForceCalculatorCanConstruct) { ListedInteractionData interactions; Box box(1, 1, 1); EXPECT_NO_THROW(ListedForceCalculator listedForceCalculator(interactions, 2, 1, box)); } template<class TestSeq, class SeqFloat, class SeqDouble> void compareVectors(const TestSeq& forces, [[maybe_unused]] const SeqFloat& refForcesFloat, [[maybe_unused]] const SeqDouble& refForcesDouble) { for (size_t i = 0; i < forces.size(); ++i) { for (int m = 0; m < dimSize; ++m) { EXPECT_FLOAT_DOUBLE_EQ_TOL( forces[i][m], refForcesFloat[i][m], refForcesDouble[i][m], // Todo: why does the tolerance need to be so low? gmx::test::relativeToleranceAsFloatingPoint(refForcesDouble[i][m], 5e-5)); } } } class ListedExampleData : public ::testing::Test { protected: void SetUp() override { // methanol-spc data HarmonicBondType bond1{ 376560, 0.136 }; HarmonicBondType bond2{ 313800, 0.1 }; std::vector<HarmonicBondType> bonds{ bond1, bond2 }; // one bond between atoms 0-1 with bond1 parameters and another between atoms 1-2 with bond2 parameters std::vector<InteractionIndex<HarmonicBondType>> bondIndices{ { 0, 1, 0 }, { 1, 2, 1 } }; HarmonicAngle angle(397.5, Degrees(108.53)); std::vector<HarmonicAngle> angles{ angle }; std::vector<InteractionIndex<HarmonicAngle>> angleIndices{ { 0, 1, 2, 0 } }; pickType<HarmonicBondType>(interactions).indices = bondIndices; pickType<HarmonicBondType>(interactions).parameters = bonds; pickType<HarmonicAngle>(interactions).indices = angleIndices; pickType<HarmonicAngle>(interactions).parameters = angles; // initial position for the methanol atoms from the spc-water example x = std::vector<gmx::RVec>{ { 1.97, 1.46, 1.209 }, { 1.978, 1.415, 1.082 }, { 1.905, 1.46, 1.03 } }; forces = std::vector<gmx::RVec>(3, gmx::RVec{ 0, 0, 0 }); box.reset(new Box(3, 3, 3)); pbc.reset(new PbcHolder(PbcType::Xyz, *box)); } std::vector<gmx::RVec> x; std::vector<gmx::RVec> forces; ListedInteractionData interactions; std::shared_ptr<Box> box; std::shared_ptr<PbcHolder> pbc; }; TEST_F(ListedExampleData, ComputeHarmonicBondForces) { gmx::ArrayRef<const InteractionIndex<HarmonicBondType>> indices = pickType<HarmonicBondType>(interactions).indices; gmx::ArrayRef<const HarmonicBondType> bonds = pickType<HarmonicBondType>(interactions).parameters; computeForces(indices, bonds, x, &forces, *pbc); RefDataChecker vector3DTest(1e-3); vector3DTest.testArrays<Vec3>(forces, "Bond forces"); } TEST_F(ListedExampleData, ComputeHarmonicBondEnergies) { gmx::ArrayRef<const InteractionIndex<HarmonicBondType>> indices = pickType<HarmonicBondType>(interactions).indices; gmx::ArrayRef<const HarmonicBondType> bonds = pickType<HarmonicBondType>(interactions).parameters; real energy = computeForces(indices, bonds, x, &forces, *pbc); RefDataChecker vector3DTest(1e-4); vector3DTest.testReal(energy, "Bond energy"); } TEST_F(ListedExampleData, ComputeHarmonicAngleForces) { gmx::ArrayRef<const InteractionIndex<HarmonicAngle>> indices = pickType<HarmonicAngle>(interactions).indices; gmx::ArrayRef<const HarmonicAngle> angles = pickType<HarmonicAngle>(interactions).parameters; computeForces(indices, angles, x, &forces, *pbc); RefDataChecker vector3DTest(1e-4); vector3DTest.testArrays<Vec3>(forces, "Angle forces"); } TEST_F(ListedExampleData, CanReduceForces) { reduceListedForces(interactions, x, &forces, *pbc); RefDataChecker vector3DTest(1e-2); vector3DTest.testArrays<Vec3>(forces, "Reduced forces"); } TEST_F(ListedExampleData, CanReduceEnergies) { auto energies = reduceListedForces(interactions, x, &forces, *pbc); real totalEnergy = std::accumulate(begin(energies), end(energies), 0.0); RefDataChecker vector3DTest(1e-4); vector3DTest.testReal(totalEnergy, "Reduced energy"); } void compareArray(const ListedForceCalculator::EnergyType& energies, const ListedForceCalculator::EnergyType& refEnergies) { for (size_t i = 0; i < energies.size(); ++i) { EXPECT_REAL_EQ_TOL(energies[i], refEnergies[i], gmx::test::relativeToleranceAsFloatingPoint(refEnergies[i], 1e-5)); } } //! \brief sets up an interaction tuple for a linear chain with nParticles class LinearChainDataFixture : public ::testing::Test { protected: void SetUp() override { LinearChainData data(430); x = data.x; interactions = data.interactions; box = data.box; refForces = data.forces; // pbc.reset(new PbcHolder(*box)); refEnergies = reduceListedForces(interactions, x, &refForces, NoPbc{}); } void testEnergies(const ListedForceCalculator::EnergyType& energies) const { compareArray(energies, refEnergies); } void testForces(const std::vector<gmx::RVec>& forces) const { compareVectors(forces, refForces, refForces); } std::vector<gmx::RVec> x; ListedInteractionData interactions; std::shared_ptr<Box> box; // std::shared_ptr<PbcHolder> pbc; private: std::vector<gmx::RVec> refForces; ListedForceCalculator::EnergyType refEnergies; }; TEST_F(LinearChainDataFixture, Multithreading) { ListedForceCalculator lfCalculator(interactions, x.size(), 4, *box); std::vector<Vec3> forces(x.size(), Vec3{ 0, 0, 0 }); ListedForceCalculator::EnergyType energies; lfCalculator.compute(x, forces, energies); testEnergies(energies); testForces(forces); } } // namespace } // namespace test } // namespace nblib <|start_filename|>src/gromacs/mdlib/update_constrain_gpu_impl.cpp<|end_filename|> /* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2019,2020,2021, by the GROMACS development team, led by * <NAME>, <NAME>, <NAME>, and <NAME>, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS 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. * * GROMACS 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 GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ /*! \internal \file * * \brief Implements update and constraints class. * * The class combines Leap-Frog integrator with LINCS and SETTLE constraints. * * \todo The computational procedures in members should be integrated to improve * computational performance. * * \author <NAME> <<EMAIL>> * * \ingroup module_mdlib */ #include "gmxpre.h" #include "update_constrain_gpu_impl.h" #include <assert.h> #include <stdio.h> #include <cmath> #include <algorithm> #include "gromacs/gpu_utils/device_context.h" #include "gromacs/gpu_utils/device_stream.h" #include "gromacs/gpu_utils/devicebuffer.h" #include "gromacs/gpu_utils/gpueventsynchronizer.h" #include "gromacs/gpu_utils/gputraits.h" #include "gromacs/mdlib/leapfrog_gpu.h" #include "gromacs/mdlib/update_constrain_gpu.h" #include "gromacs/mdlib/update_constrain_gpu_internal.h" #include "gromacs/mdtypes/mdatom.h" #include "gromacs/timing/wallcycle.h" #include "gromacs/topology/mtop_util.h" static constexpr bool sc_haveGpuConstraintSupport = GMX_GPU_CUDA; namespace gmx { void UpdateConstrainGpu::Impl::integrate(GpuEventSynchronizer* fReadyOnDevice, const real dt, const bool updateVelocities, const bool computeVirial, tensor virial, const bool doTemperatureScaling, gmx::ArrayRef<const t_grp_tcstat> tcstat, const bool doParrinelloRahman, const float dtPressureCouple, const matrix prVelocityScalingMatrix) { wallcycle_start_nocount(wcycle_, WallCycleCounter::LaunchGpu); wallcycle_sub_start(wcycle_, WallCycleSubCounter::LaunchGpuUpdateConstrain); // Clearing virial matrix // TODO There is no point in having separate virial matrix for constraints clear_mat(virial); // Make sure that the forces are ready on device before proceeding with the update. fReadyOnDevice->enqueueWaitEvent(deviceStream_); // The integrate should save a copy of the current coordinates in d_xp_ and write updated // once into d_x_. The d_xp_ is only needed by constraints. integrator_->integrate( d_x_, d_xp_, d_v_, d_f_, dt, doTemperatureScaling, tcstat, doParrinelloRahman, dtPressureCouple, prVelocityScalingMatrix); // Constraints need both coordinates before (d_x_) and after (d_xp_) update. However, after constraints // are applied, the d_x_ can be discarded. So we intentionally swap the d_x_ and d_xp_ here to avoid the // d_xp_ -> d_x_ copy after constraints. Note that the integrate saves them in the wrong order as well. if (sc_haveGpuConstraintSupport) { lincsGpu_->apply(d_xp_, d_x_, updateVelocities, d_v_, 1.0 / dt, computeVirial, virial, pbcAiuc_); settleGpu_->apply(d_xp_, d_x_, updateVelocities, d_v_, 1.0 / dt, computeVirial, virial, pbcAiuc_); } // scaledVirial -> virial (methods above returns scaled values) float scaleFactor = 0.5F / (dt * dt); for (int i = 0; i < DIM; i++) { for (int j = 0; j < DIM; j++) { virial[i][j] = scaleFactor * virial[i][j]; } } xUpdatedOnDeviceEvent_.markEvent(deviceStream_); wallcycle_sub_stop(wcycle_, WallCycleSubCounter::LaunchGpuUpdateConstrain); wallcycle_stop(wcycle_, WallCycleCounter::LaunchGpu); } void UpdateConstrainGpu::Impl::scaleCoordinates(const matrix scalingMatrix) { wallcycle_start_nocount(wcycle_, WallCycleCounter::LaunchGpu); wallcycle_sub_start(wcycle_, WallCycleSubCounter::LaunchGpuUpdateConstrain); ScalingMatrix mu(scalingMatrix); launchScaleCoordinatesKernel(numAtoms_, d_x_, mu, deviceStream_); wallcycle_sub_stop(wcycle_, WallCycleSubCounter::LaunchGpuUpdateConstrain); wallcycle_stop(wcycle_, WallCycleCounter::LaunchGpu); } void UpdateConstrainGpu::Impl::scaleVelocities(const matrix scalingMatrix) { wallcycle_start_nocount(wcycle_, WallCycleCounter::LaunchGpu); wallcycle_sub_start(wcycle_, WallCycleSubCounter::LaunchGpuUpdateConstrain); ScalingMatrix mu(scalingMatrix); launchScaleCoordinatesKernel(numAtoms_, d_v_, mu, deviceStream_); wallcycle_sub_stop(wcycle_, WallCycleSubCounter::LaunchGpuUpdateConstrain); wallcycle_stop(wcycle_, WallCycleCounter::LaunchGpu); } UpdateConstrainGpu::Impl::Impl(const t_inputrec& ir, const gmx_mtop_t& mtop, const int numTempScaleValues, const DeviceContext& deviceContext, const DeviceStream& deviceStream, gmx_wallcycle* wcycle) : deviceContext_(deviceContext), deviceStream_(deviceStream), wcycle_(wcycle) { integrator_ = std::make_unique<LeapFrogGpu>(deviceContext_, deviceStream_, numTempScaleValues); if (sc_haveGpuConstraintSupport) { lincsGpu_ = std::make_unique<LincsGpu>(ir.nLincsIter, ir.nProjOrder, deviceContext_, deviceStream_); settleGpu_ = std::make_unique<SettleGpu>(mtop, deviceContext_, deviceStream_); } } UpdateConstrainGpu::Impl::~Impl() {} void UpdateConstrainGpu::Impl::set(DeviceBuffer<Float3> d_x, DeviceBuffer<Float3> d_v, const DeviceBuffer<Float3> d_f, const InteractionDefinitions& idef, const t_mdatoms& md) { wallcycle_start_nocount(wcycle_, WallCycleCounter::LaunchGpu); wallcycle_sub_start(wcycle_, WallCycleSubCounter::LaunchGpuUpdateConstrain); GMX_ASSERT(d_x, "Coordinates device buffer should not be null."); GMX_ASSERT(d_v, "Velocities device buffer should not be null."); GMX_ASSERT(d_f, "Forces device buffer should not be null."); d_x_ = d_x; d_v_ = d_v; d_f_ = d_f; numAtoms_ = md.nr; reallocateDeviceBuffer(&d_xp_, numAtoms_, &numXp_, &numXpAlloc_, deviceContext_); reallocateDeviceBuffer( &d_inverseMasses_, numAtoms_, &numInverseMasses_, &numInverseMassesAlloc_, deviceContext_); // Integrator should also update something, but it does not even have a method yet integrator_->set(numAtoms_, md.invmass, md.cTC); if (sc_haveGpuConstraintSupport) { lincsGpu_->set(idef, numAtoms_, md.invmass); settleGpu_->set(idef); } else { GMX_ASSERT(idef.il[F_SETTLE].empty(), "SETTLE not supported"); GMX_ASSERT(idef.il[F_CONSTR].empty(), "LINCS not supported"); } wallcycle_sub_stop(wcycle_, WallCycleSubCounter::LaunchGpuUpdateConstrain); wallcycle_stop(wcycle_, WallCycleCounter::LaunchGpu); } void UpdateConstrainGpu::Impl::setPbc(const PbcType pbcType, const matrix box) { // TODO wallcycle setPbcAiuc(numPbcDimensions(pbcType), box, &pbcAiuc_); } GpuEventSynchronizer* UpdateConstrainGpu::Impl::xUpdatedOnDeviceEvent() { return &xUpdatedOnDeviceEvent_; } UpdateConstrainGpu::UpdateConstrainGpu(const t_inputrec& ir, const gmx_mtop_t& mtop, const int numTempScaleValues, const DeviceContext& deviceContext, const DeviceStream& deviceStream, gmx_wallcycle* wcycle) : impl_(new Impl(ir, mtop, numTempScaleValues, deviceContext, deviceStream, wcycle)) { } UpdateConstrainGpu::~UpdateConstrainGpu() = default; void UpdateConstrainGpu::integrate(GpuEventSynchronizer* fReadyOnDevice, const real dt, const bool updateVelocities, const bool computeVirial, tensor virialScaled, const bool doTemperatureScaling, gmx::ArrayRef<const t_grp_tcstat> tcstat, const bool doParrinelloRahman, const float dtPressureCouple, const matrix prVelocityScalingMatrix) { impl_->integrate(fReadyOnDevice, dt, updateVelocities, computeVirial, virialScaled, doTemperatureScaling, tcstat, doParrinelloRahman, dtPressureCouple, prVelocityScalingMatrix); } void UpdateConstrainGpu::scaleCoordinates(const matrix scalingMatrix) { impl_->scaleCoordinates(scalingMatrix); } void UpdateConstrainGpu::scaleVelocities(const matrix scalingMatrix) { impl_->scaleVelocities(scalingMatrix); } void UpdateConstrainGpu::set(DeviceBuffer<Float3> d_x, DeviceBuffer<Float3> d_v, const DeviceBuffer<Float3> d_f, const InteractionDefinitions& idef, const t_mdatoms& md) { impl_->set(d_x, d_v, d_f, idef, md); } void UpdateConstrainGpu::setPbc(const PbcType pbcType, const matrix box) { impl_->setPbc(pbcType, box); } GpuEventSynchronizer* UpdateConstrainGpu::xUpdatedOnDeviceEvent() { return impl_->xUpdatedOnDeviceEvent(); } bool UpdateConstrainGpu::isNumCoupledConstraintsSupported(const gmx_mtop_t& mtop) { return LincsGpu::isNumCoupledConstraintsSupported(mtop); } bool UpdateConstrainGpu::areConstraintsSupported() { return sc_haveGpuConstraintSupport; } } // namespace gmx <|start_filename|>cmake/gmxManageFFTLibraries.cmake<|end_filename|> # # This file is part of the GROMACS molecular simulation package. # # Copyright (c) 2012,2013,2014,2015,2016 by the GROMACS development team. # Copyright (c) 2017,2018,2019,2020,2021, by the GROMACS development team, led by # <NAME>, <NAME>, <NAME>, and <NAME>, # and including many others, as listed in the AUTHORS file in the # top-level source directory and at http://www.gromacs.org. # # GROMACS 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. # # GROMACS 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 GROMACS; if not, see # http://www.gnu.org/licenses, or write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # If you want to redistribute modifications to GROMACS, please # consider that scientific software is very special. Version # control is crucial - bugs must be traceable. We will be happy to # consider code for inclusion in the official distribution, but # derived work must not be called official GROMACS. Details are found # in the README & COPYING files - if they are missing, get the # official version at http://www.gromacs.org. # # To help us fund GROMACS development, we humbly ask that you cite # the research papers on the package. Check out http://www.gromacs.org. # Manage setup of the different FFT libraries we can use in Gromacs. set(PKG_FFT "") set(PKG_FFT_LIBS "") # Intel 11 and up makes life somewhat easy if you just want to use # all their stuff. It's not easy if you only want some of their # stuff... set(MKL_MANUALLY FALSE) if (GMX_FFT_LIBRARY STREQUAL "MKL" AND NOT GMX_INTEL_LLVM) # The user will have to provide the set of magic libraries in # MKL_LIBRARIES (see below), which we cache (non-advanced), so that they # don't have to keep specifying it, and can easily see that # CMake is still using that information. set(MKL_MANUALLY TRUE) endif() set(MKL_LIBRARIES_FORMAT_DESCRIPTION "Use full paths to library files, in the right order, and separated by semicolons.") gmx_dependent_cache_variable( MKL_LIBRARIES "List of libraries for linking to MKL. ${MKL_LIBRARIES_FORMAT_DESCRIPTION}" STRING "" MKL_MANUALLY) gmx_dependent_cache_variable( MKL_INCLUDE_DIR "Path to mkl.h (non-inclusive)." PATH "" MKL_MANUALLY) if(${GMX_FFT_LIBRARY} STREQUAL "FFTW3") # ${FFTW} must be in upper case if(GMX_DOUBLE) set(FFTW "FFTW") else() set(FFTW "FFTWF") endif() if(GMX_BUILD_OWN_FFTW) if(MSVC) message(FATAL_ERROR "Cannot build FFTW3 automatically (GMX_BUILD_OWN_FFTW=ON) in Visual Studio") endif() if(CMAKE_GENERATOR STREQUAL "Ninja") message(FATAL_ERROR "Cannot build FFTW3 automatically (GMX_BUILD_OWN_FFTW=ON) with ninja") endif() add_subdirectory(src/external/build-fftw) include_directories(BEFORE ${${FFTW}_INCLUDE_DIRS}) # libgmxfftw is always built static, so libgromacs does not # have a dependency on anything, so PKG_FFT should be empty set(PKG_FFT "") set(FFT_STATUS_MESSAGE "Using external FFT library - FFTW3 build managed by GROMACS") else() string(TOLOWER "${FFTW}" LOWERFFTW) find_package(FFTW COMPONENTS ${LOWERFFTW}) if(NOT ${FFTW}_FOUND) MESSAGE(FATAL_ERROR "Cannot find FFTW 3 (with correct precision - libfftw3f for mixed-precision GROMACS or libfftw3 for double-precision GROMACS). Either choose the right precision, choose another FFT(W) library (-DGMX_FFT_LIBRARY), enable the advanced option to let GROMACS build FFTW 3 for you (-DGMX_BUILD_OWN_FFTW=ON), or use the really slow GROMACS built-in fftpack library (-DGMX_FFT_LIBRARY=fftpack).") endif() set(PKG_FFT "${${FFTW}_PKG}") include_directories(SYSTEM ${${FFTW}_INCLUDE_DIRS}) if(NOT WIN32) # Detection doesn't work on Windows if ((${GMX_SIMD_ACTIVE} MATCHES "SSE" OR ${GMX_SIMD_ACTIVE} MATCHES "AVX") AND NOT ${FFTW}_HAVE_SIMD) set(FFT_WARNING_MESSAGE "The fftw library found is compiled without SIMD support, which makes it slow. Consider recompiling it or contact your admin") else() if(${GMX_SIMD_ACTIVE} MATCHES "AVX" AND NOT (${FFTW}_HAVE_SSE OR ${FFTW}_HAVE_SSE2)) # If we end up here we have an AVX Gromacs build, and # FFTW with SIMD. set(FFT_WARNING_MESSAGE "The FFTW library was compiled with neither --enable-sse nor --enable-sse2; those would have enabled SSE(2) SIMD instructions. This will give suboptimal performance. You should (re)compile the FFTW library with --enable-sse2 and --enable-avx (and --enable-avx2 or --enable-avx512 if supported).") endif() endif() endif() find_path(ARMPL_INCLUDE_DIR "armpl.h" HINTS ${${FFTW}_INCLUDE_DIRS} NO_DEFAULT_PATH NO_CMAKE_ENVIRONMENT_PATH NO_CMAKE_PATH NO_SYSTEM_ENVIRONMENT_PATH NO_CMAKE_SYSTEM_PATH) mark_as_advanced(ARMPL_INCLUDE_DIR) if (ARMPL_INCLUDE_DIR) set(GMX_FFT_ARMPL_FFTW3 1) set(FFT_STATUS_MESSAGE "Using external FFT library - ARM Performance Library (FFTW3 compatibility mode)") else() set(FFT_STATUS_MESSAGE "Using external FFT library - FFTW3") endif() endif() if (NOT GMX_FFT_ARMPL_FFTW3) set(GMX_FFT_FFTW3 1) endif() set(FFT_LIBRARIES ${${FFTW}_LIBRARIES}) elseif(${GMX_FFT_LIBRARY} STREQUAL "MKL") # Intel compilers make life somewhat easy if you just want to use # all their stuff. It's not easy if you only want some of their # stuff... if (NOT MKL_MANUALLY) # The next line takes care of everything for MKL if (WIN32) # This works according to the Intel MKL 10.3 for Windows # docs, but on Jenkins Win2k8, icl tries to interpret it # as a file. Shrug. set(FFT_LINKER_FLAGS "/Qmkl:sequential") elseif(GMX_INTEL_LLVM AND GMX_INTEL_LLVM_VERSION GREATER_EQUAL 2021020) set(FFT_LINKER_FLAGS "-qmkl=sequential") else() set(FFT_LINKER_FLAGS "-mkl=sequential") endif() # Some versions of icc require this in order that mkl.h can be # found at compile time. list(APPEND EXTRA_C_FLAGS ${FFT_LINKER_FLAGS}) list(APPEND EXTRA_CXX_FLAGS ${FFT_LINKER_FLAGS}) set(MKL_ERROR_MESSAGE "Make sure you have configured your compiler so that ${FFT_LINKER_FLAGS} will work.") else() include_directories(SYSTEM ${MKL_INCLUDE_DIR}) set(FFT_LIBRARIES "${MKL_LIBRARIES}") set(MKL_ERROR_MESSAGE "The include path to mkl.h in MKL_INCLUDE_DIR, and the link libraries in MKL_LIBRARIES=${MKL_LIBRARIES} need to match what the MKL documentation says you need for your system: ${MKL_LIBRARIES_FORMAT_DESCRIPTION}") # Convert the semi-colon separated list to a list of # command-line linker arguments so that code using our # pkgconfig setup can use it. string(REGEX REPLACE ";" " " PKG_FFT_LIBS "${MKL_LIBRARIES}") endif() # Check MKL works. If we were in a non-global scope, we wouldn't # have to play nicely. set(old_CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS}") set(CMAKE_REQUIRED_FLAGS "${FFT_LINKER_FLAGS}") set(old_CMAKE_REQUIRED_LIBRARIES "${CMAKE_REQUIRED_LIBRARIES}") set(CMAKE_REQUIRED_LIBRARIES "${FFT_LIBRARIES}") check_function_exists(DftiCreateDescriptor TEST_MKL) set(CMAKE_REQUIRED_FLAGS "${old_CMAKE_REQUIRED_FLAGS}") set(CMAKE_REQUIRED_LIBRARIES "${old_CMAKE_REQUIRED_LIBRARIES}") if(NOT TEST_MKL) # Hack to help the user vary MKL settings until they work. # TODO Make this logic more useful. unset(TEST_MKL CACHE) message(FATAL_ERROR "Linking with MKL was requested, but was not successful: ${MKL_ERROR_MESSAGE}") endif() # Set variables to signal that we have MKL available and should use it for FFTs. set(GMX_FFT_MKL 1) set(HAVE_LIBMKL 1) set(FFT_STATUS_MESSAGE "Using external FFT library - Intel MKL") elseif(${GMX_FFT_LIBRARY} STREQUAL "FFTPACK") set(GMX_FFT_FFTPACK 1) set(FFT_STATUS_MESSAGE "Using internal FFT library - fftpack") else() gmx_invalid_option_value(GMX_FFT_LIBRARY) endif() gmx_check_if_changed(FFT_CHANGED GMX_FFT_LIBRARY) if (FFT_CHANGED) if(FFT_WARNING_MESSAGE) message(WARNING "${FFT_WARNING_MESSAGE}") endif() message(STATUS "${FFT_STATUS_MESSAGE}") endif() # enable threaded fftw3 if we've found it if(FFTW3_THREADS OR FFTW3F_THREADS) add_definitions(-DFFT5D_FFTW_THREADS) endif() <|start_filename|>cmake/gmxManageCP2K.cmake<|end_filename|> # # This file is part of the GROMACS molecular simulation package. # # Copyright (c) 2021, by the GROMACS development team, led by # <NAME>, <NAME>, <NAME>, and <NAME>, # and including many others, as listed in the AUTHORS file in the # top-level source directory and at http://www.gromacs.org. # # GROMACS 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. # # GROMACS 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 GROMACS; if not, see # http://www.gnu.org/licenses, or write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # If you want to redistribute modifications to GROMACS, please # consider that scientific software is very special. Version # control is crucial - bugs must be traceable. We will be happy to # consider code for inclusion in the official distribution, but # derived work must not be called official GROMACS. Details are found # in the README & COPYING files - if they are missing, get the # official version at http://www.gromacs.org. # # To help us fund GROMACS development, we humbly ask that you cite # the research papers on the package. Check out http://www.gromacs.org. if(GMX_CP2K) # Check that all necessary CMake flags are present set(CP2K_DIR "" CACHE STRING "Path to the directory with libcp2k.a library") set(CP2K_LINKER_FLAGS "" CACHE STRING "List of flags and libraries required for linking libcp2k. Typically this should be combination of LDFLAGS and LIBS variables from ARCH file used to compile CP2K") if ((CP2K_DIR STREQUAL "") OR (CP2K_LINKER_FLAGS STREQUAL "")) message(FATAL_ERROR "To build GROMACS with CP2K Interface both CP2K_DIR and CP2K_LINKER_FLAGS should be defined") endif() # Add directory with libcp2k.h into system include directories include_directories(SYSTEM "${CP2K_DIR}/../../../src/start") # Add libcp2k and DBCSR for linking set(CMAKE_CXX_STANDARD_LIBRARIES "${CMAKE_CXX_STANDARD_LIBRARIES} -Wl,--allow-multiple-definition -L${CP2K_DIR} -lcp2k -L${CP2K_DIR}/exts/dbcsr -ldbcsr") # Add User provided libraries set(CMAKE_CXX_STANDARD_LIBRARIES "${CMAKE_CXX_STANDARD_LIBRARIES} ${CP2K_LINKER_FLAGS}") # If we use GNU compilers then also libgfortran should be linked if (CMAKE_CXX_COMPILER_ID STREQUAL "GNU") set(CMAKE_CXX_STANDARD_LIBRARIES "${CMAKE_CXX_STANDARD_LIBRARIES} -lgfortran") endif() # If we use external MPI then Fortran MPI library should be linked if (GMX_LIB_MPI) # If Fortran MPI library is found then add it to GMX_COMMON_LIBRARIES if (MPI_Fortran_FOUND) list(APPEND GMX_COMMON_LIBRARIES ${MPI_Fortran_LIBRARIES}) else() message(FATAL_ERROR "Could not find Fortran MPI library which is required for CP2K") endif() endif() endif() <|start_filename|>src/gromacs/mdlib/mdoutf.cpp<|end_filename|> /* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2013,2014,2015,2016,2017 The GROMACS development team. * Copyright (c) 2018,2019,2020,2021, by the GROMACS development team, led by * <NAME>, <NAME>, <NAME>, and <NAME>, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS 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. * * GROMACS 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 GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ #include "gmxpre.h" #include "mdoutf.h" #include "config.h" #include "gromacs/commandline/filenm.h" #include "gromacs/domdec/collect.h" #include "gromacs/domdec/domdec_struct.h" #include "gromacs/fileio/checkpoint.h" #include "gromacs/fileio/gmxfio.h" #include "gromacs/fileio/tngio.h" #include "gromacs/fileio/trrio.h" #include "gromacs/fileio/xtcio.h" #include "gromacs/math/vec.h" #include "gromacs/mdlib/energyoutput.h" #include "gromacs/mdrunutility/handlerestart.h" #include "gromacs/mdrunutility/multisim.h" #include "gromacs/mdtypes/awh_history.h" #include "gromacs/mdtypes/commrec.h" #include "gromacs/mdtypes/edsamhistory.h" #include "gromacs/mdtypes/energyhistory.h" #include "gromacs/mdtypes/imdoutputprovider.h" #include "gromacs/mdtypes/inputrec.h" #include "gromacs/mdtypes/md_enums.h" #include "gromacs/mdtypes/mdrunoptions.h" #include "gromacs/mdtypes/observableshistory.h" #include "gromacs/mdtypes/state.h" #include "gromacs/mdtypes/swaphistory.h" #include "gromacs/timing/wallcycle.h" #include "gromacs/topology/topology.h" #include "gromacs/utility/baseversion.h" #include "gromacs/utility/fatalerror.h" #include "gromacs/utility/pleasecite.h" #include "gromacs/utility/programcontext.h" #include "gromacs/utility/smalloc.h" #include "gromacs/utility/sysinfo.h" struct gmx_mdoutf { t_fileio* fp_trn; t_fileio* fp_xtc; gmx_tng_trajectory_t tng; gmx_tng_trajectory_t tng_low_prec; int x_compression_precision; /* only used by XTC output */ ener_file_t fp_ene; const char* fn_cpt; gmx_bool bKeepAndNumCPT; IntegrationAlgorithm eIntegrator; gmx_bool bExpanded; LambdaWeightCalculation elamstats; int simulation_part; FILE* fp_dhdl; int natoms_global; int natoms_x_compressed; const SimulationGroups* groups; /* for compressed position writing */ gmx_wallcycle* wcycle; rvec* f_global; gmx::IMDOutputProvider* outputProvider; const gmx::MDModulesNotifiers* mdModulesNotifiers; bool simulationsShareState; MPI_Comm mastersComm; }; gmx_mdoutf_t init_mdoutf(FILE* fplog, int nfile, const t_filenm fnm[], const gmx::MdrunOptions& mdrunOptions, const t_commrec* cr, gmx::IMDOutputProvider* outputProvider, const gmx::MDModulesNotifiers& mdModulesNotifiers, const t_inputrec* ir, const gmx_mtop_t& top_global, const gmx_output_env_t* oenv, gmx_wallcycle* wcycle, const gmx::StartingBehavior startingBehavior, bool simulationsShareState, const gmx_multisim_t* ms) { gmx_mdoutf_t of; const char * appendMode = "a+", *writeMode = "w+", *filemode; gmx_bool bCiteTng = FALSE; int i; bool restartWithAppending = (startingBehavior == gmx::StartingBehavior::RestartWithAppending); snew(of, 1); of->fp_trn = nullptr; of->fp_ene = nullptr; of->fp_xtc = nullptr; of->tng = nullptr; of->tng_low_prec = nullptr; of->fp_dhdl = nullptr; of->eIntegrator = ir->eI; of->bExpanded = ir->bExpanded; of->elamstats = ir->expandedvals->elamstats; of->simulation_part = ir->simulation_part; of->x_compression_precision = static_cast<int>(ir->x_compression_precision); of->wcycle = wcycle; of->f_global = nullptr; of->outputProvider = outputProvider; GMX_RELEASE_ASSERT(!simulationsShareState || ms != nullptr, "Need valid multisim object when simulations share state"); of->simulationsShareState = simulationsShareState; if (of->simulationsShareState) { of->mastersComm = ms->mastersComm_; } if (MASTER(cr)) { of->bKeepAndNumCPT = mdrunOptions.checkpointOptions.keepAndNumberCheckpointFiles; filemode = restartWithAppending ? appendMode : writeMode; if (EI_DYNAMICS(ir->eI) && ir->nstxout_compressed > 0) { const char* filename; filename = ftp2fn(efCOMPRESSED, nfile, fnm); switch (fn2ftp(filename)) { case efXTC: of->fp_xtc = open_xtc(filename, filemode); break; case efTNG: gmx_tng_open(filename, filemode[0], &of->tng_low_prec); if (filemode[0] == 'w') { gmx_tng_prepare_low_prec_writing(of->tng_low_prec, &top_global, ir); } bCiteTng = TRUE; break; default: gmx_incons("Invalid reduced precision file format"); } } if ((EI_DYNAMICS(ir->eI) || EI_ENERGY_MINIMIZATION(ir->eI)) && (!GMX_FAHCORE && !(EI_DYNAMICS(ir->eI) && ir->nstxout == 0 && ir->nstvout == 0 && ir->nstfout == 0))) { const char* filename; filename = ftp2fn(efTRN, nfile, fnm); switch (fn2ftp(filename)) { case efTRR: case efTRN: /* If there is no uncompressed coordinate output and there is compressed TNG output write forces and/or velocities to the TNG file instead. */ if (ir->nstxout != 0 || ir->nstxout_compressed == 0 || !of->tng_low_prec) { of->fp_trn = gmx_trr_open(filename, filemode); } break; case efTNG: gmx_tng_open(filename, filemode[0], &of->tng); if (filemode[0] == 'w') { gmx_tng_prepare_md_writing(of->tng, &top_global, ir); } bCiteTng = TRUE; break; default: gmx_incons("Invalid full precision file format"); } } if (EI_DYNAMICS(ir->eI) || EI_ENERGY_MINIMIZATION(ir->eI)) { of->fp_ene = open_enx(ftp2fn(efEDR, nfile, fnm), filemode); } of->fn_cpt = opt2fn("-cpo", nfile, fnm); if ((ir->efep != FreeEnergyPerturbationType::No || ir->bSimTemp) && ir->fepvals->nstdhdl > 0 && (ir->fepvals->separate_dhdl_file == SeparateDhdlFile::Yes) && EI_DYNAMICS(ir->eI)) { if (restartWithAppending) { of->fp_dhdl = gmx_fio_fopen(opt2fn("-dhdl", nfile, fnm), filemode); } else { of->fp_dhdl = open_dhdl(opt2fn("-dhdl", nfile, fnm), ir, oenv); } } outputProvider->initOutput(fplog, nfile, fnm, restartWithAppending, oenv); of->mdModulesNotifiers = &mdModulesNotifiers; /* Set up atom counts so they can be passed to actual trajectory-writing routines later. Also, XTC writing needs to know what (and how many) atoms might be in the XTC groups, and how to look up later which ones they are. */ of->natoms_global = top_global.natoms; of->groups = &top_global.groups; of->natoms_x_compressed = 0; for (i = 0; (i < top_global.natoms); i++) { if (getGroupType(*of->groups, SimulationAtomGroupType::CompressedPositionOutput, i) == 0) { of->natoms_x_compressed++; } } if (ir->nstfout && haveDDAtomOrdering(*cr)) { snew(of->f_global, top_global.natoms); } } if (bCiteTng) { please_cite(fplog, "Lundborg2014"); } return of; } ener_file_t mdoutf_get_fp_ene(gmx_mdoutf_t of) { return of->fp_ene; } FILE* mdoutf_get_fp_dhdl(gmx_mdoutf_t of) { return of->fp_dhdl; } gmx_wallcycle* mdoutf_get_wcycle(gmx_mdoutf_t of) { return of->wcycle; } static void mpiBarrierBeforeRename(const bool applyMpiBarrierBeforeRename, MPI_Comm mpiBarrierCommunicator) { if (applyMpiBarrierBeforeRename) { #if GMX_MPI MPI_Barrier(mpiBarrierCommunicator); #else GMX_RELEASE_ASSERT(false, "Should not request a barrier without MPI"); GMX_UNUSED_VALUE(mpiBarrierCommunicator); #endif } } /*! \brief Write a checkpoint to the filename * * Appends the _step<step>.cpt with bNumberAndKeep, otherwise moves * the previous checkpoint filename with suffix _prev.cpt. */ static void write_checkpoint(const char* fn, gmx_bool bNumberAndKeep, FILE* fplog, const t_commrec* cr, ivec domdecCells, int nppnodes, IntegrationAlgorithm eIntegrator, int simulation_part, gmx_bool bExpanded, LambdaWeightCalculation elamstats, int64_t step, double t, t_state* state, ObservablesHistory* observablesHistory, const gmx::MDModulesNotifiers& mdModulesNotifiers, gmx::WriteCheckpointDataHolder* modularSimulatorCheckpointData, bool applyMpiBarrierBeforeRename, MPI_Comm mpiBarrierCommunicator) { t_fileio* fp; char* fntemp; /* the temporary checkpoint file name */ int npmenodes; char buf[1024], suffix[5 + STEPSTRSIZE], sbuf[STEPSTRSIZE]; t_fileio* ret; if (haveDDAtomOrdering(*cr)) { npmenodes = cr->npmenodes; } else { npmenodes = 0; } #if !GMX_NO_RENAME /* make the new temporary filename */ snew(fntemp, std::strlen(fn) + 5 + STEPSTRSIZE); std::strcpy(fntemp, fn); fntemp[std::strlen(fn) - std::strlen(ftp2ext(fn2ftp(fn))) - 1] = '\0'; sprintf(suffix, "_%s%s", "step", gmx_step_str(step, sbuf)); std::strcat(fntemp, suffix); std::strcat(fntemp, fn + std::strlen(fn) - std::strlen(ftp2ext(fn2ftp(fn))) - 1); #else /* if we can't rename, we just overwrite the cpt file. * dangerous if interrupted. */ snew(fntemp, std::strlen(fn)); std::strcpy(fntemp, fn); #endif std::string timebuf = gmx_format_current_time(); if (fplog) { fprintf(fplog, "Writing checkpoint, step %s at %s\n\n", gmx_step_str(step, buf), timebuf.c_str()); } /* Get offsets for open files */ auto outputfiles = gmx_fio_get_output_file_positions(); fp = gmx_fio_open(fntemp, "w"); /* We can check many more things now (CPU, acceleration, etc), but * it is highly unlikely to have two separate builds with exactly * the same version, user, time, and build host! */ int nlambda = (state->dfhist ? state->dfhist->nlambda : 0); edsamhistory_t* edsamhist = observablesHistory->edsamHistory.get(); int nED = (edsamhist ? edsamhist->nED : 0); swaphistory_t* swaphist = observablesHistory->swapHistory.get(); SwapType eSwapCoords = (swaphist ? swaphist->eSwapCoords : SwapType::No); CheckpointHeaderContents headerContents = { CheckPointVersion::UnknownVersion0, { 0 }, { 0 }, { 0 }, { 0 }, GMX_DOUBLE, { 0 }, { 0 }, eIntegrator, simulation_part, step, t, nppnodes, { 0 }, npmenodes, state->natoms, state->ngtc, state->nnhpres, state->nhchainlength, nlambda, state->flags, 0, 0, 0, 0, 0, nED, eSwapCoords, false }; std::strcpy(headerContents.version, gmx_version()); std::strcpy(headerContents.fprog, gmx::getProgramContext().fullBinaryPath()); std::strcpy(headerContents.ftime, timebuf.c_str()); if (haveDDAtomOrdering(*cr)) { copy_ivec(domdecCells, headerContents.dd_nc); } write_checkpoint_data(fp, headerContents, bExpanded, elamstats, state, observablesHistory, mdModulesNotifiers, &outputfiles, modularSimulatorCheckpointData); /* we really, REALLY, want to make sure to physically write the checkpoint, and all the files it depends on, out to disk. Because we've opened the checkpoint with gmx_fio_open(), it's in our list of open files. */ ret = gmx_fio_all_output_fsync(); if (ret) { char buf[STRLEN]; sprintf(buf, "Cannot fsync '%s'; maybe you are out of disk space?", gmx_fio_getname(ret)); if (getenv(GMX_IGNORE_FSYNC_FAILURE_ENV) == nullptr) { gmx_file(buf); } else { gmx_warning("%s", buf); } } if (gmx_fio_close(fp) != 0) { gmx_file("Cannot read/write checkpoint; corrupt file, or maybe you are out of disk space?"); } /* we don't move the checkpoint if the user specified they didn't want it, or if the fsyncs failed */ #if !GMX_NO_RENAME if (!bNumberAndKeep && !ret) { // Add a barrier before renaming to reduce chance to get out of sync (#2440) // Note: Checkpoint might only exist on some ranks, so put barrier before if clause (#3919) mpiBarrierBeforeRename(applyMpiBarrierBeforeRename, mpiBarrierCommunicator); if (gmx_fexist(fn)) { /* Rename the previous checkpoint file */ std::strcpy(buf, fn); buf[std::strlen(fn) - std::strlen(ftp2ext(fn2ftp(fn))) - 1] = '\0'; std::strcat(buf, "_prev"); std::strcat(buf, fn + std::strlen(fn) - std::strlen(ftp2ext(fn2ftp(fn))) - 1); if (!GMX_FAHCORE) { /* we copy here so that if something goes wrong between now and * the rename below, there's always a state.cpt. * If renames are atomic (such as in POSIX systems), * this copying should be unneccesary. */ gmx_file_copy(fn, buf, FALSE); /* We don't really care if this fails: * there's already a new checkpoint. */ } else { gmx_file_rename(fn, buf); } } /* Rename the checkpoint file from the temporary to the final name */ mpiBarrierBeforeRename(applyMpiBarrierBeforeRename, mpiBarrierCommunicator); if (gmx_file_rename(fntemp, fn) != 0) { gmx_file("Cannot rename checkpoint file; maybe you are out of disk space?"); } } #endif /* GMX_NO_RENAME */ sfree(fntemp); #if GMX_FAHCORE /* Always FAH checkpoint immediately after a GROMACS checkpoint. * * Note that it is critical that we save a FAH checkpoint directly * after writing a GROMACS checkpoint. If the program dies, either * by the machine powering off suddenly or the process being, * killed, FAH can recover files that have only appended data by * truncating them to the last recorded length. The GROMACS * checkpoint does not just append data, it is fully rewritten each * time so a crash between moving the new Gromacs checkpoint file in * to place and writing a FAH checkpoint is not recoverable. Thus * the time between these operations must be kept as short as * possible. */ fcCheckpoint(); #endif /* end GMX_FAHCORE block */ } void mdoutf_write_checkpoint(gmx_mdoutf_t of, FILE* fplog, const t_commrec* cr, int64_t step, double t, t_state* state_global, ObservablesHistory* observablesHistory, gmx::WriteCheckpointDataHolder* modularSimulatorCheckpointData) { fflush_tng(of->tng); fflush_tng(of->tng_low_prec); /* Write the checkpoint file. * When simulations share the state, an MPI barrier is applied before * renaming old and new checkpoint files to minimize the risk of * checkpoint files getting out of sync. */ ivec one_ivec = { 1, 1, 1 }; write_checkpoint(of->fn_cpt, of->bKeepAndNumCPT, fplog, cr, haveDDAtomOrdering(*cr) ? cr->dd->numCells : one_ivec, haveDDAtomOrdering(*cr) ? cr->dd->nnodes : cr->nnodes, of->eIntegrator, of->simulation_part, of->bExpanded, of->elamstats, step, t, state_global, observablesHistory, *(of->mdModulesNotifiers), modularSimulatorCheckpointData, of->simulationsShareState, of->mastersComm); } void mdoutf_write_to_trajectory_files(FILE* fplog, const t_commrec* cr, gmx_mdoutf_t of, int mdof_flags, int natoms, int64_t step, double t, t_state* state_local, t_state* state_global, ObservablesHistory* observablesHistory, gmx::ArrayRef<const gmx::RVec> f_local, gmx::WriteCheckpointDataHolder* modularSimulatorCheckpointData) { const rvec* f_global; if (haveDDAtomOrdering(*cr)) { if (mdof_flags & MDOF_CPT) { dd_collect_state(cr->dd, state_local, state_global); } else { if (mdof_flags & (MDOF_X | MDOF_X_COMPRESSED)) { auto globalXRef = MASTER(cr) ? state_global->x : gmx::ArrayRef<gmx::RVec>(); dd_collect_vec(cr->dd, state_local->ddp_count, state_local->ddp_count_cg_gl, state_local->cg_gl, state_local->x, globalXRef); } if (mdof_flags & MDOF_V) { auto globalVRef = MASTER(cr) ? state_global->v : gmx::ArrayRef<gmx::RVec>(); dd_collect_vec(cr->dd, state_local->ddp_count, state_local->ddp_count_cg_gl, state_local->cg_gl, state_local->v, globalVRef); } } f_global = of->f_global; if (mdof_flags & MDOF_F) { auto globalFRef = MASTER(cr) ? gmx::arrayRefFromArray( reinterpret_cast<gmx::RVec*>(of->f_global), of->natoms_global) : gmx::ArrayRef<gmx::RVec>(); dd_collect_vec(cr->dd, state_local->ddp_count, state_local->ddp_count_cg_gl, state_local->cg_gl, f_local, globalFRef); } } else { /* We have the whole state locally: copy the local state pointer */ state_global = state_local; f_global = as_rvec_array(f_local.data()); } if (MASTER(cr)) { if (mdof_flags & MDOF_CPT) { mdoutf_write_checkpoint( of, fplog, cr, step, t, state_global, observablesHistory, modularSimulatorCheckpointData); } if (mdof_flags & (MDOF_X | MDOF_V | MDOF_F)) { const rvec* x = (mdof_flags & MDOF_X) ? state_global->x.rvec_array() : nullptr; const rvec* v = (mdof_flags & MDOF_V) ? state_global->v.rvec_array() : nullptr; const rvec* f = (mdof_flags & MDOF_F) ? f_global : nullptr; if (of->fp_trn) { gmx_trr_write_frame(of->fp_trn, step, t, state_local->lambda[FreeEnergyPerturbationCouplingType::Fep], state_local->box, natoms, x, v, f); if (gmx_fio_flush(of->fp_trn) != 0) { gmx_file("Cannot write trajectory; maybe you are out of disk space?"); } } /* If a TNG file is open for uncompressed coordinate output also write velocities and forces to it. */ else if (of->tng) { gmx_fwrite_tng(of->tng, FALSE, step, t, state_local->lambda[FreeEnergyPerturbationCouplingType::Fep], state_local->box, natoms, x, v, f); } /* If only a TNG file is open for compressed coordinate output (no uncompressed coordinate output) also write forces and velocities to it. */ else if (of->tng_low_prec) { gmx_fwrite_tng(of->tng_low_prec, FALSE, step, t, state_local->lambda[FreeEnergyPerturbationCouplingType::Fep], state_local->box, natoms, x, v, f); } } if (mdof_flags & MDOF_X_COMPRESSED) { rvec* xxtc = nullptr; if (of->natoms_x_compressed == of->natoms_global) { /* We are writing the positions of all of the atoms to the compressed output */ xxtc = state_global->x.rvec_array(); } else { /* We are writing the positions of only a subset of the atoms to the compressed output, so we have to make a copy of the subset of coordinates. */ int i, j; snew(xxtc, of->natoms_x_compressed); auto x = makeArrayRef(state_global->x); for (i = 0, j = 0; (i < of->natoms_global); i++) { if (getGroupType(*of->groups, SimulationAtomGroupType::CompressedPositionOutput, i) == 0) { copy_rvec(x[i], xxtc[j++]); } } } if (write_xtc(of->fp_xtc, of->natoms_x_compressed, step, t, state_local->box, xxtc, of->x_compression_precision) == 0) { gmx_fatal(FARGS, "XTC error. This indicates you are out of disk space, or a " "simulation with major instabilities resulting in coordinates " "that are NaN or too large to be represented in the XTC format.\n"); } gmx_fwrite_tng(of->tng_low_prec, TRUE, step, t, state_local->lambda[FreeEnergyPerturbationCouplingType::Fep], state_local->box, of->natoms_x_compressed, xxtc, nullptr, nullptr); if (of->natoms_x_compressed != of->natoms_global) { sfree(xxtc); } } if (mdof_flags & (MDOF_BOX | MDOF_LAMBDA) && !(mdof_flags & (MDOF_X | MDOF_V | MDOF_F))) { if (of->tng) { real lambda = -1; rvec* box = nullptr; if (mdof_flags & MDOF_BOX) { box = state_local->box; } if (mdof_flags & MDOF_LAMBDA) { lambda = state_local->lambda[FreeEnergyPerturbationCouplingType::Fep]; } gmx_fwrite_tng(of->tng, FALSE, step, t, lambda, box, natoms, nullptr, nullptr, nullptr); } } if (mdof_flags & (MDOF_BOX_COMPRESSED | MDOF_LAMBDA_COMPRESSED) && !(mdof_flags & (MDOF_X_COMPRESSED))) { if (of->tng_low_prec) { real lambda = -1; rvec* box = nullptr; if (mdof_flags & MDOF_BOX_COMPRESSED) { box = state_local->box; } if (mdof_flags & MDOF_LAMBDA_COMPRESSED) { lambda = state_local->lambda[FreeEnergyPerturbationCouplingType::Fep]; } gmx_fwrite_tng(of->tng_low_prec, FALSE, step, t, lambda, box, natoms, nullptr, nullptr, nullptr); } } #if GMX_FAHCORE /* Write a FAH checkpoint after writing any other data. We may end up checkpointing twice but it's fast so it's ok. */ if ((mdof_flags & ~MDOF_CPT)) { fcCheckpoint(); } #endif } } void mdoutf_tng_close(gmx_mdoutf_t of) { if (of->tng || of->tng_low_prec) { wallcycle_start(of->wcycle, WallCycleCounter::Traj); gmx_tng_close(&of->tng); gmx_tng_close(&of->tng_low_prec); wallcycle_stop(of->wcycle, WallCycleCounter::Traj); } } void done_mdoutf(gmx_mdoutf_t of) { if (of->fp_ene != nullptr) { done_ener_file(of->fp_ene); } if (of->fp_xtc) { close_xtc(of->fp_xtc); } if (of->fp_trn) { gmx_trr_close(of->fp_trn); } if (of->fp_dhdl != nullptr) { gmx_fio_fclose(of->fp_dhdl); } of->outputProvider->finishOutput(); if (of->f_global != nullptr) { sfree(of->f_global); } gmx_tng_close(&of->tng); gmx_tng_close(&of->tng_low_prec); sfree(of); } int mdoutf_get_tng_box_output_interval(gmx_mdoutf_t of) { if (of->tng) { return gmx_tng_get_box_output_interval(of->tng); } return 0; } int mdoutf_get_tng_lambda_output_interval(gmx_mdoutf_t of) { if (of->tng) { return gmx_tng_get_lambda_output_interval(of->tng); } return 0; } int mdoutf_get_tng_compressed_box_output_interval(gmx_mdoutf_t of) { if (of->tng_low_prec) { return gmx_tng_get_box_output_interval(of->tng_low_prec); } return 0; } int mdoutf_get_tng_compressed_lambda_output_interval(gmx_mdoutf_t of) { if (of->tng_low_prec) { return gmx_tng_get_lambda_output_interval(of->tng_low_prec); } return 0; } <|start_filename|>api/nblib/listed_forces/tests/helpers.cpp<|end_filename|> /* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2020,2021, by the GROMACS development team, led by * <NAME>, <NAME>, <NAME>, and <NAME>, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS 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. * * GROMACS 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 GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ /*! \internal \file * \brief * This implements basic nblib utility tests * * \author <NAME> <<EMAIL>> * \author <NAME> <<EMAIL>> * \author <NAME> <<EMAIL>> * \author <NAME> <<EMAIL>> */ #include "gmxpre.h" #include <gtest/gtest.h> #include "nblib/listed_forces/helpers.hpp" #include "nblib/listed_forces/traits.h" #include "testutils/testasserts.h" namespace nblib { namespace test { namespace { TEST(NBlibTest, CanSplitListedWork) { ListedInteractionData interactions; HarmonicAngle angle(1, Degrees(1)); HarmonicBondType bond(1, 1); int largestIndex = 20; int nSplits = 3; // split ranges: [0,5], [6,11], [12, 19] std::vector<InteractionIndex<HarmonicBondType>> bondIndices{ { 0, 1, 0 }, { 0, 6, 0 }, { 11, 12, 0 }, { 18, 19, 0 } }; std::vector<InteractionIndex<HarmonicAngle>> angleIndices{ { 0, 1, 2, 0 }, { 0, 6, 7, 0 }, { 11, 12, 13, 0 }, { 17, 19, 18, 0 } }; pickType<HarmonicBondType>(interactions).indices = bondIndices; pickType<HarmonicAngle>(interactions).indices = angleIndices; std::vector<ListedInteractionData> splitInteractions = splitListedWork(interactions, largestIndex, nSplits); std::vector<InteractionIndex<HarmonicBondType>> refBondIndices0{ { 0, 1, 0 }, { 0, 6, 0 } }; std::vector<InteractionIndex<HarmonicAngle>> refAngleIndices0{ { 0, 1, 2, 0 }, { 0, 6, 7, 0 } }; std::vector<InteractionIndex<HarmonicBondType>> refBondIndices1{ { 11, 12, 0 } }; std::vector<InteractionIndex<HarmonicAngle>> refAngleIndices1{ { 11, 12, 13, 0 } }; std::vector<InteractionIndex<HarmonicBondType>> refBondIndices2{ { 18, 19, 0 } }; std::vector<InteractionIndex<HarmonicAngle>> refAngleIndices2{ { 17, 19, 18, 0 } }; EXPECT_EQ(refBondIndices0, pickType<HarmonicBondType>(splitInteractions[0]).indices); EXPECT_EQ(refBondIndices1, pickType<HarmonicBondType>(splitInteractions[1]).indices); EXPECT_EQ(refBondIndices2, pickType<HarmonicBondType>(splitInteractions[2]).indices); EXPECT_EQ(refAngleIndices0, pickType<HarmonicAngle>(splitInteractions[0]).indices); EXPECT_EQ(refAngleIndices1, pickType<HarmonicAngle>(splitInteractions[1]).indices); EXPECT_EQ(refAngleIndices2, pickType<HarmonicAngle>(splitInteractions[2]).indices); } TEST(NBlibTest, ListedForceBuffer) { using T = gmx::RVec; int ncoords = 20; T vzero{ 0, 0, 0 }; std::vector<T> masterBuffer(ncoords, vzero); // the ForceBuffer is going to access indices [10-15) through the masterBuffer // and the outliers internally int rangeStart = 10; int rangeEnd = 15; ForceBuffer<T> forceBuffer(masterBuffer.data(), rangeStart, rangeEnd); // in range T internal1{ 1, 2, 3 }; T internal2{ 4, 5, 6 }; forceBuffer[10] = internal1; forceBuffer[14] = internal2; // outliers T outlier{ 0, 1, 2 }; forceBuffer[5] = outlier; std::vector<T> refMasterBuffer(ncoords, vzero); refMasterBuffer[10] = internal1; refMasterBuffer[14] = internal2; for (size_t i = 0; i < masterBuffer.size(); ++i) { for (size_t m = 0; m < dimSize; ++m) { EXPECT_REAL_EQ_TOL( refMasterBuffer[i][m], masterBuffer[i][m], gmx::test::defaultRealTolerance()); } } for (size_t m = 0; m < dimSize; ++m) { EXPECT_REAL_EQ_TOL(outlier[m], forceBuffer[5][m], gmx::test::defaultRealTolerance()); EXPECT_REAL_EQ_TOL(vzero[m], forceBuffer[4][m], gmx::test::defaultRealTolerance()); } } } // namespace } // namespace test } // namespace nblib <|start_filename|>src/testutils/include/testutils/mpitest.h<|end_filename|> /* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2016,2019,2020,2021, by the GROMACS development team, led by * <NAME>, <NAME>, <NAME>, and <NAME>, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS 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. * * GROMACS 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 GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ /*! \libinternal \file * \brief * Helper functions for MPI tests to make thread-MPI look like real MPI. * * \author <NAME> <<EMAIL>> * \inlibraryapi * \ingroup module_testutils */ #ifndef GMX_TESTUTILS_MPITEST_H #define GMX_TESTUTILS_MPITEST_H #include "config.h" #include <functional> #include <type_traits> #include "gromacs/utility/basenetwork.h" namespace gmx { namespace test { /*! \brief * Returns the number of MPI ranks to use for an MPI test. * * For thread-MPI builds, this will return the requested number of ranks * even before the thread-MPI threads have been started. * * \ingroup module_testutils */ int getNumberOfTestMpiRanks(); //! \cond internal /*! \brief * Helper function for GMX_MPI_TEST(). * * \ingroup module_testutils */ bool threadMpiTestRunner(std::function<void()> testBody); //! \endcond /*! \brief * Declares that this test is an MPI-enabled unit test. * * \param[in] expectedRankCount Expected number of ranks for this test. * The test will fail if run with unsupported number of ranks. * * To write unit tests that run under MPI, you need to do a few things: * - Put GMX_MPI_TEST() as the first statement in your test body and * specify the number of ranks this test expects. * - Declare your unit test in CMake with gmx_add_mpi_unit_test(). * Note that all tests in the binary should fulfill the conditions above, * and work with the same number of ranks. * TODO: Figure out a mechanism for mixing tests with different rank counts in * the same binary (possibly, also MPI and non-MPI tests). * * When you do the above, the following will happen: * - The test will get compiled only if thread-MPI or real MPI is enabled. * - The test will get executed on the number of ranks specified. * If you are using real MPI, the whole test binary is run under MPI and * test execution across the processes is synchronized (GMX_MPI_TEST() * actually has no effect in this case, the synchronization is handled at a * higher level). * If you are using thread-MPI, GMX_MPI_TEST() is required and it * initializes thread-MPI with the specified number of threads and runs the * rest of the test on each of the threads. * * You need to be extra careful for variables in the test fixture, if you use * one: when run under thread-MPI, these will be shared across all the ranks, * while under real MPI, these are naturally different for each process. * Local variables in the test body are private to each rank in both cases. * * Currently, it is not possible to specify the number of ranks as one, because * that will lead to problems with (at least) thread-MPI, but such tests can be * written as serial tests anyways. * * \ingroup module_testutils */ #if GMX_THREAD_MPI # define GMX_MPI_TEST(expectedRankCount) \ do \ { \ ASSERT_EQ(expectedRankCount, ::gmx::test::getNumberOfTestMpiRanks()); \ using MyTestClass = std::remove_reference_t<decltype(*this)>; \ if (!::gmx::test::threadMpiTestRunner([this]() { this->MyTestClass::TestBody(); })) \ { \ return; \ } \ } while (0) #else # define GMX_MPI_TEST(expectedRankCount) \ ASSERT_EQ(expectedRankCount, ::gmx::test::getNumberOfTestMpiRanks()) #endif } // namespace test } // namespace gmx #endif <|start_filename|>src/gromacs/ewald/tests/pmesplinespreadtest.cpp<|end_filename|> /* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2016,2017,2018,2019,2020,2021, by the GROMACS development team, led by * <NAME>, <NAME>, <NAME>, and <NAME>, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS 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. * * GROMACS 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 GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ /*! \internal \file * \brief * Implements PME spline computation and charge spreading tests. * * \author <NAME> <<EMAIL>> * \ingroup module_ewald */ #include "gmxpre.h" #include <string> #include <gmock/gmock.h> #include "gromacs/mdtypes/inputrec.h" #include "gromacs/utility/stringutil.h" #include "testutils/refdata.h" #include "testutils/test_hardware_environment.h" #include "testutils/testasserts.h" #include "pmetestcommon.h" namespace gmx { namespace test { namespace { //! PME spline and spread code path being tested enum class PmeSplineAndSpreadOptions { SplineOnly, SpreadOnly, SplineAndSpreadUnified }; /*! \brief Convenience typedef of input parameters - unit cell box, PME interpolation order, grid * dimensions, particle coordinates, particle charges * TODO: consider inclusion of local grid offsets/sizes or PME nodes counts to test the PME DD */ typedef std::tuple<Matrix3x3, int, IVec, CoordinatesVector, ChargesVector> SplineAndSpreadInputParameters; /*! \brief Test fixture for testing both atom spline parameter computation and charge spreading. * These 2 stages of PME are tightly coupled in the code. */ class PmeSplineAndSpreadTest : public ::testing::TestWithParam<SplineAndSpreadInputParameters> { public: PmeSplineAndSpreadTest() = default; //! Sets the programs once static void SetUpTestSuite() { s_pmeTestHardwareContexts = createPmeTestHardwareContextList(); g_allowPmeWithSyclForTesting = true; // We support PmeSplineAndSpread with SYCL } static void TearDownTestSuite() { // Revert the value back. g_allowPmeWithSyclForTesting = false; } //! The test static void runTest() { /* Getting the input */ Matrix3x3 box; int pmeOrder; IVec gridSize; CoordinatesVector coordinates; ChargesVector charges; std::tie(box, pmeOrder, gridSize, coordinates, charges) = GetParam(); const size_t atomCount = coordinates.size(); /* Storing the input where it's needed */ t_inputrec inputRec; inputRec.nkx = gridSize[XX]; inputRec.nky = gridSize[YY]; inputRec.nkz = gridSize[ZZ]; inputRec.pme_order = pmeOrder; inputRec.coulombtype = CoulombInteractionType::Pme; inputRec.epsilon_r = 1.0; const std::map<PmeSplineAndSpreadOptions, std::string> optionsToTest = { { PmeSplineAndSpreadOptions::SplineAndSpreadUnified, "spline computation and charge spreading (fused)" }, { PmeSplineAndSpreadOptions::SplineOnly, "spline computation" }, { PmeSplineAndSpreadOptions::SpreadOnly, "charge spreading" } }; // There is a subtle problem with multiple comparisons against same reference data: // The subsequent (GPU) spreading runs at one point didn't actually copy the output grid // into the proper buffer, but the reference data was already marked as checked // (hasBeenChecked_) by the CPU run, so nothing failed. For now we will manually track that // the count of the grid entries is the same on each run. This is just a hack for a single // specific output though. What would be much better TODO is to split different codepaths // into separate tests, while making them use the same reference files. bool gridValuesSizeAssigned = false; size_t previousGridValuesSize; TestReferenceData refData; for (const auto& pmeTestHardwareContext : s_pmeTestHardwareContexts) { pmeTestHardwareContext->activate(); CodePath codePath = pmeTestHardwareContext->codePath(); const bool supportedInput = pmeSupportsInputForMode( *getTestHardwareEnvironment()->hwinfo(), &inputRec, codePath); if (!supportedInput) { /* Testing the failure for the unsupported input */ EXPECT_THROW_GMX(pmeInitWrapper(&inputRec, codePath, nullptr, nullptr, nullptr, box), NotImplementedError); continue; } for (const auto& option : optionsToTest) { /* Describing the test uniquely in case it fails */ SCOPED_TRACE( formatString("Testing %s on %s for PME grid size %d %d %d" ", order %d, %zu atoms", option.second.c_str(), pmeTestHardwareContext->description().c_str(), gridSize[XX], gridSize[YY], gridSize[ZZ], pmeOrder, atomCount)); /* Running the test */ PmeSafePointer pmeSafe = pmeInitWrapper(&inputRec, codePath, pmeTestHardwareContext->deviceContext(), pmeTestHardwareContext->deviceStream(), pmeTestHardwareContext->pmeGpuProgram(), box); std::unique_ptr<StatePropagatorDataGpu> stateGpu = (codePath == CodePath::GPU) ? makeStatePropagatorDataGpu(*pmeSafe.get(), pmeTestHardwareContext->deviceContext(), pmeTestHardwareContext->deviceStream()) : nullptr; pmeInitAtoms(pmeSafe.get(), stateGpu.get(), codePath, coordinates, charges); const bool computeSplines = (option.first == PmeSplineAndSpreadOptions::SplineOnly) || (option.first == PmeSplineAndSpreadOptions::SplineAndSpreadUnified); const bool spreadCharges = (option.first == PmeSplineAndSpreadOptions::SpreadOnly) || (option.first == PmeSplineAndSpreadOptions::SplineAndSpreadUnified); if (!computeSplines) { // Here we should set up the results of the spline computation so that the spread can run. // What is lazy and works is running the separate spline so that it will set it up for us: pmePerformSplineAndSpread(pmeSafe.get(), codePath, true, false); // We know that it is tested in another iteration. // TODO: Clean alternative: read and set the reference gridline indices, spline params } pmePerformSplineAndSpread(pmeSafe.get(), codePath, computeSplines, spreadCharges); pmeFinalizeTest(pmeSafe.get(), codePath); /* Outputs correctness check */ /* All tolerances were picked empirically for single precision on CPU */ TestReferenceChecker rootChecker(refData.rootChecker()); const auto maxGridSize = std::max(std::max(gridSize[XX], gridSize[YY]), gridSize[ZZ]); const auto ulpToleranceSplineValues = 4 * (pmeOrder - 2) * maxGridSize; /* 4 is a modest estimate for amount of operations; (pmeOrder - 2) is a number of iterations; * maxGridSize is inverse of the smallest positive fractional coordinate (which are interpolated by the splines). */ if (computeSplines) { const char* dimString[] = { "X", "Y", "Z" }; /* Spline values */ SCOPED_TRACE(formatString("Testing spline values with tolerance of %d", ulpToleranceSplineValues)); TestReferenceChecker splineValuesChecker( rootChecker.checkCompound("Splines", "Values")); splineValuesChecker.setDefaultTolerance( relativeToleranceAsUlp(1.0, ulpToleranceSplineValues)); for (int i = 0; i < DIM; i++) { auto splineValuesDim = pmeGetSplineData(pmeSafe.get(), codePath, PmeSplineDataType::Values, i); splineValuesChecker.checkSequence( splineValuesDim.begin(), splineValuesDim.end(), dimString[i]); } /* Spline derivatives */ const auto ulpToleranceSplineDerivatives = 4 * ulpToleranceSplineValues; /* 4 is just a wild guess since the derivatives are deltas of neighbor spline values which could differ greatly */ SCOPED_TRACE(formatString("Testing spline derivatives with tolerance of %d", ulpToleranceSplineDerivatives)); TestReferenceChecker splineDerivativesChecker( rootChecker.checkCompound("Splines", "Derivatives")); splineDerivativesChecker.setDefaultTolerance( relativeToleranceAsUlp(1.0, ulpToleranceSplineDerivatives)); for (int i = 0; i < DIM; i++) { auto splineDerivativesDim = pmeGetSplineData( pmeSafe.get(), codePath, PmeSplineDataType::Derivatives, i); splineDerivativesChecker.checkSequence( splineDerivativesDim.begin(), splineDerivativesDim.end(), dimString[i]); } /* Particle gridline indices */ auto gridLineIndices = pmeGetGridlineIndices(pmeSafe.get(), codePath); rootChecker.checkSequence( gridLineIndices.begin(), gridLineIndices.end(), "Gridline indices"); } if (spreadCharges) { /* The wrapped grid */ SparseRealGridValuesOutput nonZeroGridValues = pmeGetRealGrid(pmeSafe.get(), codePath); TestReferenceChecker gridValuesChecker( rootChecker.checkCompound("NonZeroGridValues", "RealSpaceGrid")); const auto ulpToleranceGrid = 2 * ulpToleranceSplineValues * static_cast<int>(ceil(sqrt(static_cast<real>(atomCount)))); /* 2 is empiric; sqrt(atomCount) assumes all the input charges may spread onto the same cell */ SCOPED_TRACE(formatString("Testing grid values with tolerance of %d", ulpToleranceGrid)); if (!gridValuesSizeAssigned) { previousGridValuesSize = nonZeroGridValues.size(); gridValuesSizeAssigned = true; } else { EXPECT_EQ(previousGridValuesSize, nonZeroGridValues.size()); } gridValuesChecker.setDefaultTolerance(relativeToleranceAsUlp(1.0, ulpToleranceGrid)); for (const auto& point : nonZeroGridValues) { gridValuesChecker.checkReal(point.second, point.first.c_str()); } } } } } static std::vector<std::unique_ptr<PmeTestHardwareContext>> s_pmeTestHardwareContexts; }; std::vector<std::unique_ptr<PmeTestHardwareContext>> PmeSplineAndSpreadTest::s_pmeTestHardwareContexts; /*! \brief Test for spline parameter computation and charge spreading. */ TEST_P(PmeSplineAndSpreadTest, ReproducesOutputs) { EXPECT_NO_THROW_GMX(runTest()); } /* Valid input instances */ //! A couple of valid inputs for boxes. std::vector<Matrix3x3> const c_sampleBoxes{ // normal box Matrix3x3{ { 8.0F, 0.0F, 0.0F, 0.0F, 3.4F, 0.0F, 0.0F, 0.0F, 2.0F } }, // triclinic box Matrix3x3{ { 7.0F, 0.0F, 0.0F, 0.0F, 4.1F, 0.0F, 3.5F, 2.0F, 12.2F } }, }; //! A couple of valid inputs for grid sizes. std::vector<IVec> const c_sampleGridSizes{ IVec{ 16, 12, 14 }, IVec{ 19, 17, 11 } }; //! Random charges std::vector<real> const c_sampleChargesFull{ 4.95F, 3.11F, 3.97F, 1.08F, 2.09F, 1.1F, 4.13F, 3.31F, 2.8F, 5.83F, 5.09F, 6.1F, 2.86F, 0.24F, 5.76F, 5.19F, 0.72F }; //! 1 charge auto const c_sampleCharges1 = ChargesVector(c_sampleChargesFull).subArray(0, 1); //! 2 charges auto const c_sampleCharges2 = ChargesVector(c_sampleChargesFull).subArray(1, 2); //! 13 charges auto const c_sampleCharges13 = ChargesVector(c_sampleChargesFull).subArray(3, 13); //! Random coordinate vectors CoordinatesVector const c_sampleCoordinatesFull{ { 5.59F, 1.37F, 0.95F }, { 16.0F, 1.02F, 0.22F // 2 box lengths in x }, { 0.034F, 1.65F, 0.22F }, { 0.33F, 0.92F, 1.56F }, { 1.16F, 0.75F, 0.39F }, { 0.5F, 1.63F, 1.14F }, { 16.0001F, 1.52F, 1.19F // > 2 box lengths in x }, { 1.43F, 1.1F, 4.1F // > 2 box lengths in z }, { -1.08F, 1.19F, 0.08F // negative x }, { 1.6F, 0.93F, 0.53F }, { 1.32F, -1.48F, 0.16F // negative y }, { 0.87F, 0.0F, 0.33F }, { 0.95F, 7.7F, -0.48F // > 2 box lengths in y, negative z }, { 1.23F, 0.91F, 0.68F }, { 0.19F, 1.45F, 0.94F }, { 1.28F, 0.46F, 0.38F }, { 1.21F, 0.23F, 1.0F } }; //! 1 coordinate vector CoordinatesVector const c_sampleCoordinates1(c_sampleCoordinatesFull.begin(), c_sampleCoordinatesFull.begin() + 1); //! 2 coordinate vectors CoordinatesVector const c_sampleCoordinates2(c_sampleCoordinatesFull.begin() + 1, c_sampleCoordinatesFull.begin() + 3); //! 13 coordinate vectors CoordinatesVector const c_sampleCoordinates13(c_sampleCoordinatesFull.begin() + 3, c_sampleCoordinatesFull.begin() + 16); //! moved out from instantiantions for readability auto c_inputBoxes = ::testing::ValuesIn(c_sampleBoxes); //! moved out from instantiantions for readability auto c_inputPmeOrders = ::testing::Range(3, 5 + 1); //! moved out from instantiantions for readability auto c_inputGridSizes = ::testing::ValuesIn(c_sampleGridSizes); /*! \brief Instantiation of the test with valid input and 1 atom */ INSTANTIATE_TEST_SUITE_P(SaneInput1, PmeSplineAndSpreadTest, ::testing::Combine(c_inputBoxes, c_inputPmeOrders, c_inputGridSizes, ::testing::Values(c_sampleCoordinates1), ::testing::Values(c_sampleCharges1))); /*! \brief Instantiation of the test with valid input and 2 atoms */ INSTANTIATE_TEST_SUITE_P(SaneInput2, PmeSplineAndSpreadTest, ::testing::Combine(c_inputBoxes, c_inputPmeOrders, c_inputGridSizes, ::testing::Values(c_sampleCoordinates2), ::testing::Values(c_sampleCharges2))); /*! \brief Instantiation of the test with valid input and 13 atoms */ INSTANTIATE_TEST_SUITE_P(SaneInput13, PmeSplineAndSpreadTest, ::testing::Combine(c_inputBoxes, c_inputPmeOrders, c_inputGridSizes, ::testing::Values(c_sampleCoordinates13), ::testing::Values(c_sampleCharges13))); } // namespace } // namespace test } // namespace gmx <|start_filename|>src/gromacs/gpu_utils/cudautils.cuh<|end_filename|> /* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2012,2014,2015,2016,2017 by the GROMACS development team. * Copyright (c) 2018,2019,2020,2021, by the GROMACS development team, led by * <NAME>, <NAME>, <NAME>, and <NAME>, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS 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. * * GROMACS 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 GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ #ifndef GMX_GPU_UTILS_CUDAUTILS_CUH #define GMX_GPU_UTILS_CUDAUTILS_CUH #include <stdio.h> #include <array> #include <string> #include <type_traits> #include "gromacs/gpu_utils/device_stream.h" #include "gromacs/gpu_utils/gputraits.cuh" #include "gromacs/math/vec.h" #include "gromacs/math/vectypes.h" #include "gromacs/utility/exceptions.h" #include "gromacs/utility/fatalerror.h" #include "gromacs/utility/gmxassert.h" #include "gromacs/utility/stringutil.h" namespace gmx { namespace { /*! \brief Add the API information on the specific error to the error message. * * \param[in] deviceError The error to assert cudaSuccess on. * * \returns A description of the API error. Returns '(CUDA error #0 (cudaSuccess): no error)' in case deviceError is cudaSuccess. */ inline std::string getDeviceErrorString(const cudaError_t deviceError) { return formatString("CUDA error #%d (%s): %s.", deviceError, cudaGetErrorName(deviceError), cudaGetErrorString(deviceError)); } /*! \brief Check if API returned an error and throw an exception with information on it. * * \param[in] deviceError The error to assert cudaSuccess on. * \param[in] errorMessage Undecorated error message. * * \throws InternalError if deviceError is not a success. */ inline void checkDeviceError(const cudaError_t deviceError, const std::string& errorMessage) { if (deviceError != cudaSuccess) { GMX_THROW(gmx::InternalError(errorMessage + " " + getDeviceErrorString(deviceError))); } } /*! \brief Helper function to ensure no pending error silently * disrupts error handling. * * Asserts in a debug build if an unhandled error is present. Issues a * warning at run time otherwise. * * \param[in] errorMessage Undecorated error message. */ inline void ensureNoPendingDeviceError(const std::string& errorMessage) { // Ensure there is no pending error that would otherwise affect // the behaviour of future error handling. cudaError_t deviceError = cudaGetLastError(); if (deviceError == cudaSuccess) { return; } // If we would find an error in a release build, we do not know // what is appropriate to do about it, so assert only for debug // builds. const std::string fullErrorMessage = errorMessage + " An unhandled error from a previous CUDA operation was detected. " + gmx::getDeviceErrorString(deviceError); GMX_ASSERT(deviceError == cudaSuccess, fullErrorMessage.c_str()); // TODO When we evolve a better logging framework, use that // for release-build error reporting. gmx_warning("%s", fullErrorMessage.c_str()); } } // namespace } // namespace gmx enum class GpuApiCallBehavior; /* TODO error checking needs to be rewritten. We have 2 types of error checks needed based on where they occur in the code: - non performance-critical: these errors are unsafe to be ignored and must be _always_ checked for, e.g. initializations - performance critical: handling errors might hurt performance so care need to be taken when/if we should check for them at all, e.g. in cu_upload_X. However, we should be able to turn the check for these errors on! Probably we'll need two sets of the macros below... */ #define CHECK_CUDA_ERRORS #ifdef CHECK_CUDA_ERRORS /*! Check for CUDA error on the return status of a CUDA RT API call. */ # define CU_RET_ERR(deviceError, msg) \ do \ { \ if ((deviceError) != cudaSuccess) \ { \ gmx_fatal(FARGS, "%s\n", ((msg) + gmx::getDeviceErrorString(deviceError)).c_str()); \ } \ } while (0) #else /* CHECK_CUDA_ERRORS */ # define CU_RET_ERR(status, msg) \ do \ { \ } while (0) #endif /* CHECK_CUDA_ERRORS */ // TODO: the 2 functions below are pretty much a constructor/destructor of a simple // GPU table object. There is also almost self-contained fetchFromParamLookupTable() // in cuda_kernel_utils.cuh. They could all live in a separate class/struct file. /*! \brief Add a triplets stored in a float3 to an rvec variable. * * \param[out] a Rvec to increment * \param[in] b Float triplet to increment with. */ static inline void rvec_inc(rvec a, const float3 b) { rvec tmp = { b.x, b.y, b.z }; rvec_inc(a, tmp); } /*! \brief Returns true if all tasks in \p s have completed. * * \param[in] deviceStream CUDA stream to check. * * \returns True if all tasks enqueued in the stream \p deviceStream (at the time of this call) have completed. */ static inline bool haveStreamTasksCompleted(const DeviceStream& deviceStream) { cudaError_t stat = cudaStreamQuery(deviceStream.stream()); if (stat == cudaErrorNotReady) { // work is still in progress in the stream return false; } GMX_ASSERT(stat != cudaErrorInvalidResourceHandle, ("Stream identifier not valid. " + gmx::getDeviceErrorString(stat)).c_str()); // cudaSuccess and cudaErrorNotReady are the expected return values CU_RET_ERR(stat, "Unexpected cudaStreamQuery failure. "); GMX_ASSERT(stat == cudaSuccess, ("Values other than cudaSuccess should have been explicitly handled. " + gmx::getDeviceErrorString(stat)) .c_str()); return true; } /* Kernel launch helpers */ /*! \brief * A function for setting up a single CUDA kernel argument. * This is the tail of the compile-time recursive function below. * It has to be seen by the compiler first. * * \tparam totalArgsCount Number of the kernel arguments * \tparam KernelPtr Kernel function handle type * \param[in] argIndex Index of the current argument */ template<size_t totalArgsCount, typename KernelPtr> void prepareGpuKernelArgument(KernelPtr /*kernel*/, std::array<void*, totalArgsCount>* /* kernelArgsPtr */, size_t gmx_used_in_debug argIndex) { GMX_ASSERT(argIndex == totalArgsCount, "Tail expansion"); } /*! \brief * Compile-time recursive function for setting up a single CUDA kernel argument. * This function copies a kernel argument pointer \p argPtr into \p kernelArgsPtr, * and calls itself on the next argument, eventually calling the tail function above. * * \tparam CurrentArg Type of the current argument * \tparam RemainingArgs Types of remaining arguments after the current one * \tparam totalArgsCount Number of the kernel arguments * \tparam KernelPtr Kernel function handle type * \param[in] kernel Kernel function handle * \param[in,out] kernelArgsPtr Pointer to the argument array to be filled in * \param[in] argIndex Index of the current argument * \param[in] argPtr Pointer to the current argument * \param[in] otherArgsPtrs Pack of pointers to arguments remaining to process after the current one */ template<typename CurrentArg, typename... RemainingArgs, size_t totalArgsCount, typename KernelPtr> void prepareGpuKernelArgument(KernelPtr kernel, std::array<void*, totalArgsCount>* kernelArgsPtr, size_t argIndex, const CurrentArg* argPtr, const RemainingArgs*... otherArgsPtrs) { (*kernelArgsPtr)[argIndex] = const_cast<void*>(static_cast<const void*>(argPtr)); prepareGpuKernelArgument(kernel, kernelArgsPtr, argIndex + 1, otherArgsPtrs...); } /*! \brief * A wrapper function for setting up all the CUDA kernel arguments. * Calls the recursive functions above. * * \tparam KernelPtr Kernel function handle type * \tparam Args Types of all the kernel arguments * \param[in] kernel Kernel function handle * \param[in] argsPtrs Pointers to all the kernel arguments * \returns A prepared parameter pack to be used with launchGpuKernel() as the last argument. */ template<typename KernelPtr, typename... Args> std::array<void*, sizeof...(Args)> prepareGpuKernelArguments(KernelPtr kernel, const KernelLaunchConfig& /*config */, const Args*... argsPtrs) { std::array<void*, sizeof...(Args)> kernelArgs; prepareGpuKernelArgument(kernel, &kernelArgs, 0, argsPtrs...); return kernelArgs; } /*! \brief Launches the CUDA kernel and handles the errors. * * \tparam Args Types of all the kernel arguments * \param[in] kernel Kernel function handle * \param[in] config Kernel configuration for launching * \param[in] deviceStream GPU stream to launch kernel in * \param[in] kernelName Human readable kernel description, for error handling only * \param[in] kernelArgs Array of the pointers to the kernel arguments, prepared by * prepareGpuKernelArguments() \throws gmx::InternalError on kernel launch failure */ template<typename... Args> void launchGpuKernel(void (*kernel)(Args...), const KernelLaunchConfig& config, const DeviceStream& deviceStream, CommandEvent* /*timingEvent */, const char* kernelName, const std::array<void*, sizeof...(Args)>& kernelArgs) { dim3 blockSize(config.blockSize[0], config.blockSize[1], config.blockSize[2]); dim3 gridSize(config.gridSize[0], config.gridSize[1], config.gridSize[2]); cudaLaunchKernel(reinterpret_cast<void*>(kernel), gridSize, blockSize, const_cast<void**>(kernelArgs.data()), config.sharedMemorySize, deviceStream.stream()); gmx::ensureNoPendingDeviceError("GPU kernel (" + std::string(kernelName) + ") failed to launch."); } #endif <|start_filename|>api/nblib/tests/nbnxmsetup.cpp<|end_filename|> /* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2021, by the GROMACS development team, led by * <NAME>, <NAME>, <NAME>, and <NAME>, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS 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. * * GROMACS 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 GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ /*! \internal \file * \brief * Tests for nbnxm setup utilities * * \author <NAME> <<EMAIL>> * \author <NAME> <<EMAIL>> * \author <NAME> <<EMAIL>> * \author <NAME> <<EMAIL>> */ #include <cmath> #include "gromacs/mdtypes/forcerec.h" #include "gromacs/mdtypes/interaction_const.h" #include "gromacs/mdtypes/simulation_workload.h" #include "gromacs/nbnxm/nbnxm.h" #include "gromacs/nbnxm/nbnxm_simd.h" #include "nblib/box.h" #include "nblib/nbnxmsetuphelpers.h" #include "testutils/testasserts.h" namespace nblib { namespace test { namespace { TEST(NbnxmSetupTest, findNumEnergyGroups) { std::vector<int64_t> v(10); int arbitraryGid = 7; // this sets some bit outside the range of bits used for the group ID // having all bits zero except those used for the group ID can otherwise hide bugs v[5] |= gmx::sc_atomInfo_HasCharge; v[5] = (v[5] & ~gmx::sc_atomInfo_EnergyGroupIdMask) | arbitraryGid; int nEnergyGroups = arbitraryGid + 1; EXPECT_EQ(nEnergyGroups, findNumEnergyGroups(v)); } TEST(NbnxmSetupTest, canTranslateBenchmarkEnumAuto) { auto kernel = SimdKernels::SimdAuto; EXPECT_EQ(translateBenchmarkEnum(kernel), Nbnxm::KernelType::NotSet); } TEST(NbnxmSetupTest, canTranslateBenchmarkEnumNo) { auto kernel = SimdKernels::SimdNo; EXPECT_EQ(translateBenchmarkEnum(kernel), Nbnxm::KernelType::Cpu4x4_PlainC); } TEST(NbnxmSetupTest, canTranslateBenchmarkEnum2XM) { auto kernel = SimdKernels::Simd2XMM; EXPECT_EQ(translateBenchmarkEnum(kernel), Nbnxm::KernelType::Cpu4xN_Simd_2xNN); } TEST(NbnxmSetupTest, canTranslateBenchmarkEnum4XM) { auto kernel = SimdKernels::Simd4XM; EXPECT_EQ(translateBenchmarkEnum(kernel), Nbnxm::KernelType::Cpu4xN_Simd_4xN); } TEST(NbnxmSetupTest, CheckKernelSetupThrowsAuto) { EXPECT_ANY_THROW(checkKernelSetupSimd(SimdKernels::SimdAuto)); } TEST(NbnxmSetupTest, CheckKernelSetupThrowsCount) { EXPECT_ANY_THROW(checkKernelSetupSimd(SimdKernels::Count)); } TEST(NbnxmSetupTest, canCreateKernelSetupPlain) { NBKernelOptions nbKernelOptions; nbKernelOptions.nbnxmSimd = SimdKernels::SimdNo; Nbnxm::KernelSetup kernelSetup = createKernelSetupCPU(nbKernelOptions.nbnxmSimd, nbKernelOptions.useTabulatedEwaldCorr); EXPECT_EQ(kernelSetup.kernelType, Nbnxm::KernelType::Cpu4x4_PlainC); EXPECT_EQ(kernelSetup.ewaldExclusionType, Nbnxm::EwaldExclusionType::Table); } TEST(NbnxmSetupTest, canCreateParticleInfoAllVdv) { size_t numParticles = 2; int64_t mask = 0; mask |= gmx::sc_atomInfo_HasVdw; mask |= gmx::sc_atomInfo_HasCharge; std::vector<int64_t> refParticles = { mask, mask }; std::vector<int64_t> testParticles = createParticleInfoAllVdw(numParticles); EXPECT_EQ(refParticles, testParticles); } TEST(NbnxmSetupTest, ewaldCoeffWorks) { real ewald = ewaldCoeff(1e-5, 1.0); gmx::test::FloatingPointTolerance tolerance = gmx::test::absoluteTolerance(1e-5); EXPECT_REAL_EQ_TOL(ewald, 3.12341, tolerance); } TEST(NbnxmSetupTest, updateForcerecWorks) { t_forcerec forcerec; Box box(3); EXPECT_NO_THROW(updateForcerec(&forcerec, box.legacyMatrix())); } // The following tests check if the user is allowed to specify configurations not permitted due // to conflicting compile time setup flags TEST(NbnxmSetupTest, canCheckKernelSetup) { NBKernelOptions nbKernelOptions; nbKernelOptions.nbnxmSimd = SimdKernels::SimdNo; #ifdef GMX_NBNXN_SIMD_4XN nbKernelOptions.nbnxmSimd = SimdKernels::Simd4XM; #endif #ifdef GMX_NBNXN_SIMD_2XNN nbKernelOptions.nbnxmSimd = SimdKernels::Simd2XMM; #endif EXPECT_NO_THROW(checkKernelSetupSimd(nbKernelOptions.nbnxmSimd)); } // check if the user is allowed to ask for SimdKernels::Simd2XMM when NBLIB is not compiled with it #ifndef GMX_NBNXN_SIMD_2XNN TEST(NbnxmSetupTest, cannotCreateKernelSetupCPU2XM) { NBKernelOptions nbKernelOptions; nbKernelOptions.nbnxmSimd = SimdKernels::Simd2XMM; nbKernelOptions.useTabulatedEwaldCorr = true; EXPECT_ANY_THROW(createKernelSetupCPU(nbKernelOptions.nbnxmSimd, nbKernelOptions.useTabulatedEwaldCorr)); } #endif // check if the user is allowed to ask for SimdKernels::Simd4XM when NBLIB is not compiled with it #ifndef GMX_NBNXN_SIMD_4XN TEST(NbnxmSetupTest, cannotCreateKernelSetupCPU4XM) { NBKernelOptions nbKernelOptions; nbKernelOptions.nbnxmSimd = SimdKernels::Simd4XM; nbKernelOptions.useTabulatedEwaldCorr = false; EXPECT_ANY_THROW(createKernelSetupCPU(nbKernelOptions.nbnxmSimd, nbKernelOptions.useTabulatedEwaldCorr)); } #endif TEST(NbnxmSetupTest, CanCreateNbnxmCPU) { size_t numParticles = 1; NBKernelOptions nbKernelOptions; nbKernelOptions.nbnxmSimd = SimdKernels::SimdNo; int numEnergyGroups = 1; std::vector<real> nonbondedParameters = { 1, 1 }; EXPECT_NO_THROW(createNbnxmCPU(numParticles, nbKernelOptions, numEnergyGroups, nonbondedParameters)); } } // namespace } // namespace test } // namespace nblib <|start_filename|>src/gromacs/mdrun/md.cpp<|end_filename|> /* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 1991-2000, University of Groningen, The Netherlands. * Copyright (c) 2001-2004, The GROMACS development team. * Copyright (c) 2011-2019,2020,2021, by the GROMACS development team, led by * <NAME>, <NAME>, <NAME>, and <NAME>, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS 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. * * GROMACS 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 GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ /*! \internal \file * * \brief Implements the integrator for normal molecular dynamics simulations * * \author <NAME> <<EMAIL>> * \ingroup module_mdrun */ #include "gmxpre.h" #include <cinttypes> #include <cmath> #include <cstdio> #include <cstdlib> #include <algorithm> #include <memory> #include <numeric> #include "gromacs/applied_forces/awh/awh.h" #include "gromacs/applied_forces/awh/read_params.h" #include "gromacs/commandline/filenm.h" #include "gromacs/domdec/collect.h" #include "gromacs/domdec/dlbtiming.h" #include "gromacs/domdec/domdec.h" #include "gromacs/domdec/domdec_network.h" #include "gromacs/domdec/domdec_struct.h" #include "gromacs/domdec/gpuhaloexchange.h" #include "gromacs/domdec/localtopologychecker.h" #include "gromacs/domdec/mdsetup.h" #include "gromacs/domdec/partition.h" #include "gromacs/essentialdynamics/edsam.h" #include "gromacs/ewald/pme_load_balancing.h" #include "gromacs/ewald/pme_pp.h" #include "gromacs/fileio/trxio.h" #include "gromacs/gmxlib/network.h" #include "gromacs/gmxlib/nrnb.h" #include "gromacs/gpu_utils/device_stream_manager.h" #include "gromacs/gpu_utils/gpu_utils.h" #include "gromacs/imd/imd.h" #include "gromacs/listed_forces/listed_forces.h" #include "gromacs/math/functions.h" #include "gromacs/math/invertmatrix.h" #include "gromacs/math/vec.h" #include "gromacs/math/vectypes.h" #include "gromacs/mdlib/checkpointhandler.h" #include "gromacs/mdlib/compute_io.h" #include "gromacs/mdlib/constr.h" #include "gromacs/mdlib/coupling.h" #include "gromacs/mdlib/ebin.h" #include "gromacs/mdlib/enerdata_utils.h" #include "gromacs/mdlib/energyoutput.h" #include "gromacs/mdlib/expanded.h" #include "gromacs/mdlib/force.h" #include "gromacs/mdlib/force_flags.h" #include "gromacs/mdlib/forcerec.h" #include "gromacs/mdlib/freeenergyparameters.h" #include "gromacs/mdlib/md_support.h" #include "gromacs/mdlib/mdatoms.h" #include "gromacs/mdlib/mdoutf.h" #include "gromacs/mdlib/membed.h" #include "gromacs/mdlib/resethandler.h" #include "gromacs/mdlib/sighandler.h" #include "gromacs/mdlib/simulationsignal.h" #include "gromacs/mdlib/stat.h" #include "gromacs/mdlib/stophandler.h" #include "gromacs/mdlib/tgroup.h" #include "gromacs/mdlib/trajectory_writing.h" #include "gromacs/mdlib/update.h" #include "gromacs/mdlib/update_constrain_gpu.h" #include "gromacs/mdlib/update_vv.h" #include "gromacs/mdlib/vcm.h" #include "gromacs/mdlib/vsite.h" #include "gromacs/mdrunutility/freeenergy.h" #include "gromacs/mdrunutility/handlerestart.h" #include "gromacs/mdrunutility/multisim.h" #include "gromacs/mdrunutility/printtime.h" #include "gromacs/mdtypes/awh_history.h" #include "gromacs/mdtypes/awh_params.h" #include "gromacs/mdtypes/commrec.h" #include "gromacs/mdtypes/df_history.h" #include "gromacs/mdtypes/energyhistory.h" #include "gromacs/mdtypes/fcdata.h" #include "gromacs/mdtypes/forcebuffers.h" #include "gromacs/mdtypes/forcerec.h" #include "gromacs/mdtypes/group.h" #include "gromacs/mdtypes/inputrec.h" #include "gromacs/mdtypes/interaction_const.h" #include "gromacs/mdtypes/md_enums.h" #include "gromacs/mdtypes/mdatom.h" #include "gromacs/mdtypes/mdrunoptions.h" #include "gromacs/mdtypes/multipletimestepping.h" #include "gromacs/mdtypes/observableshistory.h" #include "gromacs/mdtypes/observablesreducer.h" #include "gromacs/mdtypes/pullhistory.h" #include "gromacs/mdtypes/simulation_workload.h" #include "gromacs/mdtypes/state.h" #include "gromacs/mdtypes/state_propagator_data_gpu.h" #include "gromacs/modularsimulator/energydata.h" #include "gromacs/nbnxm/gpu_data_mgmt.h" #include "gromacs/nbnxm/nbnxm.h" #include "gromacs/pbcutil/pbc.h" #include "gromacs/pulling/output.h" #include "gromacs/pulling/pull.h" #include "gromacs/swap/swapcoords.h" #include "gromacs/timing/wallcycle.h" #include "gromacs/timing/walltime_accounting.h" #include "gromacs/topology/atoms.h" #include "gromacs/topology/idef.h" #include "gromacs/topology/mtop_util.h" #include "gromacs/topology/topology.h" #include "gromacs/trajectory/trajectoryframe.h" #include "gromacs/utility/basedefinitions.h" #include "gromacs/utility/cstringutil.h" #include "gromacs/utility/fatalerror.h" #include "gromacs/utility/logger.h" #include "gromacs/utility/real.h" #include "gromacs/utility/smalloc.h" #include "legacysimulator.h" #include "replicaexchange.h" #include "shellfc.h" using gmx::SimulationSignaller; void gmx::LegacySimulator::do_md() { // TODO Historically, the EM and MD "integrators" used different // names for the t_inputrec *parameter, but these must have the // same name, now that it's a member of a struct. We use this ir // alias to avoid a large ripple of nearly useless changes. // t_inputrec is being replaced by IMdpOptionsProvider, so this // will go away eventually. const t_inputrec* ir = inputrec; double t, t0 = ir->init_t; gmx_bool bGStatEveryStep, bGStat, bCalcVir, bCalcEnerStep, bCalcEner; gmx_bool bNS = FALSE, bNStList, bStopCM, bFirstStep, bInitStep, bLastStep = FALSE; gmx_bool bDoExpanded = FALSE; gmx_bool do_ene, do_log, do_verbose; gmx_bool bMasterState; unsigned int force_flags; tensor force_vir = { { 0 } }, shake_vir = { { 0 } }, total_vir = { { 0 } }, pres = { { 0 } }; int i, m; rvec mu_tot; matrix pressureCouplingMu, M; gmx_repl_ex_t repl_ex = nullptr; gmx_global_stat_t gstat; gmx_shellfc_t* shellfc; gmx_bool bSumEkinhOld, bDoReplEx, bExchanged, bNeedRepartition; gmx_bool bTrotter; real dvdl_constr; std::vector<RVec> cbuf; matrix lastbox; int lamnew = 0; /* for FEP */ double cycles; real saved_conserved_quantity = 0; real last_ekin = 0; t_extmass MassQ; char sbuf[STEPSTRSIZE], sbuf2[STEPSTRSIZE]; /* PME load balancing data for GPU kernels */ gmx_bool bPMETune = FALSE; gmx_bool bPMETunePrinting = FALSE; bool bInteractiveMDstep = false; SimulationSignals signals; // Most global communnication stages don't propagate mdrun // signals, and will use this object to achieve that. SimulationSignaller nullSignaller(nullptr, nullptr, nullptr, false, false); if (!mdrunOptions.writeConfout) { // This is on by default, and the main known use case for // turning it off is for convenience in benchmarking, which is // something that should not show up in the general user // interface. GMX_LOG(mdlog.info) .asParagraph() .appendText( "The -noconfout functionality is deprecated, and may be removed in a " "future version."); } /* md-vv uses averaged full step velocities for T-control md-vv-avek uses averaged half step velocities for T-control (but full step ekin for P control) md uses averaged half step kinetic energies to determine temperature unless defined otherwise by GMX_EKIN_AVE_VEL; */ bTrotter = (EI_VV(ir->eI) && (inputrecNptTrotter(ir) || inputrecNphTrotter(ir) || inputrecNvtTrotter(ir))); const bool bRerunMD = false; int nstglobalcomm = computeGlobalCommunicationPeriod(mdlog, ir, cr); bGStatEveryStep = (nstglobalcomm == 1); const SimulationGroups* groups = &top_global.groups; std::unique_ptr<EssentialDynamics> ed = nullptr; if (opt2bSet("-ei", nfile, fnm)) { /* Initialize essential dynamics sampling */ ed = init_edsam(mdlog, opt2fn_null("-ei", nfile, fnm), opt2fn("-eo", nfile, fnm), top_global, *ir, cr, constr, state_global, observablesHistory, oenv, startingBehavior); } else if (observablesHistory->edsamHistory) { gmx_fatal(FARGS, "The checkpoint is from a run with essential dynamics sampling, " "but the current run did not specify the -ei option. " "Either specify the -ei option to mdrun, or do not use this checkpoint file."); } int* fep_state = MASTER(cr) ? &state_global->fep_state : nullptr; gmx::ArrayRef<real> lambda = MASTER(cr) ? state_global->lambda : gmx::ArrayRef<real>(); initialize_lambdas(fplog, ir->efep, ir->bSimTemp, *ir->fepvals, ir->simtempvals->temperatures, gmx::arrayRefFromArray(ir->opts.ref_t, ir->opts.ngtc), MASTER(cr), fep_state, lambda); Update upd(*ir, deform); bool doSimulatedAnnealing = false; { // TODO: Avoid changing inputrec (#3854) // Simulated annealing updates the reference temperature. auto* nonConstInputrec = const_cast<t_inputrec*>(inputrec); doSimulatedAnnealing = initSimulatedAnnealing(nonConstInputrec, &upd); } const bool useReplicaExchange = (replExParams.exchangeInterval > 0); t_fcdata& fcdata = *fr->fcdata; bool simulationsShareState = false; int nstSignalComm = nstglobalcomm; { // TODO This implementation of ensemble orientation restraints is nasty because // a user can't just do multi-sim with single-sim orientation restraints. bool usingEnsembleRestraints = (fcdata.disres->nsystems > 1) || ((ms != nullptr) && fcdata.orires); bool awhUsesMultiSim = (ir->bDoAwh && ir->awhParams->shareBiasMultisim() && (ms != nullptr)); // Replica exchange, ensemble restraints and AWH need all // simulations to remain synchronized, so they need // checkpoints and stop conditions to act on the same step, so // the propagation of such signals must take place between // simulations, not just within simulations. // TODO: Make algorithm initializers set these flags. simulationsShareState = useReplicaExchange || usingEnsembleRestraints || awhUsesMultiSim; if (simulationsShareState) { // Inter-simulation signal communication does not need to happen // often, so we use a minimum of 200 steps to reduce overhead. const int c_minimumInterSimulationSignallingInterval = 200; nstSignalComm = ((c_minimumInterSimulationSignallingInterval + nstglobalcomm - 1) / nstglobalcomm) * nstglobalcomm; } } if (startingBehavior != StartingBehavior::RestartWithAppending) { pleaseCiteCouplingAlgorithms(fplog, *ir); } gmx_mdoutf* outf = init_mdoutf(fplog, nfile, fnm, mdrunOptions, cr, outputProvider, mdModulesNotifiers, ir, top_global, oenv, wcycle, startingBehavior, simulationsShareState, ms); gmx::EnergyOutput energyOutput(mdoutf_get_fp_ene(outf), top_global, *ir, pull_work, mdoutf_get_fp_dhdl(outf), false, startingBehavior, simulationsShareState, mdModulesNotifiers); gstat = global_stat_init(ir); const auto& simulationWork = runScheduleWork->simulationWork; const bool useGpuForPme = simulationWork.useGpuPme; const bool useGpuForNonbonded = simulationWork.useGpuNonbonded; const bool useGpuForBufferOps = simulationWork.useGpuBufferOps; const bool useGpuForUpdate = simulationWork.useGpuUpdate; /* Check for polarizable models and flexible constraints */ shellfc = init_shell_flexcon(fplog, top_global, constr ? constr->numFlexibleConstraints() : 0, ir->nstcalcenergy, haveDDAtomOrdering(*cr), useGpuForPme); { double io = compute_io(ir, top_global.natoms, *groups, energyOutput.numEnergyTerms(), 1); if ((io > 2000) && MASTER(cr)) { fprintf(stderr, "\nWARNING: This run will generate roughly %.0f Mb of data\n\n", io); } } ObservablesReducer observablesReducer = observablesReducerBuilder->build(); ForceBuffers f(simulationWork.useMts, ((useGpuForNonbonded && useGpuForBufferOps) || useGpuForUpdate) ? PinningPolicy::PinnedIfSupported : PinningPolicy::CannotBePinned); const t_mdatoms* md = mdAtoms->mdatoms(); if (haveDDAtomOrdering(*cr)) { // Local state only becomes valid now. dd_init_local_state(*cr->dd, state_global, state); /* Distribute the charge groups over the nodes from the master node */ dd_partition_system(fplog, mdlog, ir->init_step, cr, TRUE, 1, state_global, top_global, *ir, imdSession, pull_work, state, &f, mdAtoms, top, fr, vsite, constr, nrnb, nullptr, FALSE); upd.updateAfterPartition(state->natoms, md->cFREEZE ? gmx::arrayRefFromArray(md->cFREEZE, md->nr) : gmx::ArrayRef<const unsigned short>(), md->cTC ? gmx::arrayRefFromArray(md->cTC, md->nr) : gmx::ArrayRef<const unsigned short>()); fr->longRangeNonbondeds->updateAfterPartition(*md); } else { state_change_natoms(state_global, state_global->natoms); /* Generate and initialize new topology */ mdAlgorithmsSetupAtomData(cr, *ir, top_global, top, fr, &f, mdAtoms, constr, vsite, shellfc); upd.updateAfterPartition(state->natoms, md->cFREEZE ? gmx::arrayRefFromArray(md->cFREEZE, md->nr) : gmx::ArrayRef<const unsigned short>(), md->cTC ? gmx::arrayRefFromArray(md->cTC, md->nr) : gmx::ArrayRef<const unsigned short>()); fr->longRangeNonbondeds->updateAfterPartition(*md); } std::unique_ptr<UpdateConstrainGpu> integrator; StatePropagatorDataGpu* stateGpu = fr->stateGpu; // TODO: the assertions below should be handled by UpdateConstraintsBuilder. if (useGpuForUpdate) { GMX_RELEASE_ASSERT(!haveDDAtomOrdering(*cr) || ddUsesUpdateGroups(*cr->dd) || constr == nullptr || constr->numConstraintsTotal() == 0, "Constraints in domain decomposition are only supported with update " "groups if using GPU update.\n"); GMX_RELEASE_ASSERT(ir->eConstrAlg != ConstraintAlgorithm::Shake || constr == nullptr || constr->numConstraintsTotal() == 0, "SHAKE is not supported with GPU update."); GMX_RELEASE_ASSERT(useGpuForPme || (useGpuForNonbonded && simulationWork.useGpuBufferOps), "Either PME or short-ranged non-bonded interaction tasks must run on " "the GPU to use GPU update.\n"); GMX_RELEASE_ASSERT(ir->eI == IntegrationAlgorithm::MD, "Only the md integrator is supported with the GPU update.\n"); GMX_RELEASE_ASSERT( ir->etc != TemperatureCoupling::NoseHoover, "Nose-Hoover temperature coupling is not supported with the GPU update.\n"); GMX_RELEASE_ASSERT( ir->epc == PressureCoupling::No || ir->epc == PressureCoupling::ParrinelloRahman || ir->epc == PressureCoupling::Berendsen || ir->epc == PressureCoupling::CRescale, "Only Parrinello-Rahman, Berendsen, and C-rescale pressure coupling are supported " "with the GPU update.\n"); GMX_RELEASE_ASSERT(!md->haveVsites, "Virtual sites are not supported with the GPU update.\n"); GMX_RELEASE_ASSERT(ed == nullptr, "Essential dynamics is not supported with the GPU update.\n"); GMX_RELEASE_ASSERT(!ir->bPull || !pull_have_constraint(*ir->pull), "Constraints pulling is not supported with the GPU update.\n"); GMX_RELEASE_ASSERT(fcdata.orires == nullptr, "Orientation restraints are not supported with the GPU update.\n"); GMX_RELEASE_ASSERT( ir->efep == FreeEnergyPerturbationType::No || (!haveFepPerturbedMasses(top_global) && !havePerturbedConstraints(top_global)), "Free energy perturbation of masses and constraints are not supported with the GPU " "update."); if (constr != nullptr && constr->numConstraintsTotal() > 0) { GMX_LOG(mdlog.info) .asParagraph() .appendText("Updating coordinates and applying constraints on the GPU."); } else { GMX_LOG(mdlog.info).asParagraph().appendText("Updating coordinates on the GPU."); } GMX_RELEASE_ASSERT(fr->deviceStreamManager != nullptr, "Device stream manager should be initialized in order to use GPU " "update-constraints."); GMX_RELEASE_ASSERT( fr->deviceStreamManager->streamIsValid(gmx::DeviceStreamType::UpdateAndConstraints), "Update stream should be initialized in order to use GPU " "update-constraints."); integrator = std::make_unique<UpdateConstrainGpu>( *ir, top_global, ekind->ngtc, fr->deviceStreamManager->context(), fr->deviceStreamManager->stream(gmx::DeviceStreamType::UpdateAndConstraints), wcycle); stateGpu->setXUpdatedOnDeviceEvent(integrator->xUpdatedOnDeviceEvent()); integrator->setPbc(PbcType::Xyz, state->box); } if (useGpuForPme || (useGpuForNonbonded && useGpuForBufferOps) || useGpuForUpdate) { changePinningPolicy(&state->x, PinningPolicy::PinnedIfSupported); } if (useGpuForUpdate) { changePinningPolicy(&state->v, PinningPolicy::PinnedIfSupported); } // NOTE: The global state is no longer used at this point. // But state_global is still used as temporary storage space for writing // the global state to file and potentially for replica exchange. // (Global topology should persist.) update_mdatoms(mdAtoms->mdatoms(), state->lambda[FreeEnergyPerturbationCouplingType::Mass]); if (ir->bExpanded) { /* Check nstexpanded here, because the grompp check was broken */ if (ir->expandedvals->nstexpanded % ir->nstcalcenergy != 0) { gmx_fatal(FARGS, "With expanded ensemble, nstexpanded should be a multiple of nstcalcenergy"); } init_expanded_ensemble(startingBehavior != StartingBehavior::NewSimulation, ir, state->dfhist); } if (MASTER(cr)) { EnergyData::initializeEnergyHistory(startingBehavior, observablesHistory, &energyOutput); } preparePrevStepPullCom(ir, pull_work, gmx::arrayRefFromArray(md->massT, md->nr), state, state_global, cr, startingBehavior != StartingBehavior::NewSimulation); // TODO: Remove this by converting AWH into a ForceProvider auto awh = prepareAwhModule(fplog, *ir, state_global, cr, ms, startingBehavior != StartingBehavior::NewSimulation, shellfc != nullptr, opt2fn("-awh", nfile, fnm), pull_work); if (useReplicaExchange && MASTER(cr)) { repl_ex = init_replica_exchange(fplog, ms, top_global.natoms, ir, replExParams); } /* PME tuning is only supported in the Verlet scheme, with PME for * Coulomb. It is not supported with only LJ PME. */ bPMETune = (mdrunOptions.tunePme && EEL_PME(fr->ic->eeltype) && !mdrunOptions.reproducible && ir->cutoff_scheme != CutoffScheme::Group); pme_load_balancing_t* pme_loadbal = nullptr; if (bPMETune) { pme_loadbal_init( &pme_loadbal, cr, mdlog, *ir, state->box, *fr->ic, *fr->nbv, fr->pmedata, fr->nbv->useGpu()); } if (!ir->bContinuation) { if (state->flags & enumValueToBitMask(StateEntry::V)) { auto v = makeArrayRef(state->v); /* Set the velocities of vsites, shells and frozen atoms to zero */ for (i = 0; i < md->homenr; i++) { if (md->ptype[i] == ParticleType::Shell) { clear_rvec(v[i]); } else if (md->cFREEZE) { for (m = 0; m < DIM; m++) { if (ir->opts.nFreeze[md->cFREEZE[i]][m]) { v[i][m] = 0; } } } } } if (constr) { /* Constrain the initial coordinates and velocities */ do_constrain_first(fplog, constr, ir, md->nr, md->homenr, state->x.arrayRefWithPadding(), state->v.arrayRefWithPadding(), state->box, state->lambda[FreeEnergyPerturbationCouplingType::Bonded]); } } const int nstfep = computeFepPeriod(*ir, replExParams); /* Be REALLY careful about what flags you set here. You CANNOT assume * this is the first step, since we might be restarting from a checkpoint, * and in that case we should not do any modifications to the state. */ bStopCM = (ir->comm_mode != ComRemovalAlgorithm::No && !ir->bContinuation); // When restarting from a checkpoint, it can be appropriate to // initialize ekind from quantities in the checkpoint. Otherwise, // compute_globals must initialize ekind before the simulation // starts/restarts. However, only the master rank knows what was // found in the checkpoint file, so we have to communicate in // order to coordinate the restart. // // TODO Consider removing this communication if/when checkpoint // reading directly follows .tpr reading, because all ranks can // agree on hasReadEkinState at that time. bool hasReadEkinState = MASTER(cr) ? state_global->ekinstate.hasReadEkinState : false; if (PAR(cr)) { gmx_bcast(sizeof(hasReadEkinState), &hasReadEkinState, cr->mpi_comm_mygroup); } if (hasReadEkinState) { restore_ekinstate_from_state(cr, ekind, &state_global->ekinstate); } unsigned int cglo_flags = (CGLO_TEMPERATURE | CGLO_GSTAT | (EI_VV(ir->eI) ? CGLO_PRESSURE : 0) | (EI_VV(ir->eI) ? CGLO_CONSTRAINT : 0) | (hasReadEkinState ? CGLO_READEKIN : 0)); bSumEkinhOld = FALSE; t_vcm vcm(top_global.groups, *ir); reportComRemovalInfo(fplog, vcm); int64_t step = ir->init_step; int64_t step_rel = 0; /* To minimize communication, compute_globals computes the COM velocity * and the kinetic energy for the velocities without COM motion removed. * Thus to get the kinetic energy without the COM contribution, we need * to call compute_globals twice. */ for (int cgloIteration = 0; cgloIteration < (bStopCM ? 2 : 1); cgloIteration++) { unsigned int cglo_flags_iteration = cglo_flags; if (bStopCM && cgloIteration == 0) { cglo_flags_iteration |= CGLO_STOPCM; cglo_flags_iteration &= ~CGLO_TEMPERATURE; } compute_globals(gstat, cr, ir, fr, ekind, makeConstArrayRef(state->x), makeConstArrayRef(state->v), state->box, md, nrnb, &vcm, nullptr, enerd, force_vir, shake_vir, total_vir, pres, &nullSignaller, state->box, &bSumEkinhOld, cglo_flags_iteration, step, &observablesReducer); // Clean up after pre-step use of compute_globals() observablesReducer.markAsReadyToReduce(); if (cglo_flags_iteration & CGLO_STOPCM) { /* At initialization, do not pass x with acceleration-correction mode * to avoid (incorrect) correction of the initial coordinates. */ auto x = (vcm.mode == ComRemovalAlgorithm::LinearAccelerationCorrection) ? ArrayRef<RVec>() : makeArrayRef(state->x); process_and_stopcm_grp(fplog, &vcm, *md, x, makeArrayRef(state->v)); inc_nrnb(nrnb, eNR_STOPCM, md->homenr); } } if (ir->eI == IntegrationAlgorithm::VVAK) { /* a second call to get the half step temperature initialized as well */ /* we do the same call as above, but turn the pressure off -- internally to compute_globals, this is recognized as a velocity verlet half-step kinetic energy calculation. This minimized excess variables, but perhaps loses some logic?*/ compute_globals(gstat, cr, ir, fr, ekind, makeConstArrayRef(state->x), makeConstArrayRef(state->v), state->box, md, nrnb, &vcm, nullptr, enerd, force_vir, shake_vir, total_vir, pres, &nullSignaller, state->box, &bSumEkinhOld, cglo_flags & ~CGLO_PRESSURE, step, &observablesReducer); // Clean up after pre-step use of compute_globals() observablesReducer.markAsReadyToReduce(); } /* Calculate the initial half step temperature, and save the ekinh_old */ if (startingBehavior == StartingBehavior::NewSimulation) { for (i = 0; (i < ir->opts.ngtc); i++) { copy_mat(ekind->tcstat[i].ekinh, ekind->tcstat[i].ekinh_old); } } /* need to make an initiation call to get the Trotter variables set, as well as other constants for non-trotter temperature control */ auto trotter_seq = init_npt_vars(ir, state, &MassQ, bTrotter); if (MASTER(cr)) { if (!ir->bContinuation) { if (constr && ir->eConstrAlg == ConstraintAlgorithm::Lincs) { fprintf(fplog, "RMS relative constraint deviation after constraining: %.2e\n", constr->rmsd()); } if (EI_STATE_VELOCITY(ir->eI)) { real temp = enerd->term[F_TEMP]; if (ir->eI != IntegrationAlgorithm::VV) { /* Result of Ekin averaged over velocities of -half * and +half step, while we only have -half step here. */ temp *= 2; } fprintf(fplog, "Initial temperature: %g K\n", temp); } } char tbuf[20]; fprintf(stderr, "starting mdrun '%s'\n", *(top_global.name)); if (ir->nsteps >= 0) { sprintf(tbuf, "%8.1f", (ir->init_step + ir->nsteps) * ir->delta_t); } else { sprintf(tbuf, "%s", "infinite"); } if (ir->init_step > 0) { fprintf(stderr, "%s steps, %s ps (continuing from step %s, %8.1f ps).\n", gmx_step_str(ir->init_step + ir->nsteps, sbuf), tbuf, gmx_step_str(ir->init_step, sbuf2), ir->init_step * ir->delta_t); } else { fprintf(stderr, "%s steps, %s ps.\n", gmx_step_str(ir->nsteps, sbuf), tbuf); } fprintf(fplog, "\n"); } walltime_accounting_start_time(walltime_accounting); wallcycle_start(wcycle, WallCycleCounter::Run); print_start(fplog, cr, walltime_accounting, "mdrun"); /*********************************************************** * * Loop over MD steps * ************************************************************/ bFirstStep = TRUE; /* Skip the first Nose-Hoover integration when we get the state from tpx */ bInitStep = startingBehavior == StartingBehavior::NewSimulation || EI_VV(ir->eI); bSumEkinhOld = FALSE; bExchanged = FALSE; bNeedRepartition = FALSE; auto stopHandler = stopHandlerBuilder->getStopHandlerMD( compat::not_null<SimulationSignal*>(&signals[eglsSTOPCOND]), simulationsShareState, MASTER(cr), ir->nstlist, mdrunOptions.reproducible, nstSignalComm, mdrunOptions.maximumHoursToRun, ir->nstlist == 0, fplog, step, bNS, walltime_accounting); auto checkpointHandler = std::make_unique<CheckpointHandler>( compat::make_not_null<SimulationSignal*>(&signals[eglsCHKPT]), simulationsShareState, ir->nstlist == 0, MASTER(cr), mdrunOptions.writeConfout, mdrunOptions.checkpointOptions.period); const bool resetCountersIsLocal = true; auto resetHandler = std::make_unique<ResetHandler>( compat::make_not_null<SimulationSignal*>(&signals[eglsRESETCOUNTERS]), !resetCountersIsLocal, ir->nsteps, MASTER(cr), mdrunOptions.timingOptions.resetHalfway, mdrunOptions.maximumHoursToRun, mdlog, wcycle, walltime_accounting); const DDBalanceRegionHandler ddBalanceRegionHandler(cr); if (MASTER(cr) && isMultiSim(ms) && !useReplicaExchange) { logInitialMultisimStatus(ms, cr, mdlog, simulationsShareState, ir->nsteps, ir->init_step); } /* and stop now if we should */ bLastStep = (bLastStep || (ir->nsteps >= 0 && step_rel > ir->nsteps)); while (!bLastStep) { /* Determine if this is a neighbor search step */ bNStList = (ir->nstlist > 0 && step % ir->nstlist == 0); if (bPMETune && bNStList) { // This has to be here because PME load balancing is called so early. // TODO: Move to after all booleans are defined. if (useGpuForUpdate && !bFirstStep) { stateGpu->copyCoordinatesFromGpu(state->x, AtomLocality::Local); stateGpu->waitCoordinatesReadyOnHost(AtomLocality::Local); } /* PME grid + cut-off optimization with GPUs or PME nodes */ pme_loadbal_do(pme_loadbal, cr, (mdrunOptions.verbose && MASTER(cr)) ? stderr : nullptr, fplog, mdlog, *ir, fr, state->box, state->x, wcycle, step, step_rel, &bPMETunePrinting, simulationWork.useGpuPmePpCommunication); } wallcycle_start(wcycle, WallCycleCounter::Step); bLastStep = (step_rel == ir->nsteps); t = t0 + step * ir->delta_t; // TODO Refactor this, so that nstfep does not need a default value of zero if (ir->efep != FreeEnergyPerturbationType::No || ir->bSimTemp) { /* find and set the current lambdas */ state->lambda = currentLambdas(step, *(ir->fepvals), state->fep_state); bDoExpanded = (do_per_step(step, ir->expandedvals->nstexpanded) && (ir->bExpanded) && (!bFirstStep)); } bDoReplEx = (useReplicaExchange && (step > 0) && !bLastStep && do_per_step(step, replExParams.exchangeInterval)); if (doSimulatedAnnealing) { // TODO: Avoid changing inputrec (#3854) // Simulated annealing updates the reference temperature. auto* nonConstInputrec = const_cast<t_inputrec*>(inputrec); update_annealing_target_temp(nonConstInputrec, t, &upd); } /* Stop Center of Mass motion */ bStopCM = (ir->comm_mode != ComRemovalAlgorithm::No && do_per_step(step, ir->nstcomm)); /* Determine whether or not to do Neighbour Searching */ bNS = (bFirstStep || bNStList || bExchanged || bNeedRepartition); /* Note that the stopHandler will cause termination at nstglobalcomm * steps. Since this concides with nstcalcenergy, nsttcouple and/or * nstpcouple steps, we have computed the half-step kinetic energy * of the previous step and can always output energies at the last step. */ bLastStep = bLastStep || stopHandler->stoppingAfterCurrentStep(bNS); /* do_log triggers energy and virial calculation. Because this leads * to different code paths, forces can be different. Thus for exact * continuation we should avoid extra log output. * Note that the || bLastStep can result in non-exact continuation * beyond the last step. But we don't consider that to be an issue. */ do_log = (do_per_step(step, ir->nstlog) || (bFirstStep && startingBehavior == StartingBehavior::NewSimulation) || bLastStep); do_verbose = mdrunOptions.verbose && (step % mdrunOptions.verboseStepPrintInterval == 0 || bFirstStep || bLastStep); // On search steps, when doing the update on the GPU, copy // the coordinates and velocities to the host unless they are // already there (ie on the first step and after replica // exchange). if (useGpuForUpdate && bNS && !bFirstStep && !bExchanged) { stateGpu->copyVelocitiesFromGpu(state->v, AtomLocality::Local); stateGpu->copyCoordinatesFromGpu(state->x, AtomLocality::Local); stateGpu->waitVelocitiesReadyOnHost(AtomLocality::Local); stateGpu->waitCoordinatesReadyOnHost(AtomLocality::Local); } // We only need to calculate virtual velocities if we are writing them in the current step const bool needVirtualVelocitiesThisStep = (vsite != nullptr) && (do_per_step(step, ir->nstvout) || checkpointHandler->isCheckpointingStep()); if (vsite != nullptr) { // Virtual sites need to be updated before domain decomposition and forces are calculated wallcycle_start(wcycle, WallCycleCounter::VsiteConstr); // md-vv calculates virtual velocities once it has full-step real velocities vsite->construct(state->x, state->v, state->box, (!EI_VV(inputrec->eI) && needVirtualVelocitiesThisStep) ? VSiteOperation::PositionsAndVelocities : VSiteOperation::Positions); wallcycle_stop(wcycle, WallCycleCounter::VsiteConstr); } if (bNS && !(bFirstStep && ir->bContinuation)) { bMasterState = FALSE; /* Correct the new box if it is too skewed */ if (inputrecDynamicBox(ir)) { if (correct_box(fplog, step, state->box)) { bMasterState = TRUE; } } // If update is offloaded, and the box was changed either // above or in a replica exchange on the previous step, // the GPU Update object should be informed if (useGpuForUpdate && (bMasterState || bExchanged)) { integrator->setPbc(PbcType::Xyz, state->box); } if (haveDDAtomOrdering(*cr) && bMasterState) { dd_collect_state(cr->dd, state, state_global); } if (haveDDAtomOrdering(*cr)) { /* Repartition the domain decomposition */ dd_partition_system(fplog, mdlog, step, cr, bMasterState, nstglobalcomm, state_global, top_global, *ir, imdSession, pull_work, state, &f, mdAtoms, top, fr, vsite, constr, nrnb, wcycle, do_verbose && !bPMETunePrinting); upd.updateAfterPartition(state->natoms, md->cFREEZE ? gmx::arrayRefFromArray(md->cFREEZE, md->nr) : gmx::ArrayRef<const unsigned short>(), md->cTC ? gmx::arrayRefFromArray(md->cTC, md->nr) : gmx::ArrayRef<const unsigned short>()); fr->longRangeNonbondeds->updateAfterPartition(*md); } } // Allocate or re-size GPU halo exchange object, if necessary if (bNS && simulationWork.havePpDomainDecomposition && simulationWork.useGpuHaloExchange) { GMX_RELEASE_ASSERT(fr->deviceStreamManager != nullptr, "GPU device manager has to be initialized to use GPU " "version of halo exchange."); constructGpuHaloExchange(mdlog, *cr, *fr->deviceStreamManager, wcycle); } if (MASTER(cr) && do_log) { gmx::EnergyOutput::printHeader( fplog, step, t); /* can we improve the information printed here? */ } if (ir->efep != FreeEnergyPerturbationType::No) { update_mdatoms(mdAtoms->mdatoms(), state->lambda[FreeEnergyPerturbationCouplingType::Mass]); } if (bExchanged) { /* We need the kinetic energy at minus the half step for determining * the full step kinetic energy and possibly for T-coupling.*/ /* This may not be quite working correctly yet . . . . */ int cglo_flags = CGLO_GSTAT | CGLO_TEMPERATURE; compute_globals(gstat, cr, ir, fr, ekind, makeConstArrayRef(state->x), makeConstArrayRef(state->v), state->box, md, nrnb, &vcm, wcycle, enerd, nullptr, nullptr, nullptr, nullptr, &nullSignaller, state->box, &bSumEkinhOld, cglo_flags, step, &observablesReducer); } clear_mat(force_vir); checkpointHandler->decideIfCheckpointingThisStep(bNS, bFirstStep, bLastStep); /* Determine the energy and pressure: * at nstcalcenergy steps and at energy output steps (set below). */ if (EI_VV(ir->eI) && (!bInitStep)) { bCalcEnerStep = do_per_step(step, ir->nstcalcenergy); bCalcVir = bCalcEnerStep || (ir->epc != PressureCoupling::No && (do_per_step(step, ir->nstpcouple) || do_per_step(step - 1, ir->nstpcouple))); } else { bCalcEnerStep = do_per_step(step, ir->nstcalcenergy); bCalcVir = bCalcEnerStep || (ir->epc != PressureCoupling::No && do_per_step(step, ir->nstpcouple)); } bCalcEner = bCalcEnerStep; do_ene = (do_per_step(step, ir->nstenergy) || bLastStep); if (do_ene || do_log || bDoReplEx) { bCalcVir = TRUE; bCalcEner = TRUE; } // bCalcEner is only here for when the last step is not a mulitple of nstfep const bool computeDHDL = ((ir->efep != FreeEnergyPerturbationType::No || ir->bSimTemp) && (do_per_step(step, nstfep) || bCalcEner)); /* Do we need global communication ? */ bGStat = (bCalcVir || bCalcEner || bStopCM || do_per_step(step, nstglobalcomm) || (EI_VV(ir->eI) && inputrecNvtTrotter(ir) && do_per_step(step - 1, nstglobalcomm))); force_flags = (GMX_FORCE_STATECHANGED | ((inputrecDynamicBox(ir)) ? GMX_FORCE_DYNAMICBOX : 0) | GMX_FORCE_ALLFORCES | (bCalcVir ? GMX_FORCE_VIRIAL : 0) | (bCalcEner ? GMX_FORCE_ENERGY : 0) | (computeDHDL ? GMX_FORCE_DHDL : 0)); if (simulationWork.useMts && !do_per_step(step, ir->nstfout)) { // TODO: merge this with stepWork.useOnlyMtsCombinedForceBuffer force_flags |= GMX_FORCE_DO_NOT_NEED_NORMAL_FORCE; } if (shellfc) { /* Now is the time to relax the shells */ relax_shell_flexcon(fplog, cr, ms, mdrunOptions.verbose, enforcedRotation, step, ir, imdSession, pull_work, bNS, force_flags, top, constr, enerd, state->natoms, state->x.arrayRefWithPadding(), state->v.arrayRefWithPadding(), state->box, state->lambda, &state->hist, &f.view(), force_vir, *md, fr->longRangeNonbondeds.get(), nrnb, wcycle, shellfc, fr, runScheduleWork, t, mu_tot, vsite, ddBalanceRegionHandler); } else { /* The AWH history need to be saved _before_ doing force calculations where the AWH bias is updated (or the AWH update will be performed twice for one step when continuing). It would be best to call this update function from do_md_trajectory_writing but that would occur after do_force. One would have to divide the update_awh function into one function applying the AWH force and one doing the AWH bias update. The update AWH bias function could then be called after do_md_trajectory_writing (then containing update_awh_history). The checkpointing will in the future probably moved to the start of the md loop which will rid of this issue. */ if (awh && checkpointHandler->isCheckpointingStep() && MASTER(cr)) { awh->updateHistory(state_global->awhHistory.get()); } /* The coordinates (x) are shifted (to get whole molecules) * in do_force. * This is parallellized as well, and does communication too. * Check comments in sim_util.c */ do_force(fplog, cr, ms, *ir, awh.get(), enforcedRotation, imdSession, pull_work, step, nrnb, wcycle, top, state->box, state->x.arrayRefWithPadding(), &state->hist, &f.view(), force_vir, md, enerd, state->lambda, fr, runScheduleWork, vsite, mu_tot, t, ed ? ed->getLegacyED() : nullptr, fr->longRangeNonbondeds.get(), (bNS ? GMX_FORCE_NS : 0) | force_flags, ddBalanceRegionHandler); } // VV integrators do not need the following velocity half step // if it is the first step after starting from a checkpoint. // That is, the half step is needed on all other steps, and // also the first step when starting from a .tpr file. if (EI_VV(ir->eI)) { integrateVVFirstStep(step, bFirstStep, bInitStep, startingBehavior, nstglobalcomm, ir, fr, cr, state, mdAtoms->mdatoms(), &fcdata, &MassQ, &vcm, enerd, &observablesReducer, ekind, gstat, &last_ekin, bCalcVir, total_vir, shake_vir, force_vir, pres, M, do_log, do_ene, bCalcEner, bGStat, bStopCM, bTrotter, bExchanged, &bSumEkinhOld, &saved_conserved_quantity, &f, &upd, constr, &nullSignaller, trotter_seq, nrnb, fplog, wcycle); if (vsite != nullptr && needVirtualVelocitiesThisStep) { // Positions were calculated earlier wallcycle_start(wcycle, WallCycleCounter::VsiteConstr); vsite->construct(state->x, state->v, state->box, VSiteOperation::Velocities); wallcycle_stop(wcycle, WallCycleCounter::VsiteConstr); } } /* ######## END FIRST UPDATE STEP ############## */ /* ######## If doing VV, we now have v(dt) ###### */ if (bDoExpanded) { /* perform extended ensemble sampling in lambda - we don't actually move to the new state before outputting statistics, but if performing simulated tempering, we do update the velocities and the tau_t. */ // TODO: Avoid changing inputrec (#3854) // Simulated tempering updates the reference temperature. // Expanded ensemble without simulated tempering does not change the inputrec. auto* nonConstInputrec = const_cast<t_inputrec*>(inputrec); lamnew = ExpandedEnsembleDynamics(fplog, nonConstInputrec, enerd, state, &MassQ, state->fep_state, state->dfhist, step, state->v.rvec_array(), md->homenr, md->cTC ? gmx::arrayRefFromArray(md->cTC, md->nr) : gmx::ArrayRef<const unsigned short>()); /* history is maintained in state->dfhist, but state_global is what is sent to trajectory and log output */ if (MASTER(cr)) { copy_df_history(state_global->dfhist, state->dfhist); } } // Copy coordinate from the GPU for the output/checkpointing if the update is offloaded and // coordinates have not already been copied for i) search or ii) CPU force tasks. if (useGpuForUpdate && !bNS && !runScheduleWork->domainWork.haveCpuLocalForceWork && (do_per_step(step, ir->nstxout) || do_per_step(step, ir->nstxout_compressed) || checkpointHandler->isCheckpointingStep())) { stateGpu->copyCoordinatesFromGpu(state->x, AtomLocality::Local); stateGpu->waitCoordinatesReadyOnHost(AtomLocality::Local); } // Copy velocities if needed for the output/checkpointing. // NOTE: Copy on the search steps is done at the beginning of the step. if (useGpuForUpdate && !bNS && (do_per_step(step, ir->nstvout) || checkpointHandler->isCheckpointingStep())) { stateGpu->copyVelocitiesFromGpu(state->v, AtomLocality::Local); stateGpu->waitVelocitiesReadyOnHost(AtomLocality::Local); } // Copy forces for the output if the forces were reduced on the GPU (not the case on virial steps) // and update is offloaded hence forces are kept on the GPU for update and have not been // already transferred in do_force(). // TODO: There should be an improved, explicit mechanism that ensures this copy is only executed // when the forces are ready on the GPU -- the same synchronizer should be used as the one // prior to GPU update. // TODO: When the output flags will be included in step workload, this copy can be combined with the // copy call in do_force(...). // NOTE: The forces should not be copied here if the vsites are present, since they were modified // on host after the D2H copy in do_force(...). if (runScheduleWork->stepWork.useGpuFBufferOps && (simulationWork.useGpuUpdate && !vsite) && do_per_step(step, ir->nstfout)) { stateGpu->copyForcesFromGpu(f.view().force(), AtomLocality::Local); stateGpu->waitForcesReadyOnHost(AtomLocality::Local); } /* Now we have the energies and forces corresponding to the * coordinates at time t. We must output all of this before * the update. */ do_md_trajectory_writing(fplog, cr, nfile, fnm, step, step_rel, t, ir, state, state_global, observablesHistory, top_global, fr, outf, energyOutput, ekind, f.view().force(), checkpointHandler->isCheckpointingStep(), bRerunMD, bLastStep, mdrunOptions.writeConfout, bSumEkinhOld); /* Check if IMD step and do IMD communication, if bIMD is TRUE. */ bInteractiveMDstep = imdSession->run(step, bNS, state->box, state->x, t); /* kludge -- virial is lost with restart for MTTK NPT control. Must reload (saved earlier). */ if (startingBehavior != StartingBehavior::NewSimulation && bFirstStep && (inputrecNptTrotter(ir) || inputrecNphTrotter(ir))) { copy_mat(state->svir_prev, shake_vir); copy_mat(state->fvir_prev, force_vir); } stopHandler->setSignal(); resetHandler->setSignal(walltime_accounting); if (bGStat || !PAR(cr)) { /* In parallel we only have to check for checkpointing in steps * where we do global communication, * otherwise the other nodes don't know. */ checkpointHandler->setSignal(walltime_accounting); } /* ######### START SECOND UPDATE STEP ################# */ /* at the start of step, randomize or scale the velocities ((if vv. Restriction of Andersen controlled in preprocessing */ if (ETC_ANDERSEN(ir->etc)) /* keep this outside of update_tcouple because of the extra info required to pass */ { gmx_bool bIfRandomize; bIfRandomize = update_randomize_velocities(ir, step, cr, md->homenr, md->cTC ? gmx::arrayRefFromArray(md->cTC, md->nr) : gmx::ArrayRef<const unsigned short>(), gmx::arrayRefFromArray(md->invmass, md->nr), state->v, &upd, constr); /* if we have constraints, we have to remove the kinetic energy parallel to the bonds */ if (constr && bIfRandomize) { constrain_velocities(constr, do_log, do_ene, step, state, nullptr, false, nullptr); } } /* Box is changed in update() when we do pressure coupling, * but we should still use the old box for energy corrections and when * writing it to the energy file, so it matches the trajectory files for * the same timestep above. Make a copy in a separate array. */ copy_mat(state->box, lastbox); dvdl_constr = 0; if (!useGpuForUpdate) { wallcycle_start(wcycle, WallCycleCounter::Update); } /* UPDATE PRESSURE VARIABLES IN TROTTER FORMULATION WITH CONSTRAINTS */ if (bTrotter) { trotter_update(ir, step, ekind, enerd, state, total_vir, md->homenr, md->cTC ? gmx::arrayRefFromArray(md->cTC, md->nr) : gmx::ArrayRef<const unsigned short>(), gmx::arrayRefFromArray(md->invmass, md->nr), &MassQ, trotter_seq, TrotterSequence::Three); /* We can only do Berendsen coupling after we have summed * the kinetic energy or virial. Since the happens * in global_state after update, we should only do it at * step % nstlist = 1 with bGStatEveryStep=FALSE. */ } else { update_tcouple(step, ir, state, ekind, &MassQ, md->homenr, md->cTC ? gmx::arrayRefFromArray(md->cTC, md->nr) : gmx::ArrayRef<const unsigned short>()); update_pcouple_before_coordinates(fplog, step, ir, state, pressureCouplingMu, M, bInitStep); } /* With leap-frog type integrators we compute the kinetic energy * at a whole time step as the average of the half-time step kinetic * energies of two subsequent steps. Therefore we need to compute the * half step kinetic energy also if we need energies at the next step. */ const bool needHalfStepKineticEnergy = (!EI_VV(ir->eI) && (do_per_step(step + 1, nstglobalcomm) || step_rel + 1 == ir->nsteps)); // Parrinello-Rahman requires the pressure to be availible before the update to compute // the velocity scaling matrix. Hence, it runs one step after the nstpcouple step. const bool doParrinelloRahman = (ir->epc == PressureCoupling::ParrinelloRahman && do_per_step(step + ir->nstpcouple - 1, ir->nstpcouple)); if (EI_VV(ir->eI)) { GMX_ASSERT(!useGpuForUpdate, "GPU update is not supported with VVAK integrator."); integrateVVSecondStep(step, ir, fr, cr, state, mdAtoms->mdatoms(), &fcdata, &MassQ, &vcm, pull_work, enerd, &observablesReducer, ekind, gstat, &dvdl_constr, bCalcVir, total_vir, shake_vir, force_vir, pres, M, lastbox, do_log, do_ene, bGStat, &bSumEkinhOld, &f, &cbuf, &upd, constr, &nullSignaller, trotter_seq, nrnb, wcycle); } else { if (useGpuForUpdate) { // On search steps, update handles to device vectors if (bNS && (bFirstStep || haveDDAtomOrdering(*cr) || bExchanged)) { integrator->set(stateGpu->getCoordinates(), stateGpu->getVelocities(), stateGpu->getForces(), top->idef, *md); // Copy data to the GPU after buffers might have being reinitialized /* The velocity copy is redundant if we had Center-of-Mass motion removed on * the previous step. We don't check that now. */ stateGpu->copyVelocitiesToGpu(state->v, AtomLocality::Local); if (bExchanged || (!runScheduleWork->stepWork.haveGpuPmeOnThisRank && !runScheduleWork->stepWork.useGpuXBufferOps)) { stateGpu->copyCoordinatesToGpu(state->x, AtomLocality::Local); } } if ((simulationWork.useGpuPme && simulationWork.useCpuPmePpCommunication) || (!runScheduleWork->stepWork.useGpuFBufferOps)) { // The PME forces were recieved to the host, and reduced on the CPU with the // rest of the forces computed on the GPU, so the final forces have to be copied // back to the GPU. Or the buffer ops were not offloaded this step, so the // forces are on the host and have to be copied stateGpu->copyForcesToGpu(f.view().force(), AtomLocality::Local); } const bool doTemperatureScaling = (ir->etc != TemperatureCoupling::No && do_per_step(step + ir->nsttcouple - 1, ir->nsttcouple)); // This applies Leap-Frog, LINCS and SETTLE in succession integrator->integrate(stateGpu->getLocalForcesReadyOnDeviceEvent( runScheduleWork->stepWork, runScheduleWork->simulationWork), ir->delta_t, true, bCalcVir, shake_vir, doTemperatureScaling, ekind->tcstat, doParrinelloRahman, ir->nstpcouple * ir->delta_t, M); } else { /* With multiple time stepping we need to do an additional normal * update step to obtain the virial, as the actual MTS integration * using an acceleration where the slow forces are multiplied by mtsFactor. * Using that acceleration would result in a virial with the slow * force contribution would be a factor mtsFactor too large. */ if (simulationWork.useMts && bCalcVir && constr != nullptr) { upd.update_for_constraint_virial(*ir, md->homenr, md->havePartiallyFrozenAtoms, gmx::arrayRefFromArray(md->invmass, md->nr), gmx::arrayRefFromArray(md->invMassPerDim, md->nr), *state, f.view().forceWithPadding(), *ekind); constrain_coordinates(constr, do_log, do_ene, step, state, upd.xp()->arrayRefWithPadding(), &dvdl_constr, bCalcVir, shake_vir); } ArrayRefWithPadding<const RVec> forceCombined = (simulationWork.useMts && step % ir->mtsLevels[1].stepFactor == 0) ? f.view().forceMtsCombinedWithPadding() : f.view().forceWithPadding(); upd.update_coords(*ir, step, md->homenr, md->havePartiallyFrozenAtoms, gmx::arrayRefFromArray(md->ptype, md->nr), gmx::arrayRefFromArray(md->invmass, md->nr), gmx::arrayRefFromArray(md->invMassPerDim, md->nr), state, forceCombined, &fcdata, ekind, M, etrtPOSITION, cr, constr != nullptr); wallcycle_stop(wcycle, WallCycleCounter::Update); constrain_coordinates(constr, do_log, do_ene, step, state, upd.xp()->arrayRefWithPadding(), &dvdl_constr, bCalcVir && !simulationWork.useMts, shake_vir); upd.update_sd_second_half(*ir, step, &dvdl_constr, md->homenr, gmx::arrayRefFromArray(md->ptype, md->nr), gmx::arrayRefFromArray(md->invmass, md->nr), state, cr, nrnb, wcycle, constr, do_log, do_ene); upd.finish_update( *ir, md->havePartiallyFrozenAtoms, md->homenr, state, wcycle, constr != nullptr); } if (ir->bPull && ir->pull->bSetPbcRefToPrevStepCOM) { updatePrevStepPullCom(pull_work, state->pull_com_prev_step); } enerd->term[F_DVDL_CONSTR] += dvdl_constr; } /* ############## IF NOT VV, Calculate globals HERE ############ */ /* With Leap-Frog we can skip compute_globals at * non-communication steps, but we need to calculate * the kinetic energy one step before communication. */ { // Organize to do inter-simulation signalling on steps if // and when algorithms require it. const bool doInterSimSignal = (simulationsShareState && do_per_step(step, nstSignalComm)); if (useGpuForUpdate) { const bool coordinatesRequiredForStopCM = bStopCM && (bGStat || needHalfStepKineticEnergy || doInterSimSignal) && !EI_VV(ir->eI); // Copy coordinates when needed to stop the CM motion or for replica exchange if (coordinatesRequiredForStopCM || bDoReplEx) { stateGpu->copyCoordinatesFromGpu(state->x, AtomLocality::Local); stateGpu->waitCoordinatesReadyOnHost(AtomLocality::Local); } // Copy velocities back to the host if: // - Globals are computed this step (includes the energy output steps). // - Temperature is needed for the next step. // - This is a replica exchange step (even though we will only need // the velocities if an exchange succeeds) if (bGStat || needHalfStepKineticEnergy || bDoReplEx) { stateGpu->copyVelocitiesFromGpu(state->v, AtomLocality::Local); stateGpu->waitVelocitiesReadyOnHost(AtomLocality::Local); } } if (bGStat || needHalfStepKineticEnergy || doInterSimSignal) { // Since we're already communicating at this step, we // can propagate intra-simulation signals. Note that // check_nstglobalcomm has the responsibility for // choosing the value of nstglobalcomm that is one way // bGStat becomes true, so we can't get into a // situation where e.g. checkpointing can't be // signalled. bool doIntraSimSignal = true; SimulationSignaller signaller(&signals, cr, ms, doInterSimSignal, doIntraSimSignal); compute_globals(gstat, cr, ir, fr, ekind, makeConstArrayRef(state->x), makeConstArrayRef(state->v), state->box, md, nrnb, &vcm, wcycle, enerd, force_vir, shake_vir, total_vir, pres, &signaller, lastbox, &bSumEkinhOld, (bGStat ? CGLO_GSTAT : 0) | (!EI_VV(ir->eI) && bCalcEner ? CGLO_ENERGY : 0) | (!EI_VV(ir->eI) && bStopCM ? CGLO_STOPCM : 0) | (!EI_VV(ir->eI) ? CGLO_TEMPERATURE : 0) | (!EI_VV(ir->eI) ? CGLO_PRESSURE : 0) | CGLO_CONSTRAINT, step, &observablesReducer); if (!EI_VV(ir->eI) && bStopCM) { process_and_stopcm_grp( fplog, &vcm, *md, makeArrayRef(state->x), makeArrayRef(state->v)); inc_nrnb(nrnb, eNR_STOPCM, md->homenr); // TODO: The special case of removing CM motion should be dealt more gracefully if (useGpuForUpdate) { stateGpu->copyCoordinatesToGpu(state->x, AtomLocality::Local); // Here we block until the H2D copy completes because event sync with the // force kernels that use the coordinates on the next steps is not implemented // (not because of a race on state->x being modified on the CPU while H2D is in progress). stateGpu->waitCoordinatesCopiedToDevice(AtomLocality::Local); // If the COM removal changed the velocities on the CPU, this has to be accounted for. if (vcm.mode != ComRemovalAlgorithm::No) { stateGpu->copyVelocitiesToGpu(state->v, AtomLocality::Local); } } } } } /* ############# END CALC EKIN AND PRESSURE ################# */ /* Note: this is OK, but there are some numerical precision issues with using the convergence of the virial that should probably be addressed eventually. state->veta has better properies, but what we actually need entering the new cycle is the new shake_vir value. Ideally, we could generate the new shake_vir, but test the veta value for convergence. This will take some thought. */ if (ir->efep != FreeEnergyPerturbationType::No && !EI_VV(ir->eI)) { /* Sum up the foreign energy and dK/dl terms for md and sd. Currently done every step so that dH/dl is correct in the .edr */ accumulateKineticLambdaComponents(enerd, state->lambda, *ir->fepvals); } bool scaleCoordinates = !useGpuForUpdate || bDoReplEx; update_pcouple_after_coordinates(fplog, step, ir, md->homenr, md->cFREEZE ? gmx::arrayRefFromArray(md->cFREEZE, md->nr) : gmx::ArrayRef<const unsigned short>(), pres, force_vir, shake_vir, pressureCouplingMu, state, nrnb, upd.deform(), scaleCoordinates); const bool doBerendsenPressureCoupling = (inputrec->epc == PressureCoupling::Berendsen && do_per_step(step, inputrec->nstpcouple)); const bool doCRescalePressureCoupling = (inputrec->epc == PressureCoupling::CRescale && do_per_step(step, inputrec->nstpcouple)); if (useGpuForUpdate && (doBerendsenPressureCoupling || doCRescalePressureCoupling || doParrinelloRahman)) { integrator->scaleCoordinates(pressureCouplingMu); if (doCRescalePressureCoupling) { matrix pressureCouplingInvMu; gmx::invertBoxMatrix(pressureCouplingMu, pressureCouplingInvMu); integrator->scaleVelocities(pressureCouplingInvMu); } integrator->setPbc(PbcType::Xyz, state->box); } /* ################# END UPDATE STEP 2 ################# */ /* #### We now have r(t+dt) and v(t+dt/2) ############# */ /* The coordinates (x) were unshifted in update */ if (!bGStat) { /* We will not sum ekinh_old, * so signal that we still have to do it. */ bSumEkinhOld = TRUE; } if (bCalcEner) { /* ######### BEGIN PREPARING EDR OUTPUT ########### */ /* use the directly determined last velocity, not actually the averaged half steps */ if (bTrotter && ir->eI == IntegrationAlgorithm::VV) { enerd->term[F_EKIN] = last_ekin; } enerd->term[F_ETOT] = enerd->term[F_EPOT] + enerd->term[F_EKIN]; if (integratorHasConservedEnergyQuantity(ir)) { if (EI_VV(ir->eI)) { enerd->term[F_ECONSERVED] = enerd->term[F_ETOT] + saved_conserved_quantity; } else { enerd->term[F_ECONSERVED] = enerd->term[F_ETOT] + NPT_energy(ir, state, &MassQ); } } /* ######### END PREPARING EDR OUTPUT ########### */ } /* Output stuff */ if (MASTER(cr)) { if (fplog && do_log && bDoExpanded) { /* only needed if doing expanded ensemble */ PrintFreeEnergyInfoToFile(fplog, ir->fepvals.get(), ir->expandedvals.get(), ir->bSimTemp ? ir->simtempvals.get() : nullptr, state_global->dfhist, state->fep_state, ir->nstlog, step); } if (bCalcEner) { const bool outputDHDL = (computeDHDL && do_per_step(step, ir->fepvals->nstdhdl)); energyOutput.addDataAtEnergyStep(outputDHDL, bCalcEnerStep, t, md->tmass, enerd, ir->fepvals.get(), ir->expandedvals.get(), lastbox, PTCouplingArrays{ state->boxv, state->nosehoover_xi, state->nosehoover_vxi, state->nhpres_xi, state->nhpres_vxi }, state->fep_state, total_vir, pres, ekind, mu_tot, constr); } else { energyOutput.recordNonEnergyStep(); } gmx_bool do_dr = do_per_step(step, ir->nstdisreout); gmx_bool do_or = do_per_step(step, ir->nstorireout); if (doSimulatedAnnealing) { gmx::EnergyOutput::printAnnealingTemperatures( do_log ? fplog : nullptr, groups, &(ir->opts)); } if (do_log || do_ene || do_dr || do_or) { energyOutput.printStepToEnergyFile(mdoutf_get_fp_ene(outf), do_ene, do_dr, do_or, do_log ? fplog : nullptr, step, t, fr->fcdata.get(), awh.get()); } if (do_log && ir->bDoAwh && awh->hasFepLambdaDimension()) { const bool isInitialOutput = false; printLambdaStateToLog(fplog, state->lambda, isInitialOutput); } if (ir->bPull) { pull_print_output(pull_work, step, t); } if (do_per_step(step, ir->nstlog)) { if (fflush(fplog) != 0) { gmx_fatal(FARGS, "Cannot flush logfile - maybe you are out of disk space?"); } } } if (bDoExpanded) { /* Have to do this part _after_ outputting the logfile and the edr file */ /* Gets written into the state at the beginning of next loop*/ state->fep_state = lamnew; } else if (ir->bDoAwh && awh->needForeignEnergyDifferences(step)) { state->fep_state = awh->fepLambdaState(); } /* Print the remaining wall clock time for the run */ if (isMasterSimMasterRank(ms, MASTER(cr)) && (do_verbose || gmx_got_usr_signal()) && !bPMETunePrinting) { if (shellfc) { fprintf(stderr, "\n"); } print_time(stderr, walltime_accounting, step, ir, cr); } /* Ion/water position swapping. * Not done in last step since trajectory writing happens before this call * in the MD loop and exchanges would be lost anyway. */ bNeedRepartition = FALSE; if ((ir->eSwapCoords != SwapType::No) && (step > 0) && !bLastStep && do_per_step(step, ir->swap->nstswap)) { bNeedRepartition = do_swapcoords(cr, step, t, ir, swap, wcycle, as_rvec_array(state->x.data()), state->box, MASTER(cr) && mdrunOptions.verbose, bRerunMD); if (bNeedRepartition && haveDDAtomOrdering(*cr)) { dd_collect_state(cr->dd, state, state_global); } } /* Replica exchange */ bExchanged = FALSE; if (bDoReplEx) { bExchanged = replica_exchange(fplog, cr, ms, repl_ex, state_global, enerd, state, step, t); } if ((bExchanged || bNeedRepartition) && haveDDAtomOrdering(*cr)) { dd_partition_system(fplog, mdlog, step, cr, TRUE, 1, state_global, top_global, *ir, imdSession, pull_work, state, &f, mdAtoms, top, fr, vsite, constr, nrnb, wcycle, FALSE); upd.updateAfterPartition(state->natoms, md->cFREEZE ? gmx::arrayRefFromArray(md->cFREEZE, md->nr) : gmx::ArrayRef<const unsigned short>(), md->cTC ? gmx::arrayRefFromArray(md->cTC, md->nr) : gmx::ArrayRef<const unsigned short>()); fr->longRangeNonbondeds->updateAfterPartition(*md); } bFirstStep = FALSE; bInitStep = FALSE; /* ####### SET VARIABLES FOR NEXT ITERATION IF THEY STILL NEED IT ###### */ /* With all integrators, except VV, we need to retain the pressure * at the current step for coupling at the next step. */ if ((state->flags & enumValueToBitMask(StateEntry::PressurePrevious)) && (bGStatEveryStep || (ir->nstpcouple > 0 && step % ir->nstpcouple == 0))) { /* Store the pressure in t_state for pressure coupling * at the next MD step. */ copy_mat(pres, state->pres_prev); } /* ####### END SET VARIABLES FOR NEXT ITERATION ###### */ if ((membed != nullptr) && (!bLastStep)) { rescale_membed(step_rel, membed, as_rvec_array(state_global->x.data())); } cycles = wallcycle_stop(wcycle, WallCycleCounter::Step); if (haveDDAtomOrdering(*cr) && wcycle) { dd_cycles_add(cr->dd, cycles, ddCyclStep); } /* increase the MD step number */ step++; step_rel++; observablesReducer.markAsReadyToReduce(); #if GMX_FAHCORE if (MASTER(cr)) { fcReportProgress(ir->nsteps + ir->init_step, step); } #endif resetHandler->resetCounters( step, step_rel, mdlog, fplog, cr, fr->nbv.get(), nrnb, fr->pmedata, pme_loadbal, wcycle, walltime_accounting); /* If bIMD is TRUE, the master updates the IMD energy record and sends positions to VMD client */ imdSession->updateEnergyRecordAndSendPositionsAndEnergies(bInteractiveMDstep, step, bCalcEner); } /* End of main MD loop */ /* Closing TNG files can include compressing data. Therefore it is good to do that * before stopping the time measurements. */ mdoutf_tng_close(outf); /* Stop measuring walltime */ walltime_accounting_end_time(walltime_accounting); if (simulationWork.haveSeparatePmeRank) { /* Tell the PME only node to finish */ gmx_pme_send_finish(cr); } if (MASTER(cr)) { if (ir->nstcalcenergy > 0) { energyOutput.printEnergyConservation(fplog, ir->simulation_part, EI_MD(ir->eI)); gmx::EnergyOutput::printAnnealingTemperatures(fplog, groups, &(ir->opts)); energyOutput.printAverages(fplog, groups); } } done_mdoutf(outf); if (bPMETune) { pme_loadbal_done(pme_loadbal, fplog, mdlog, fr->nbv->useGpu()); } done_shellfc(fplog, shellfc, step_rel); if (useReplicaExchange && MASTER(cr)) { print_replica_exchange_statistics(fplog, repl_ex); } walltime_accounting_set_nsteps_done(walltime_accounting, step_rel); global_stat_destroy(gstat); } <|start_filename|>api/nblib/integrator.cpp<|end_filename|> /* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2020, by the GROMACS development team, led by * <NAME>, <NAME>, <NAME>, and <NAME>, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS 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. * * GROMACS 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 GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ /*! \internal \file * \brief * Implements nblib integrator * * \author <NAME> <<EMAIL>> * \author <NAME> <<EMAIL>> * \author <NAME> <<EMAIL>> * \author <NAME> <<EMAIL>> * \author <NAME> <<EMAIL>> */ #include "nblib/integrator.h" #include "gromacs/pbcutil/pbc.h" #include "gromacs/utility/arrayref.h" #include "nblib/topology.h" namespace nblib { LeapFrog::LeapFrog(const Topology& topology, const Box& box) : box_(box) { inverseMasses_.resize(topology.numParticles()); for (int i = 0; i < topology.numParticles(); i++) { int typeIndex = topology.getParticleTypeIdOfAllParticles()[i]; inverseMasses_[i] = 1.0 / topology.getParticleTypes()[typeIndex].mass(); } } void LeapFrog::integrate(const real dt, gmx::ArrayRef<Vec3> x, gmx::ArrayRef<Vec3> v, gmx::ArrayRef<const Vec3> f) { for (size_t i = 0; i < x.size(); i++) { for (int dim = 0; dim < dimSize; dim++) { v[i][dim] += f[i][dim] * dt * inverseMasses_[i]; x[i][dim] += v[i][dim] * dt; } } put_atoms_in_box(PbcType::Xyz, box_.legacyMatrix(), x); } } // namespace nblib <|start_filename|>api/nblib/listed_forces/dataflow.hpp<|end_filename|> /* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2019, by the GROMACS development team, led by * <NAME>, <NAME>, <NAME>, and <NAME>, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS 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. * * GROMACS 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 GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ /*! \internal \file * \brief * Implements the data flow from ListedInteractionData and coordinates * down to the individual interaction type kernels * * Intended for internal use inside ListedCalculator only. * * \author <NAME> <<EMAIL>> * \author <NAME> <<EMAIL>> * \author <NAME> <<EMAIL>> * \author <NAME> <<EMAIL>> * \author <NAME> <<EMAIL>> */ #ifndef NBLIB_LISTEDFORCES_DATAFLOW_HPP #define NBLIB_LISTEDFORCES_DATAFLOW_HPP #include <tuple> #include <vector> #include "nblib/listed_forces/traits.h" #include "nblib/listed_forces/kernels.hpp" #include "nblib/util/util.hpp" #include "nblib/pbc.hpp" #include "nblib/vector.h" #include "gromacs/utility/arrayref.h" #define NBLIB_ALWAYS_INLINE __attribute((always_inline)) namespace nblib { //! \brief returns the address of an element in the shiftForces buffer template<class ShiftForce> inline ShiftForce* accessShiftForces(int shiftIndex, gmx::ArrayRef<ShiftForce> shiftForces) { return shiftForces.data() + shiftIndex; } //! \brief dummy op in case shift forces are not computed (will be removed by the compiler) inline std::nullptr_t accessShiftForces([[maybe_unused]] int shiftIndex, [[maybe_unused]] gmx::ArrayRef<std::nullptr_t> shiftForces) { return nullptr; } template<class TwoCenterType, class BasicVector, class ShiftForce> inline NBLIB_ALWAYS_INLINE auto computeTwoCenter(const TwoCenterType& parameters, const BasicVector& dx, BasicVector* fi, BasicVector* fj, ShiftForce* sh_f, ShiftForce* sh_fc) { using ValueType = BasicVectorValueType_t<BasicVector>; ValueType dr2 = dot(dx, dx); ValueType dr = std::sqrt(dr2); auto [force, energy] = bondKernel(dr, parameters); // avoid division by 0 if (dr2 != 0.0) { force /= dr; spreadTwoCenterForces(force, dx, fi, fj, sh_f, sh_fc); } return energy; } /*! \brief calculate two-center interactions * * \tparam Force buffer type * \tparam TwoCenterType The bond type to compute; used for type deduction * \tparam Cartesian vector type * \tparam PBC type * \param[in] index The atom and parameter indices used for computing the interaction * \param[in] bondInstances The full type-specific interaction list * \param[in] x The coordinates * \param[in/out] forces The forces * \param[in] pbc Object used for computing distances accounting for PBC's * \return Computed kernel energies */ template <class Buffer, class TwoCenterType, class BasicVector, class ShiftForce, class Pbc, std::enable_if_t<Contains<TwoCenterType, SupportedTwoCenterTypes>{}>* = nullptr> inline NBLIB_ALWAYS_INLINE auto dispatchInteraction(InteractionIndex<TwoCenterType> index, gmx::ArrayRef<const TwoCenterType> bondInstances, gmx::ArrayRef<const BasicVector> x, Buffer* forces, gmx::ArrayRef<ShiftForce> shiftForces, const Pbc& pbc) { KernelEnergy<BasicVectorValueType_t<BasicVector>> energy; int i = std::get<0>(index); int j = std::get<1>(index); BasicVector xi = x[i]; BasicVector xj = x[j]; TwoCenterType bond = bondInstances[std::get<2>(index)]; BasicVector dx; // calculate xi - xj modulo pbc int sIdx = pbc.dxAiuc(xi, xj, dx); ShiftForce* sh_f = accessShiftForces(sIdx, shiftForces); ShiftForce* sh_fc = accessShiftForces(gmx::c_centralShiftIndex, shiftForces); energy.carrier() = computeTwoCenter(bond, dx, &(*forces)[i], &(*forces)[j], sh_f, sh_fc); return energy; } template<class ThreeCenterType, class BasicVector, class ShiftForce> inline NBLIB_ALWAYS_INLINE std::enable_if_t<HasTwoCenterAggregate<ThreeCenterType>::value, BasicVectorValueType_t<BasicVector>> addTwoCenterAggregate(const ThreeCenterType& parameters, const BasicVector& rij, const BasicVector& rkj, BasicVector* fi, BasicVector* fj, BasicVector* fk, ShiftForce* shf_ij, ShiftForce* shf_kj, ShiftForce* shf_c) { if (parameters.manifest == ThreeCenterType::Cargo::ij) { // i-j bond return computeTwoCenter(parameters.twoCenter(), rij, fi, fj, shf_ij, shf_c); } if (parameters.manifest == ThreeCenterType::Cargo::jk) { // j-k bond return computeTwoCenter(parameters.twoCenter(), rkj, fk, fj, shf_kj, shf_c); } // aggregate is empty return 0.0; }; template<class ThreeCenterType, class BasicVector, class ShiftForce> inline NBLIB_ALWAYS_INLINE std::enable_if_t<!HasTwoCenterAggregate<ThreeCenterType>::value, BasicVectorValueType_t<BasicVector>> addTwoCenterAggregate([[maybe_unused]] const ThreeCenterType& parameters, [[maybe_unused]] const BasicVector& rij, [[maybe_unused]] const BasicVector& rkj, [[maybe_unused]] BasicVector* fi, [[maybe_unused]] BasicVector* fj, [[maybe_unused]] BasicVector* fk, [[maybe_unused]] ShiftForce* shf_ij, [[maybe_unused]] ShiftForce* shf_kj, [[maybe_unused]] ShiftForce* shf_c) { return 0.0; }; template<class ThreeCenterType, class BasicVector, class ShiftForce> inline NBLIB_ALWAYS_INLINE auto computeThreeCenter(const ThreeCenterType& parameters, const BasicVector& rij, const BasicVector& rkj, const BasicVector& /* rik */, BasicVector* fi, BasicVector* fj, BasicVector* fk, ShiftForce* shf_ij, ShiftForce* shf_kj, ShiftForce* shf_c) { using ValueType = BasicVectorValueType_t<BasicVector>; // calculate 3-center common quantities: angle between x1-x2 and x2-x3 // Todo: after sufficient evaluation, switch over to atan2 based algorithm ValueType costh = basicVectorCosAngle(rij, rkj); /* 25 */ ValueType theta = std::acos(costh); /* 10 */ // call type-specific angle kernel, e.g. harmonic, restricted, quartic, etc. auto [force, energy] = threeCenterKernel(theta, parameters); spreadThreeCenterForces(costh, force, rij, rkj, fi, fj, fk, shf_ij, shf_kj, shf_c); return energy; } template<class BasicVector, class ShiftForce> inline NBLIB_ALWAYS_INLINE auto computeThreeCenter(const LinearAngle& parameters, const BasicVector& rij, const BasicVector& rkj, const BasicVector& /* rik */, BasicVector* fi, BasicVector* fj, BasicVector* fk, ShiftForce* shf_ij, ShiftForce* shf_kj, ShiftForce* shf_c) { using ValueType = BasicVectorValueType_t<BasicVector>; ValueType b = parameters.equilConstant() - 1; auto dr_vec = b * rkj - parameters.equilConstant() * rij; ValueType dr = norm(dr_vec); auto [ci, ck, energy] = threeCenterKernel(dr, parameters); BasicVector fi_loc = ci * dr_vec; BasicVector fk_loc = ck * dr_vec; BasicVector fj_loc = ValueType(-1.0) * (fi_loc + fk_loc); *fi += fi_loc; *fj += fj_loc; *fk += fk_loc; addShiftForce(fi_loc, shf_ij); addShiftForce(fj_loc, shf_c); addShiftForce(fk_loc, shf_kj); return energy; } template<class BasicVector, class ShiftForce> inline NBLIB_ALWAYS_INLINE auto computeThreeCenter(const CrossBondBond& parameters, const BasicVector& rij, const BasicVector& rkj, const BasicVector& /* rik */, BasicVector* fi, BasicVector* fj, BasicVector* fk, ShiftForce* shf_ij, ShiftForce* shf_kj, ShiftForce* shf_c) { using ValueType = BasicVectorValueType_t<BasicVector>; // 28 flops from the norm() calls auto [ci, ck, energy] = threeCenterKernel(norm(rij), norm(rkj), parameters); BasicVector fi_loc = ci * rij; BasicVector fk_loc = ck * rkj; BasicVector fj_loc = ValueType(-1.0) * (fi_loc + fk_loc); *fi += fi_loc; *fj += fj_loc; *fk += fk_loc; addShiftForce(fi_loc, shf_ij); addShiftForce(fj_loc, shf_c); addShiftForce(fk_loc, shf_kj); return energy; } template<class BasicVector, class ShiftForce> inline NBLIB_ALWAYS_INLINE auto computeThreeCenter(const CrossBondAngle& parameters, const BasicVector& rij, const BasicVector& rkj, const BasicVector& rik, BasicVector* fi, BasicVector* fj, BasicVector* fk, ShiftForce* shf_ij, ShiftForce* shf_kj, ShiftForce* shf_c) { using ValueType = BasicVectorValueType_t<BasicVector>; // 42 flops from the norm() calls auto [ci, cj, ck, energy] = crossBondAngleKernel(norm(rij), norm(rkj), norm(rik), parameters); BasicVector fi_loc = ci * rij + ck * rik; BasicVector fk_loc = cj * rkj - ck * rik; BasicVector fj_loc = ValueType(-1.0) * (fi_loc + fk_loc); *fi += fi_loc; *fj += fj_loc; *fk += fk_loc; addShiftForce(fi_loc, shf_ij); addShiftForce(fj_loc, shf_c); addShiftForce(fk_loc, shf_kj); return energy; } /*! \brief Calculate three-center interactions * * \tparam Force buffer type * \tparam Three centre interaction parameters * \tparam Cartesian vector type * \tparam PBC type * \param[in] index * \param[in] Bond parameters * \param[in] x coordinate array * \param[in/out] Force buffer * \param[in] PBC * \return Computed kernel energies */ template <class Buffer, class ThreeCenterType, class BasicVector, class ShiftForce, class Pbc, std::enable_if_t<Contains<ThreeCenterType, SupportedThreeCenterTypes>{}>* = nullptr> inline NBLIB_ALWAYS_INLINE auto dispatchInteraction(InteractionIndex<ThreeCenterType> index, gmx::ArrayRef<const ThreeCenterType> parameters, gmx::ArrayRef<const BasicVector> x, Buffer* forces, gmx::ArrayRef<ShiftForce> shiftForces, const Pbc& pbc) { KernelEnergy<BasicVectorValueType_t<BasicVector>> energy; //! fetch input data: position vectors x1-x3 and interaction parameters int i = std::get<0>(index); int j = std::get<1>(index); int k = std::get<2>(index); BasicVector xi = x[i]; BasicVector xj = x[j]; BasicVector xk = x[k]; ThreeCenterType threeCenterParameters = parameters[std::get<3>(index)]; BasicVector fi{0,0,0}, fj{0,0,0}, fk{0,0,0}; BasicVector rij, rkj, rik; int sIdx_ij = pbc.dxAiuc(xi, xj, rij); /* 3 */ int sIdx_kj = pbc.dxAiuc(xk, xj, rkj); /* 3 */ pbc.dxAiuc(xi, xk, rik); /* 3 */ ShiftForce* shf_ij = accessShiftForces(sIdx_ij, shiftForces); ShiftForce* shf_kj = accessShiftForces(sIdx_kj, shiftForces); ShiftForce* shf_c = accessShiftForces(gmx::c_centralShiftIndex, shiftForces); energy.carrier() = computeThreeCenter(threeCenterParameters, rij, rkj, rik, &fi, &fj, &fk, shf_ij, shf_kj, shf_c); energy.twoCenterAggregate() = addTwoCenterAggregate(threeCenterParameters, rij, rkj, &fi, &fj, &fk, shf_ij, shf_kj, shf_c); (*forces)[i] += fi; (*forces)[j] += fj; (*forces)[k] += fk; return energy; } template<class FourCenterType, class BasicVector> inline NBLIB_ALWAYS_INLINE std::enable_if_t<HasThreeCenterAggregate<FourCenterType>::value, BasicVectorValueType_t<BasicVector>> addThreeCenterAggregate(const FourCenterType& parameters, const BasicVector& rij, const BasicVector& rkj, const BasicVector& rkl, BasicVector* fi, BasicVector* fj, BasicVector* fk, BasicVector* fl) { using ValueType = BasicVectorValueType_t<BasicVector>; if (parameters.manifest == FourCenterType::Cargo::j) { return computeThreeCenter(parameters.threeCenter(), rij, rkj, fi, fj, fk); } if (parameters.manifest == FourCenterType::Cargo::k) { return computeThreeCenter(parameters.threeCenter(), ValueType(-1.0)*rkj, ValueType(-1.0)*rkl, fj, fk, fl); //return computeThreeCenter(parameters.threeCenter(), rkj, rkl, fj, fk, fl); } // aggregate is empty return 0.0; }; template<class FourCenterType, class BasicVector> inline NBLIB_ALWAYS_INLINE std::enable_if_t<!HasThreeCenterAggregate<FourCenterType>::value, BasicVectorValueType_t<BasicVector>> addThreeCenterAggregate([[maybe_unused]] const FourCenterType& parameters, [[maybe_unused]] const BasicVector& rij, [[maybe_unused]] const BasicVector& rkj, [[maybe_unused]] const BasicVector& rkl, [[maybe_unused]] BasicVector* fi, [[maybe_unused]] BasicVector* fj, [[maybe_unused]] BasicVector* fk, [[maybe_unused]] BasicVector* fl) { return 0.0; }; /*! \brief Calculate four-center interactions * * \tparam Force buffer type * \tparam FourCenterType The bond type to compute; used for type deduction * \tparam Cartesian vector type * \tparam PBC type * \param[in] index The atom and parameter indices used for computing the interaction * \param[in] parameters The full type-specific interaction list * \param[in] x The coordinates * \param[in/out] forces The forces * \param[in] pbc Object used for computing distances accounting for PBC's * \return Computed kernel energies */ template <class Buffer, class FourCenterType, class BasicVector, class ShiftForce, class Pbc, std::enable_if_t<Contains<FourCenterType, SupportedFourCenterTypes>{}>* = nullptr> inline NBLIB_ALWAYS_INLINE auto dispatchInteraction(InteractionIndex<FourCenterType> index, gmx::ArrayRef<const FourCenterType> parameters, gmx::ArrayRef<const BasicVector> x, Buffer* forces, gmx::ArrayRef<ShiftForce> shiftForces, const Pbc& pbc) { using RealScalar = BasicVectorValueType_t<BasicVector>; KernelEnergy<RealScalar> energy; int i = std::get<0>(index); int j = std::get<1>(index); int k = std::get<2>(index); int l = std::get<3>(index); BasicVector xi = x[i]; BasicVector xj = x[j]; BasicVector xk = x[k]; BasicVector xl = x[l]; BasicVector fi{0,0,0}, fj{0,0,0}, fk{0,0,0}, fl{0,0,0}; BasicVector dxIJ, dxKJ, dxKL, dxLJ; int sIdx_ij = pbc.dxAiuc(xi, xj, dxIJ); int sIdx_kj = pbc.dxAiuc(xk, xj, dxKJ); pbc.dxAiuc(xk, xl, dxKL); int sIdx_lj = pbc.dxAiuc(xl, xj, dxLJ); ShiftForce* shf_ij = accessShiftForces(sIdx_ij, shiftForces); ShiftForce* shf_kj = accessShiftForces(sIdx_kj, shiftForces); ShiftForce* shf_lj = accessShiftForces(sIdx_lj, shiftForces); ShiftForce* shf_c = accessShiftForces(gmx::c_centralShiftIndex, shiftForces); FourCenterType fourCenterTypeParams = parameters[std::get<4>(index)]; BasicVector m, n; RealScalar phi = dihedralPhi(dxIJ, dxKJ, dxKL, &m, &n); auto [force, kernelEnergy] = fourCenterKernel(phi, fourCenterTypeParams); energy.carrier() = kernelEnergy; energy.threeCenterAggregate() = addThreeCenterAggregate(fourCenterTypeParams, dxIJ, dxKJ, dxKL, &fi, &fj, &fk, &fl); spreadFourCenterForces(force, dxIJ, dxKJ, dxKL, m, n, &fi, &fj, &fk, &fl, shf_ij, shf_kj, shf_lj, shf_c); (*forces)[i] += fi; (*forces)[j] += fj; (*forces)[k] += fk; (*forces)[l] += fl; return energy; } /*! \brief Calculate five-center interactions * * \tparam Force buffer type * \tparam FiveCenterType The bond type to compute; used for type deduction * \tparam Cartesian vector type * \tparam PBC type * \param[in] index The atom and parameter indices used for computing the interaction * \param[in] parameters The full type-specific interaction list * \param[in] x The coordinates * \param[in/out] forces The forces * \param[in] pbc Object used for computing distances accounting for PBC's * \return Computed kernel energies */ template <class Buffer, class FiveCenterType, class BasicVector, class ShiftForce, class Pbc, std::enable_if_t<Contains<FiveCenterType, SupportedFiveCenterTypes>{}>* = nullptr> inline NBLIB_ALWAYS_INLINE auto dispatchInteraction(InteractionIndex<FiveCenterType> index, gmx::ArrayRef<const FiveCenterType> parameters, gmx::ArrayRef<const BasicVector> x, Buffer* forces, [[maybe_unused]] gmx::ArrayRef<ShiftForce> shiftForces, const Pbc& pbc) { KernelEnergy<BasicVectorValueType_t<BasicVector>> energy; int i = std::get<0>(index); int j = std::get<1>(index); int k = std::get<2>(index); int l = std::get<3>(index); int m = std::get<4>(index); BasicVector xi = x[i]; BasicVector xj = x[j]; BasicVector xk = x[k]; BasicVector xl = x[l]; BasicVector xm = x[m]; BasicVector dxIJ, dxJK, dxKL, dxLM; pbc.dxAiuc(xi, xj, dxIJ); pbc.dxAiuc(xj, xk, dxJK); pbc.dxAiuc(xk, xl, dxKL); pbc.dxAiuc(xl, xm, dxLM); FiveCenterType fiveCenterTypeParams = parameters[std::get<5>(index)]; // this dispatch function is not in use yet, because CMap is not yet implemented // we don't want to add [[maybe_unused]] in the signature // and we also don't want compiler warnings, so we cast to void (void)fiveCenterTypeParams; (void)forces; return energy; } /*! \brief implement a loop over bonds for a given BondType and Kernel * corresponds to e.g. the "bonds" function at Gromacs:bonded.cpp@450 * * \param[in] indices interaction atom pair indices + bond parameter index * \param[in] interactionParameters bond/interaction parameters * \param[in] x coordinate input * \param[in/out] forces The forces * \param[in] pbc Object used for computing distances accounting for PBC's * \return Computed kernel energies */ template <class Index, class InteractionType, class Buffer, class ShiftForce, class Pbc> auto computeForces(gmx::ArrayRef<const Index> indices, gmx::ArrayRef<const InteractionType> parameters, gmx::ArrayRef<const Vec3> x, Buffer* forces, gmx::ArrayRef<ShiftForce> shiftForces, const Pbc& pbc) { KernelEnergy<BasicVectorValueType_t<Vec3>> energy; for (const auto& index : indices) { energy += dispatchInteraction(index, parameters, x, forces, shiftForces, pbc); } return energy; } //! \brief convenience overload without shift forces template <class Index, class InteractionType, class Buffer, class Pbc> auto computeForces(gmx::ArrayRef<const Index> indices, gmx::ArrayRef<const InteractionType> parameters, gmx::ArrayRef<const Vec3> x, Buffer* forces, const Pbc& pbc) { return computeForces(indices, parameters, x, forces, gmx::ArrayRef<std::nullptr_t>{}, pbc); } /*! \brief implement a loop over bond types and accumulate their force contributions * * \param[in] interactions interaction pairs and bond parameters * \param[in] x coordinate input * \param[in/out] forces output force buffer * \param[in] pbc Object used for computing distances accounting for PBC's * \return Computed kernel energies */ template<class Buffer, class ShiftForce, class Pbc> auto reduceListedForces(const ListedInteractionData& interactions, gmx::ArrayRef<const Vec3> x, Buffer* forces, gmx::ArrayRef<ShiftForce> shiftForces, const Pbc& pbc) { using ValueType = BasicVectorValueType_t<Vec3>; std::array<ValueType, std::tuple_size<ListedInteractionData>::value> energies{0}; energies.fill(0); // calculate one bond type auto computeForceType = [forces, x, shiftForces, &energies, &pbc](const auto& interactionElement) { using InteractionType = typename std::decay_t<decltype(interactionElement)>::type; gmx::ArrayRef<const InteractionIndex<InteractionType>> indices(interactionElement.indices); gmx::ArrayRef<const InteractionType> parameters(interactionElement.parameters); KernelEnergy<ValueType> energy = computeForces(indices, parameters, x, forces, shiftForces, pbc); energies[CarrierIndex<InteractionType>{}] += energy.carrier(); energies[TwoCenterAggregateIndex<InteractionType>{}] += energy.twoCenterAggregate(); energies[ThreeCenterAggregateIndex<InteractionType>{}] += energy.threeCenterAggregate(); // energies[FepIndex{}] += energy.freeEnergyDerivative(); }; // calculate all bond types, returns a tuple with the energies for each type for_each_tuple(computeForceType, interactions); return energies; } //! \brief convenience overload without shift forces template<class Buffer, class Pbc> auto reduceListedForces(const ListedInteractionData& interactions, gmx::ArrayRef<const Vec3> x, Buffer* forces, const Pbc& pbc) { return reduceListedForces(interactions, x, forces, gmx::ArrayRef<std::nullptr_t>{}, pbc); } } // namespace nblib #undef NBLIB_ALWAYS_INLINE #endif // NBLIB_LISTEDFORCES_DATAFLOW_HPP <|start_filename|>src/gromacs/applied_forces/awh/biasstate.cpp<|end_filename|> /* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2015,2016,2017,2018,2019, The GROMACS development team. * Copyright (c) 2020,2021, by the GROMACS development team, led by * <NAME>, <NAME>, <NAME>, and <NAME>, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS 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. * * GROMACS 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 GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ /*! \internal \file * \brief * Implements the BiasState class. * * \author <NAME> * \author <NAME> <<EMAIL>> * \ingroup module_awh */ #include "gmxpre.h" #include "biasstate.h" #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <algorithm> #include <optional> #include "gromacs/fileio/gmxfio.h" #include "gromacs/fileio/xvgr.h" #include "gromacs/gmxlib/network.h" #include "gromacs/math/units.h" #include "gromacs/math/utilities.h" #include "gromacs/mdrunutility/multisim.h" #include "gromacs/mdtypes/awh_history.h" #include "gromacs/mdtypes/awh_params.h" #include "gromacs/mdtypes/commrec.h" #include "gromacs/simd/simd.h" #include "gromacs/simd/simd_math.h" #include "gromacs/utility/arrayref.h" #include "gromacs/utility/exceptions.h" #include "gromacs/utility/gmxassert.h" #include "gromacs/utility/smalloc.h" #include "gromacs/utility/stringutil.h" #include "biasgrid.h" #include "biassharing.h" #include "pointstate.h" namespace gmx { void BiasState::getPmf(gmx::ArrayRef<float> pmf) const { GMX_ASSERT(pmf.size() == points_.size(), "pmf should have the size of the bias grid"); /* The PMF is just the negative of the log of the sampled PMF histogram. * Points with zero target weight are ignored, they will mostly contain noise. */ for (size_t i = 0; i < points_.size(); i++) { pmf[i] = points_[i].inTargetRegion() ? -points_[i].logPmfSum() : GMX_FLOAT_MAX; } } namespace { /*! \brief * Sum PMF over multiple simulations, when requested. * * \param[in,out] pointState The state of the points in the bias. * \param[in] numSharedUpdate The number of biases sharing the histogram. * \param[in] biasSharing Object for sharing bias data over multiple simulations * \param[in] biasIndex Index of this bias in the total list of biases in this simulation */ void sumPmf(gmx::ArrayRef<PointState> pointState, int numSharedUpdate, const BiasSharing* biasSharing, const int biasIndex) { if (numSharedUpdate == 1) { return; } GMX_ASSERT(biasSharing != nullptr && numSharedUpdate % biasSharing->numSharingSimulations(biasIndex) == 0, "numSharedUpdate should be a multiple of multiSimComm->numSimulations_"); GMX_ASSERT(numSharedUpdate == biasSharing->numSharingSimulations(biasIndex), "Sharing within a simulation is not implemented (yet)"); std::vector<double> buffer(pointState.size()); /* Need to temporarily exponentiate the log weights to sum over simulations */ for (size_t i = 0; i < buffer.size(); i++) { buffer[i] = pointState[i].inTargetRegion() ? std::exp(pointState[i].logPmfSum()) : 0; } biasSharing->sum(gmx::ArrayRef<double>(buffer), biasIndex); /* Take log again to get (non-normalized) PMF */ double normFac = 1.0 / numSharedUpdate; for (gmx::index i = 0; i < pointState.ssize(); i++) { if (pointState[i].inTargetRegion()) { pointState[i].setLogPmfSum(std::log(buffer[i] * normFac)); } } } /*! \brief * Find the minimum free energy value. * * \param[in] pointState The state of the points. * \returns the minimum free energy value. */ double freeEnergyMinimumValue(gmx::ArrayRef<const PointState> pointState) { double fMin = GMX_FLOAT_MAX; for (auto const& ps : pointState) { if (ps.inTargetRegion() && ps.freeEnergy() < fMin) { fMin = ps.freeEnergy(); } } return fMin; } /*! \brief * Find and return the log of the probability weight of a point given a coordinate value. * * The unnormalized weight is given by * w(point|value) = exp(bias(point) - U(value,point)), * where U is a harmonic umbrella potential. * * \param[in] dimParams The bias dimensions parameters * \param[in] points The point state. * \param[in] grid The grid. * \param[in] pointIndex Point to evaluate probability weight for. * \param[in] pointBias Bias for the point (as a log weight). * \param[in] value Coordinate value. * \param[in] neighborLambdaEnergies The energy of the system in neighboring lambdas states. Can be * empty when there are no free energy lambda state dimensions. * \param[in] gridpointIndex The index of the current grid point. * \returns the log of the biased probability weight. */ double biasedLogWeightFromPoint(ArrayRef<const DimParams> dimParams, ArrayRef<const PointState> points, const BiasGrid& grid, int pointIndex, double pointBias, const awh_dvec value, ArrayRef<const double> neighborLambdaEnergies, int gridpointIndex) { double logWeight = detail::c_largeNegativeExponent; /* Only points in the target region have non-zero weight */ if (points[pointIndex].inTargetRegion()) { logWeight = pointBias; /* Add potential for all parameter dimensions */ for (size_t d = 0; d < dimParams.size(); d++) { if (dimParams[d].isFepLambdaDimension()) { /* If this is not a sampling step or if this function is called from * calcConvolvedBias(), when writing energy subblocks, neighborLambdaEnergies will * be empty. No convolution is required along the lambda dimension. */ if (!neighborLambdaEnergies.empty()) { const int pointLambdaIndex = grid.point(pointIndex).coordValue[d]; const int gridpointLambdaIndex = grid.point(gridpointIndex).coordValue[d]; logWeight -= dimParams[d].fepDimParams().beta * (neighborLambdaEnergies[pointLambdaIndex] - neighborLambdaEnergies[gridpointLambdaIndex]); } } else { double dev = getDeviationFromPointAlongGridAxis(grid, d, pointIndex, value[d]); logWeight -= 0.5 * dimParams[d].pullDimParams().betak * dev * dev; } } } return logWeight; } /*! \brief * Calculates the marginal distribution (marginal probability) for each value along * a free energy lambda axis. * The marginal distribution of one coordinate dimension value is the sum of the probability * distribution of all values (herein all neighbor values) with the same value in the dimension * of interest. * \param[in] grid The bias grid. * \param[in] neighbors The points to use for the calculation of the marginal distribution. * \param[in] probWeightNeighbor Probability weights of the neighbors. * \returns The calculated marginal distribution in a 1D array with * as many elements as there are points along the axis of interest. */ std::vector<double> calculateFELambdaMarginalDistribution(const BiasGrid& grid, ArrayRef<const int> neighbors, ArrayRef<const double> probWeightNeighbor) { const std::optional<int> lambdaAxisIndex = grid.lambdaAxisIndex(); GMX_RELEASE_ASSERT(lambdaAxisIndex, "There must be a free energy lambda axis in order to calculate the free " "energy lambda marginal distribution."); const int numFepLambdaStates = grid.numFepLambdaStates(); std::vector<double> lambdaMarginalDistribution(numFepLambdaStates, 0); for (size_t i = 0; i < neighbors.size(); i++) { const int neighbor = neighbors[i]; const int lambdaState = grid.point(neighbor).coordValue[lambdaAxisIndex.value()]; lambdaMarginalDistribution[lambdaState] += probWeightNeighbor[i]; } return lambdaMarginalDistribution; } } // namespace void BiasState::calcConvolvedPmf(ArrayRef<const DimParams> dimParams, const BiasGrid& grid, std::vector<float>* convolvedPmf) const { size_t numPoints = grid.numPoints(); convolvedPmf->resize(numPoints); /* Get the PMF to convolve. */ std::vector<float> pmf(numPoints); getPmf(pmf); for (size_t m = 0; m < numPoints; m++) { double freeEnergyWeights = 0; const GridPoint& point = grid.point(m); for (const auto& neighbor : point.neighbor) { /* Do not convolve the bias along a lambda axis - only use the pmf from the current point */ if (!pointsHaveDifferentLambda(grid, m, neighbor)) { /* The negative PMF is a positive bias. */ double biasNeighbor = -pmf[neighbor]; /* Add the convolved PMF weights for the neighbors of this point. Note that this function only adds point within the target > 0 region. Sum weights, take the logarithm last to get the free energy. */ double logWeight = biasedLogWeightFromPoint( dimParams, points_, grid, neighbor, biasNeighbor, point.coordValue, {}, m); freeEnergyWeights += std::exp(logWeight); } } GMX_RELEASE_ASSERT(freeEnergyWeights > 0, "Attempting to do log(<= 0) in AWH convolved PMF calculation."); (*convolvedPmf)[m] = -std::log(static_cast<float>(freeEnergyWeights)); } } namespace { /*! \brief * Updates the target distribution for all points. * * The target distribution is always updated for all points * at the same time. * * \param[in,out] pointState The state of all points. * \param[in] params The bias parameters. */ void updateTargetDistribution(ArrayRef<PointState> pointState, const BiasParams& params) { double freeEnergyCutoff = 0; if (params.eTarget == AwhTargetType::Cutoff) { freeEnergyCutoff = freeEnergyMinimumValue(pointState) + params.freeEnergyCutoffInKT; } double sumTarget = 0; for (PointState& ps : pointState) { sumTarget += ps.updateTargetWeight(params, freeEnergyCutoff); } GMX_RELEASE_ASSERT(sumTarget > 0, "We should have a non-zero distribution"); /* Normalize to 1 */ double invSum = 1.0 / sumTarget; for (PointState& ps : pointState) { ps.scaleTarget(invSum); } } /*! \brief * Puts together a string describing a grid point. * * \param[in] grid The grid. * \param[in] point BiasGrid point index. * \returns a string for the point. */ std::string gridPointValueString(const BiasGrid& grid, int point) { std::string pointString; pointString += "("; for (int d = 0; d < grid.numDimensions(); d++) { pointString += gmx::formatString("%g", grid.point(point).coordValue[d]); if (d < grid.numDimensions() - 1) { pointString += ","; } else { pointString += ")"; } } return pointString; } } // namespace int BiasState::warnForHistogramAnomalies(const BiasGrid& grid, int biasIndex, double t, FILE* fplog, int maxNumWarnings) const { GMX_ASSERT(fplog != nullptr, "Warnings can only be issued if there is log file."); const double maxHistogramRatio = 0.5; /* Tolerance for printing a warning about the histogram ratios */ /* Sum up the histograms and get their normalization */ double sumVisits = 0; double sumWeights = 0; for (const auto& pointState : points_) { if (pointState.inTargetRegion()) { sumVisits += pointState.numVisitsTot(); sumWeights += pointState.weightSumTot(); } } GMX_RELEASE_ASSERT(sumVisits > 0, "We should have visits"); GMX_RELEASE_ASSERT(sumWeights > 0, "We should have weight"); double invNormVisits = 1.0 / sumVisits; double invNormWeight = 1.0 / sumWeights; /* Check all points for warnings */ int numWarnings = 0; size_t numPoints = grid.numPoints(); for (size_t m = 0; m < numPoints; m++) { /* Skip points close to boundary or non-target region */ const GridPoint& gridPoint = grid.point(m); bool skipPoint = false; for (size_t n = 0; (n < gridPoint.neighbor.size()) && !skipPoint; n++) { int neighbor = gridPoint.neighbor[n]; skipPoint = !points_[neighbor].inTargetRegion(); for (int d = 0; (d < grid.numDimensions()) && !skipPoint; d++) { const GridPoint& neighborPoint = grid.point(neighbor); skipPoint = neighborPoint.index[d] == 0 || neighborPoint.index[d] == grid.axis(d).numPoints() - 1; } } /* Warn if the coordinate distribution is less than the target distribution with a certain fraction somewhere */ const double relativeWeight = points_[m].weightSumTot() * invNormWeight; const double relativeVisits = points_[m].numVisitsTot() * invNormVisits; if (!skipPoint && relativeVisits < relativeWeight * maxHistogramRatio) { std::string pointValueString = gridPointValueString(grid, m); std::string warningMessage = gmx::formatString( "\nawh%d warning: " "at t = %g ps the obtained coordinate distribution at coordinate value %s " "is less than a fraction %g of the reference distribution at that point. " "If you are not certain about your settings you might want to increase your " "pull force constant or " "modify your sampling region.\n", biasIndex + 1, t, pointValueString.c_str(), maxHistogramRatio); gmx::TextLineWrapper wrapper; wrapper.settings().setLineLength(c_linewidth); fprintf(fplog, "%s", wrapper.wrapToString(warningMessage).c_str()); numWarnings++; } if (numWarnings >= maxNumWarnings) { break; } } return numWarnings; } double BiasState::calcUmbrellaForceAndPotential(ArrayRef<const DimParams> dimParams, const BiasGrid& grid, int point, ArrayRef<const double> neighborLambdaDhdl, ArrayRef<double> force) const { double potential = 0; for (size_t d = 0; d < dimParams.size(); d++) { if (dimParams[d].isFepLambdaDimension()) { if (!neighborLambdaDhdl.empty()) { const int coordpointLambdaIndex = grid.point(point).coordValue[d]; force[d] = neighborLambdaDhdl[coordpointLambdaIndex]; /* The potential should not be affected by the lambda dimension. */ } } else { double deviation = getDeviationFromPointAlongGridAxis(grid, d, point, coordState_.coordValue()[d]); double k = dimParams[d].pullDimParams().k; /* Force from harmonic potential 0.5*k*dev^2 */ force[d] = -k * deviation; potential += 0.5 * k * deviation * deviation; } } return potential; } void BiasState::calcConvolvedForce(ArrayRef<const DimParams> dimParams, const BiasGrid& grid, ArrayRef<const double> probWeightNeighbor, ArrayRef<const double> neighborLambdaDhdl, ArrayRef<double> forceWorkBuffer, ArrayRef<double> force) const { for (size_t d = 0; d < dimParams.size(); d++) { force[d] = 0; } /* Only neighboring points have non-negligible contribution. */ const std::vector<int>& neighbor = grid.point(coordState_.gridpointIndex()).neighbor; gmx::ArrayRef<double> forceFromNeighbor = forceWorkBuffer; for (size_t n = 0; n < neighbor.size(); n++) { double weightNeighbor = probWeightNeighbor[n]; int indexNeighbor = neighbor[n]; /* Get the umbrella force from this point. The returned potential is ignored here. */ calcUmbrellaForceAndPotential(dimParams, grid, indexNeighbor, neighborLambdaDhdl, forceFromNeighbor); /* Add the weighted umbrella force to the convolved force. */ for (size_t d = 0; d < dimParams.size(); d++) { force[d] += forceFromNeighbor[d] * weightNeighbor; } } } double BiasState::moveUmbrella(ArrayRef<const DimParams> dimParams, const BiasGrid& grid, ArrayRef<const double> probWeightNeighbor, ArrayRef<const double> neighborLambdaDhdl, ArrayRef<double> biasForce, int64_t step, int64_t seed, int indexSeed, bool onlySampleUmbrellaGridpoint) { /* Generate and set a new coordinate reference value */ coordState_.sampleUmbrellaGridpoint( grid, coordState_.gridpointIndex(), probWeightNeighbor, step, seed, indexSeed); if (onlySampleUmbrellaGridpoint) { return 0; } std::vector<double> newForce(dimParams.size()); double newPotential = calcUmbrellaForceAndPotential( dimParams, grid, coordState_.umbrellaGridpoint(), neighborLambdaDhdl, newForce); /* A modification of the reference value at time t will lead to a different force over t-dt/2 to t and over t to t+dt/2. For high switching rates this means the force and velocity will change signs roughly as often. To avoid any issues we take the average of the previous and new force at steps when the reference value has been moved. E.g. if the ref. value is set every step to (coord dvalue +/- delta) would give zero force. */ for (gmx::index d = 0; d < biasForce.ssize(); d++) { /* Average of the current and new force */ biasForce[d] = 0.5 * (biasForce[d] + newForce[d]); } return newPotential; } namespace { /*! \brief * Sets the histogram rescaling factors needed to control the histogram size. * * For sake of robustness, the reference weight histogram can grow at a rate * different from the actual sampling rate. Typically this happens for a limited * initial time, alternatively growth is scaled down by a constant factor for all * times. Since the size of the reference histogram sets the size of the free * energy update this should be reflected also in the PMF. Thus the PMF histogram * needs to be rescaled too. * * This function should only be called by the bias update function or wrapped by a function that * knows what scale factors should be applied when, e.g, * getSkippedUpdateHistogramScaleFactors(). * * \param[in] params The bias parameters. * \param[in] newHistogramSize New reference weight histogram size. * \param[in] oldHistogramSize Previous reference weight histogram size (before adding new samples). * \param[out] weightHistScaling Scaling factor for the reference weight histogram. * \param[out] logPmfSumScaling Log of the scaling factor for the PMF histogram. */ void setHistogramUpdateScaleFactors(const BiasParams& params, double newHistogramSize, double oldHistogramSize, double* weightHistScaling, double* logPmfSumScaling) { /* The two scaling factors below are slightly different (ignoring the log factor) because the reference and the PMF histogram apply weight scaling differently. The weight histogram applies is locally, i.e. each sample is scaled down meaning all samples get equal weight. It is done this way because that is what target type local Boltzmann (for which target = weight histogram) needs. In contrast, the PMF histogram is rescaled globally by repeatedly scaling down the whole histogram. The reasons for doing it this way are: 1) empirically this is necessary for converging the PMF; 2) since the extraction of the PMF is theoretically only valid for a constant bias, new samples should get more weight than old ones for which the bias is fluctuating more. */ *weightHistScaling = newHistogramSize / (oldHistogramSize + params.updateWeight * params.localWeightScaling); *logPmfSumScaling = std::log(newHistogramSize / (oldHistogramSize + params.updateWeight)); } } // namespace void BiasState::getSkippedUpdateHistogramScaleFactors(const BiasParams& params, double* weightHistScaling, double* logPmfSumScaling) const { GMX_ASSERT(params.skipUpdates(), "Calling function for skipped updates when skipping updates is not allowed"); if (inInitialStage()) { /* In between global updates the reference histogram size is kept constant so we trivially know what the histogram size was at the time of the skipped update. */ double histogramSize = histogramSize_.histogramSize(); setHistogramUpdateScaleFactors( params, histogramSize, histogramSize, weightHistScaling, logPmfSumScaling); } else { /* In the final stage, the reference histogram grows at the sampling rate which gives trivial scale factors. */ *weightHistScaling = 1; *logPmfSumScaling = 0; } } void BiasState::doSkippedUpdatesForAllPoints(const BiasParams& params) { double weightHistScaling; double logPmfsumScaling; getSkippedUpdateHistogramScaleFactors(params, &weightHistScaling, &logPmfsumScaling); for (auto& pointState : points_) { bool didUpdate = pointState.performPreviouslySkippedUpdates( params, histogramSize_.numUpdates(), weightHistScaling, logPmfsumScaling); /* Update the bias for this point only if there were skipped updates in the past to avoid calculating the log unneccessarily */ if (didUpdate) { pointState.updateBias(); } } } void BiasState::doSkippedUpdatesInNeighborhood(const BiasParams& params, const BiasGrid& grid) { double weightHistScaling; double logPmfsumScaling; getSkippedUpdateHistogramScaleFactors(params, &weightHistScaling, &logPmfsumScaling); /* For each neighbor point of the center point, refresh its state by adding the results of all past, skipped updates. */ const std::vector<int>& neighbors = grid.point(coordState_.gridpointIndex()).neighbor; for (const auto& neighbor : neighbors) { bool didUpdate = points_[neighbor].performPreviouslySkippedUpdates( params, histogramSize_.numUpdates(), weightHistScaling, logPmfsumScaling); if (didUpdate) { points_[neighbor].updateBias(); } } } namespace { /*! \brief * Merge update lists from multiple sharing simulations. * * \param[in,out] updateList Update list for this simulation (assumed >= npoints long). * \param[in] numPoints Total number of points. * \param[in] biasSharing Object for sharing bias data over multiple simulations * \param[in] biasIndex Index of this bias in the total list of biases in this simulation */ void mergeSharedUpdateLists(std::vector<int>* updateList, int numPoints, const BiasSharing& biasSharing, const int biasIndex) { std::vector<int> numUpdatesOfPoint; /* Flag the update points of this sim. TODO: we can probably avoid allocating this array and just use the input array. */ numUpdatesOfPoint.resize(numPoints, 0); for (auto& pointIndex : *updateList) { numUpdatesOfPoint[pointIndex] = 1; } /* Sum over the sims to get all the flagged points */ biasSharing.sum(arrayRefFromArray(numUpdatesOfPoint.data(), numPoints), biasIndex); /* Collect the indices of the flagged points in place. The resulting array will be the merged update list.*/ updateList->clear(); for (int m = 0; m < numPoints; m++) { if (numUpdatesOfPoint[m] > 0) { updateList->push_back(m); } } } /*! \brief * Generate an update list of points sampled since the last update. * * \param[in] grid The AWH bias. * \param[in] points The point state. * \param[in] originUpdatelist The origin of the rectangular region that has been sampled since * last update. \param[in] endUpdatelist The end of the rectangular that has been sampled since * last update. \param[in,out] updateList Local update list to set (assumed >= npoints long). */ void makeLocalUpdateList(const BiasGrid& grid, ArrayRef<const PointState> points, const awh_ivec originUpdatelist, const awh_ivec endUpdatelist, std::vector<int>* updateList) { awh_ivec origin; awh_ivec numPoints; /* Define the update search grid */ for (int d = 0; d < grid.numDimensions(); d++) { origin[d] = originUpdatelist[d]; numPoints[d] = endUpdatelist[d] - originUpdatelist[d] + 1; /* Because the end_updatelist is unwrapped it can be > (npoints - 1) so that numPoints can be > npoints in grid. This helps for calculating the distance/number of points but should be removed and fixed when the way of updating origin/end updatelist is changed (see sampleProbabilityWeights). */ numPoints[d] = std::min(grid.axis(d).numPoints(), numPoints[d]); } /* Make the update list */ updateList->clear(); int pointIndex = -1; bool pointExists = true; while (pointExists) { pointExists = advancePointInSubgrid(grid, origin, numPoints, &pointIndex); if (pointExists && points[pointIndex].inTargetRegion()) { updateList->push_back(pointIndex); } } } } // namespace void BiasState::resetLocalUpdateRange(const BiasGrid& grid) { const int gridpointIndex = coordState_.gridpointIndex(); for (int d = 0; d < grid.numDimensions(); d++) { /* This gives the minimum range consisting only of the current closest point. */ originUpdatelist_[d] = grid.point(gridpointIndex).index[d]; endUpdatelist_[d] = grid.point(gridpointIndex).index[d]; } } namespace { /*! \brief * Add partial histograms (accumulating between updates) to accumulating histograms. * * \param[in,out] pointState The state of the points in the bias. * \param[in,out] weightSumCovering The weights for checking covering. * \param[in] numSharedUpdate The number of biases sharing the histrogram. * \param[in] biasSharing Object for sharing bias data over multiple simulations * \param[in] biasIndex Index of this bias in the total list of biases in this * simulation \param[in] localUpdateList List of points with data. */ void sumHistograms(gmx::ArrayRef<PointState> pointState, gmx::ArrayRef<double> weightSumCovering, int numSharedUpdate, const BiasSharing* biasSharing, const int biasIndex, const std::vector<int>& localUpdateList) { /* The covering checking histograms are added before summing over simulations, so that the weights from different simulations are kept distinguishable. */ for (int globalIndex : localUpdateList) { weightSumCovering[globalIndex] += pointState[globalIndex].weightSumIteration(); } /* Sum histograms over multiple simulations if needed. */ if (numSharedUpdate > 1) { GMX_ASSERT(numSharedUpdate == biasSharing->numSharingSimulations(biasIndex), "Sharing within a simulation is not implemented (yet)"); /* Collect the weights and counts in linear arrays to be able to use gmx_sumd_sim. */ std::vector<double> weightSum; std::vector<double> coordVisits; weightSum.resize(localUpdateList.size()); coordVisits.resize(localUpdateList.size()); for (size_t localIndex = 0; localIndex < localUpdateList.size(); localIndex++) { const PointState& ps = pointState[localUpdateList[localIndex]]; weightSum[localIndex] = ps.weightSumIteration(); coordVisits[localIndex] = ps.numVisitsIteration(); } biasSharing->sum(gmx::ArrayRef<double>(weightSum), biasIndex); biasSharing->sum(gmx::ArrayRef<double>(coordVisits), biasIndex); /* Transfer back the result */ for (size_t localIndex = 0; localIndex < localUpdateList.size(); localIndex++) { PointState& ps = pointState[localUpdateList[localIndex]]; ps.setPartialWeightAndCount(weightSum[localIndex], coordVisits[localIndex]); } } /* Now add the partial counts and weights to the accumulating histograms. Note: we still need to use the weights for the update so we wait with resetting them until the end of the update. */ for (int globalIndex : localUpdateList) { pointState[globalIndex].addPartialWeightAndCount(); } } /*! \brief * Label points along an axis as covered or not. * * A point is covered if it is surrounded by visited points up to a radius = coverRadius. * * \param[in] visited Visited? For each point. * \param[in] checkCovering Check for covering? For each point. * \param[in] numPoints The number of grid points along this dimension. * \param[in] period Period in number of points. * \param[in] coverRadius Cover radius, in points, needed for defining a point as covered. * \param[in,out] covered In this array elements are 1 for covered points and 0 for * non-covered points, this routine assumes that \p covered has at least size \p numPoints. */ void labelCoveredPoints(const std::vector<bool>& visited, const std::vector<bool>& checkCovering, int numPoints, int period, int coverRadius, gmx::ArrayRef<int> covered) { GMX_ASSERT(covered.ssize() >= numPoints, "covered should be at least as large as the grid"); bool haveFirstNotVisited = false; int firstNotVisited = -1; int notVisitedLow = -1; int notVisitedHigh = -1; for (int n = 0; n < numPoints; n++) { if (checkCovering[n] && !visited[n]) { if (!haveFirstNotVisited) { notVisitedLow = n; firstNotVisited = n; haveFirstNotVisited = true; } else { notVisitedHigh = n; /* Have now an interval I = [notVisitedLow,notVisitedHigh] of visited points bounded by unvisited points. The unvisted end points affect the coveredness of the visited with a reach equal to the cover radius. */ int notCoveredLow = notVisitedLow + coverRadius; int notCoveredHigh = notVisitedHigh - coverRadius; for (int i = notVisitedLow; i <= notVisitedHigh; i++) { covered[i] = static_cast<int>((i > notCoveredLow) && (i < notCoveredHigh)); } /* Find a new interval to set covering for. Make the notVisitedHigh of this interval the notVisitedLow of the next. */ notVisitedLow = notVisitedHigh; } } } /* Have labelled all the internal points. Now take care of the boundary regions. */ if (!haveFirstNotVisited) { /* No non-visited points <=> all points visited => all points covered. */ for (int n = 0; n < numPoints; n++) { covered[n] = 1; } } else { int lastNotVisited = notVisitedLow; /* For periodic boundaries, non-visited points can influence points on the other side of the boundary so we need to wrap around. */ /* Lower end. For periodic boundaries the last upper end not visited point becomes the low-end not visited point. For non-periodic boundaries there is no lower end point so a dummy value is used. */ int notVisitedHigh = firstNotVisited; int notVisitedLow = period > 0 ? (lastNotVisited - period) : -(coverRadius + 1); int notCoveredLow = notVisitedLow + coverRadius; int notCoveredHigh = notVisitedHigh - coverRadius; for (int i = 0; i <= notVisitedHigh; i++) { /* For non-periodic boundaries notCoveredLow = -1 will impose no restriction. */ covered[i] = static_cast<int>((i > notCoveredLow) && (i < notCoveredHigh)); } /* Upper end. Same as for lower end but in the other direction. */ notVisitedHigh = period > 0 ? (firstNotVisited + period) : (numPoints + coverRadius); notVisitedLow = lastNotVisited; notCoveredLow = notVisitedLow + coverRadius; notCoveredHigh = notVisitedHigh - coverRadius; for (int i = notVisitedLow; i <= numPoints - 1; i++) { /* For non-periodic boundaries notCoveredHigh = numPoints will impose no restriction. */ covered[i] = static_cast<int>((i > notCoveredLow) && (i < notCoveredHigh)); } } } } // namespace bool BiasState::isSamplingRegionCovered(const BiasParams& params, ArrayRef<const DimParams> dimParams, const BiasGrid& grid) const { /* Allocate and initialize arrays: one for checking visits along each dimension, one for keeping track of which points to check and one for the covered points. Possibly these could be kept as AWH variables to avoid these allocations. */ struct CheckDim { std::vector<bool> visited; std::vector<bool> checkCovering; // We use int for the covering array since we might use gmx_sumi_sim. std::vector<int> covered; }; std::vector<CheckDim> checkDim; checkDim.resize(grid.numDimensions()); for (int d = 0; d < grid.numDimensions(); d++) { const size_t numPoints = grid.axis(d).numPoints(); checkDim[d].visited.resize(numPoints, false); checkDim[d].checkCovering.resize(numPoints, false); checkDim[d].covered.resize(numPoints, 0); } /* Set visited points along each dimension and which points should be checked for covering. Specifically, points above the free energy cutoff (if there is one) or points outside of the target region are ignored. */ /* Set the free energy cutoff */ double maxFreeEnergy = GMX_FLOAT_MAX; if (params.eTarget == AwhTargetType::Cutoff) { maxFreeEnergy = freeEnergyMinimumValue(points_) + params.freeEnergyCutoffInKT; } /* Set the threshold weight for a point to be considered visited. */ double weightThreshold = 1; for (int d = 0; d < grid.numDimensions(); d++) { if (grid.axis(d).isFepLambdaAxis()) { /* Do not modify the weight threshold based on a FEP lambda axis. The spread * of the sampling weights is not depending on a Gaussian distribution (like * below). */ weightThreshold *= 1.0; } else { /* The spacing is proportional to 1/sqrt(betak). The weight threshold will be * approximately (given that the spacing can be modified if the dimension is periodic) * proportional to sqrt(1/(2*pi)). */ weightThreshold *= grid.axis(d).spacing() * std::sqrt(dimParams[d].pullDimParams().betak * 0.5 * M_1_PI); } } /* Project the sampling weights onto each dimension */ for (size_t m = 0; m < grid.numPoints(); m++) { const PointState& pointState = points_[m]; for (int d = 0; d < grid.numDimensions(); d++) { int n = grid.point(m).index[d]; /* Is visited if it was already visited or if there is enough weight at the current point */ checkDim[d].visited[n] = checkDim[d].visited[n] || (weightSumCovering_[m] > weightThreshold); /* Check for covering if there is at least point in this slice that is in the target region and within the cutoff */ checkDim[d].checkCovering[n] = checkDim[d].checkCovering[n] || (pointState.inTargetRegion() && pointState.freeEnergy() < maxFreeEnergy); } } /* Label each point along each dimension as covered or not. */ for (int d = 0; d < grid.numDimensions(); d++) { labelCoveredPoints(checkDim[d].visited, checkDim[d].checkCovering, grid.axis(d).numPoints(), grid.axis(d).numPointsInPeriod(), params.coverRadius()[d], checkDim[d].covered); } /* Now check for global covering. Each dimension needs to be covered separately. A dimension is covered if each point is covered. Multiple simulations collectively cover the points, i.e. a point is covered if any of the simulations covered it. However, visited points are not shared, i.e. if a point is covered or not is determined by the visits of a single simulation. In general the covering criterion is all points covered => all points are surrounded by visited points up to a radius = coverRadius. For 1 simulation, all points covered <=> all points visited. For multiple simulations however, all points visited collectively !=> all points covered, except for coverRadius = 0. In the limit of large coverRadius, all points covered => all points visited by at least one simulation (since no point will be covered until all points have been visited by a single simulation). Basically coverRadius sets how much "connectedness" (or mixing) a point needs with surrounding points before sharing covering information with other simulations. */ /* Communicate the covered points between sharing simulations if needed. */ if (params.numSharedUpdate > 1) { /* For multiple dimensions this may not be the best way to do it. */ for (int d = 0; d < grid.numDimensions(); d++) { biasSharing_->sum(gmx::arrayRefFromArray(checkDim[d].covered.data(), grid.axis(d).numPoints()), params.biasIndex); } } /* Now check if for each dimension all points are covered. Break if not true. */ bool allPointsCovered = true; for (int d = 0; d < grid.numDimensions() && allPointsCovered; d++) { for (int n = 0; n < grid.axis(d).numPoints() && allPointsCovered; n++) { allPointsCovered = (checkDim[d].covered[n] != 0); } } return allPointsCovered; } /*! \brief * Normalizes the free energy and PMF sum. * * \param[in] pointState The state of the points. */ static void normalizeFreeEnergyAndPmfSum(std::vector<PointState>* pointState) { double minF = freeEnergyMinimumValue(*pointState); for (PointState& ps : *pointState) { ps.normalizeFreeEnergyAndPmfSum(minF); } } void BiasState::updateFreeEnergyAndAddSamplesToHistogram(ArrayRef<const DimParams> dimParams, const BiasGrid& grid, const BiasParams& params, double t, int64_t step, FILE* fplog, std::vector<int>* updateList) { /* Note hat updateList is only used in this scope and is always * re-initialized. We do not use a local vector, because that would * cause reallocation every time this funtion is called and the vector * can be the size of the whole grid. */ /* Make a list of all local points, i.e. those that could have been touched since the last update. These are the points needed for summing histograms below (non-local points only add zeros). For local updates, this will also be the final update list. */ makeLocalUpdateList(grid, points_, originUpdatelist_, endUpdatelist_, updateList); if (params.numSharedUpdate > 1) { mergeSharedUpdateLists(updateList, points_.size(), *biasSharing_, params.biasIndex); } /* Reset the range for the next update */ resetLocalUpdateRange(grid); /* Add samples to histograms for all local points and sync simulations if needed */ sumHistograms(points_, weightSumCovering_, params.numSharedUpdate, biasSharing_, params.biasIndex, *updateList); sumPmf(points_, params.numSharedUpdate, biasSharing_, params.biasIndex); /* Renormalize the free energy if values are too large. */ bool needToNormalizeFreeEnergy = false; for (int& globalIndex : *updateList) { /* We want to keep the absolute value of the free energies to be less c_largePositiveExponent to be able to safely pass these values to exp(). The check below ensures this as long as the free energy values grow less than 0.5*c_largePositiveExponent in a return time to this neighborhood. For reasonable update sizes it's unlikely that this requirement would be broken. */ if (std::abs(points_[globalIndex].freeEnergy()) > 0.5 * detail::c_largePositiveExponent) { needToNormalizeFreeEnergy = true; break; } } /* Update target distribution? */ bool needToUpdateTargetDistribution = (params.eTarget != AwhTargetType::Constant && params.isUpdateTargetStep(step)); /* In the initial stage, the histogram grows dynamically as a function of the number of coverings. */ bool detectedCovering = false; if (inInitialStage()) { detectedCovering = (params.isCheckCoveringStep(step) && isSamplingRegionCovered(params, dimParams, grid)); } /* The weighthistogram size after this update. */ double newHistogramSize = histogramSize_.newHistogramSize( params, t, detectedCovering, points_, weightSumCovering_, fplog); /* Make the update list. Usually we try to only update local points, * but if the update has non-trivial or non-deterministic effects * on non-local points a global update is needed. This is the case when: * 1) a covering occurred in the initial stage, leading to non-trivial * histogram rescaling factors; or * 2) the target distribution will be updated, since we don't make any * assumption on its form; or * 3) the AWH parameters are such that we never attempt to skip non-local * updates; or * 4) the free energy values have grown so large that a renormalization * is needed. */ if (needToUpdateTargetDistribution || detectedCovering || !params.skipUpdates() || needToNormalizeFreeEnergy) { /* Global update, just add all points. */ updateList->clear(); for (size_t m = 0; m < points_.size(); m++) { if (points_[m].inTargetRegion()) { updateList->push_back(m); } } } /* Set histogram scale factors. */ double weightHistScalingSkipped = 0; double logPmfsumScalingSkipped = 0; if (params.skipUpdates()) { getSkippedUpdateHistogramScaleFactors(params, &weightHistScalingSkipped, &logPmfsumScalingSkipped); } double weightHistScalingNew; double logPmfsumScalingNew; setHistogramUpdateScaleFactors( params, newHistogramSize, histogramSize_.histogramSize(), &weightHistScalingNew, &logPmfsumScalingNew); /* Update free energy and reference weight histogram for points in the update list. */ for (int pointIndex : *updateList) { PointState* pointStateToUpdate = &points_[pointIndex]; /* Do updates from previous update steps that were skipped because this point was at that time non-local. */ if (params.skipUpdates()) { pointStateToUpdate->performPreviouslySkippedUpdates( params, histogramSize_.numUpdates(), weightHistScalingSkipped, logPmfsumScalingSkipped); } /* Now do an update with new sampling data. */ pointStateToUpdate->updateWithNewSampling( params, histogramSize_.numUpdates(), weightHistScalingNew, logPmfsumScalingNew); } /* Only update the histogram size after we are done with the local point updates */ histogramSize_.setHistogramSize(newHistogramSize, weightHistScalingNew); if (needToNormalizeFreeEnergy) { normalizeFreeEnergyAndPmfSum(&points_); } if (needToUpdateTargetDistribution) { /* The target distribution is always updated for all points at once. */ updateTargetDistribution(points_, params); } /* Update the bias. The bias is updated separately and last since it simply a function of the free energy and the target distribution and we want to avoid doing extra work. */ for (int pointIndex : *updateList) { points_[pointIndex].updateBias(); } /* Increase the update counter. */ histogramSize_.incrementNumUpdates(); } double BiasState::updateProbabilityWeightsAndConvolvedBias(ArrayRef<const DimParams> dimParams, const BiasGrid& grid, ArrayRef<const double> neighborLambdaEnergies, std::vector<double, AlignedAllocator<double>>* weight) const { /* Only neighbors of the current coordinate value will have a non-negligible chance of getting sampled */ const std::vector<int>& neighbors = grid.point(coordState_.gridpointIndex()).neighbor; #if GMX_SIMD_HAVE_DOUBLE typedef SimdDouble PackType; constexpr int packSize = GMX_SIMD_DOUBLE_WIDTH; #else typedef double PackType; constexpr int packSize = 1; #endif /* Round the size of the weight array up to packSize */ const int weightSize = ((neighbors.size() + packSize - 1) / packSize) * packSize; weight->resize(weightSize); double* gmx_restrict weightData = weight->data(); PackType weightSumPack(0.0); for (size_t i = 0; i < neighbors.size(); i += packSize) { for (size_t n = i; n < i + packSize; n++) { if (n < neighbors.size()) { const int neighbor = neighbors[n]; (*weight)[n] = biasedLogWeightFromPoint(dimParams, points_, grid, neighbor, points_[neighbor].bias(), coordState_.coordValue(), neighborLambdaEnergies, coordState_.gridpointIndex()); } else { /* Pad with values that don't affect the result */ (*weight)[n] = detail::c_largeNegativeExponent; } } PackType weightPack = load<PackType>(weightData + i); weightPack = gmx::exp(weightPack); weightSumPack = weightSumPack + weightPack; store(weightData + i, weightPack); } /* Sum of probability weights */ double weightSum = reduce(weightSumPack); GMX_RELEASE_ASSERT(weightSum > 0, "zero probability weight when updating AWH probability weights."); /* Normalize probabilities to sum to 1 */ double invWeightSum = 1 / weightSum; /* When there is a free energy lambda state axis remove the convolved contributions along that * axis from the total bias. This must be done after calculating invWeightSum (since weightSum * will be modified), but before normalizing the weights (below). */ if (grid.hasLambdaAxis()) { /* If there is only one axis the bias will not be convolved in any dimension. */ if (grid.axis().size() == 1) { weightSum = gmx::exp(points_[coordState_.gridpointIndex()].bias()); } else { for (size_t i = 0; i < neighbors.size(); i++) { const int neighbor = neighbors[i]; if (pointsHaveDifferentLambda(grid, coordState_.gridpointIndex(), neighbor)) { weightSum -= weightData[i]; } } } } for (double& w : *weight) { w *= invWeightSum; } /* Return the convolved bias */ return std::log(weightSum); } double BiasState::calcConvolvedBias(ArrayRef<const DimParams> dimParams, const BiasGrid& grid, const awh_dvec& coordValue) const { int point = grid.nearestIndex(coordValue); const GridPoint& gridPoint = grid.point(point); /* Sum the probability weights from the neighborhood of the given point */ double weightSum = 0; for (int neighbor : gridPoint.neighbor) { /* No convolution is required along the lambda dimension. */ if (pointsHaveDifferentLambda(grid, point, neighbor)) { continue; } double logWeight = biasedLogWeightFromPoint( dimParams, points_, grid, neighbor, points_[neighbor].bias(), coordValue, {}, point); weightSum += std::exp(logWeight); } /* Returns -GMX_FLOAT_MAX if no neighboring points were in the target region. */ return (weightSum > 0) ? std::log(weightSum) : -GMX_FLOAT_MAX; } void BiasState::sampleProbabilityWeights(const BiasGrid& grid, gmx::ArrayRef<const double> probWeightNeighbor) { const std::vector<int>& neighbor = grid.point(coordState_.gridpointIndex()).neighbor; /* Save weights for next update */ for (size_t n = 0; n < neighbor.size(); n++) { points_[neighbor[n]].increaseWeightSumIteration(probWeightNeighbor[n]); } /* Update the local update range. Two corner points define this rectangular * domain. We need to choose two new corner points such that the new domain * contains both the old update range and the current neighborhood. * In the simplest case when an update is performed every sample, * the update range would simply equal the current neighborhood. */ int neighborStart = neighbor[0]; int neighborLast = neighbor[neighbor.size() - 1]; for (int d = 0; d < grid.numDimensions(); d++) { int origin = grid.point(neighborStart).index[d]; int last = grid.point(neighborLast).index[d]; if (origin > last) { /* Unwrap if wrapped around the boundary (only happens for periodic * boundaries). This has been already for the stored index interval. */ /* TODO: what we want to do is to find the smallest the update * interval that contains all points that need to be updated. * This amounts to combining two intervals, the current * [origin, end] update interval and the new touched neighborhood * into a new interval that contains all points from both the old * intervals. * * For periodic boundaries it becomes slightly more complicated * than for closed boundaries because then it needs not be * true that origin < end (so one can't simply relate the origin/end * in the min()/max() below). The strategy here is to choose the * origin closest to a reference point (index 0) and then unwrap * the end index if needed and choose the largest end index. * This ensures that both intervals are in the new interval * but it's not necessarily the smallest. * Currently we solve this by going through each possibility * and checking them. */ last += grid.axis(d).numPointsInPeriod(); } originUpdatelist_[d] = std::min(originUpdatelist_[d], origin); endUpdatelist_[d] = std::max(endUpdatelist_[d], last); } } void BiasState::sampleCoordAndPmf(const std::vector<DimParams>& dimParams, const BiasGrid& grid, gmx::ArrayRef<const double> probWeightNeighbor, double convolvedBias) { /* Sampling-based deconvolution extracting the PMF. * Update the PMF histogram with the current coordinate value. * * Because of the finite width of the harmonic potential, the free energy * defined for each coordinate point does not exactly equal that of the * actual coordinate, the PMF. However, the PMF can be estimated by applying * the relation exp(-PMF) = exp(-bias_convolved)*P_biased/Z, i.e. by keeping a * reweighted histogram of the coordinate value. Strictly, this relies on * the unknown normalization constant Z being either constant or known. Here, * neither is true except in the long simulation time limit. Empirically however, * it works (mainly because how the PMF histogram is rescaled). */ const int gridPointIndex = coordState_.gridpointIndex(); const std::optional<int> lambdaAxisIndex = grid.lambdaAxisIndex(); /* Update the PMF of points along a lambda axis with their bias. */ if (lambdaAxisIndex) { const std::vector<int>& neighbors = grid.point(gridPointIndex).neighbor; std::vector<double> lambdaMarginalDistribution = calculateFELambdaMarginalDistribution(grid, neighbors, probWeightNeighbor); awh_dvec coordValueAlongLambda = { coordState_.coordValue()[0], coordState_.coordValue()[1], coordState_.coordValue()[2], coordState_.coordValue()[3] }; for (size_t i = 0; i < neighbors.size(); i++) { const int neighbor = neighbors[i]; double bias; if (pointsAlongLambdaAxis(grid, gridPointIndex, neighbor)) { const double neighborLambda = grid.point(neighbor).coordValue[lambdaAxisIndex.value()]; if (neighbor == gridPointIndex) { bias = convolvedBias; } else { coordValueAlongLambda[lambdaAxisIndex.value()] = neighborLambda; bias = calcConvolvedBias(dimParams, grid, coordValueAlongLambda); } const double probWeight = lambdaMarginalDistribution[neighborLambda]; const double weightedBias = bias - std::log(std::max(probWeight, GMX_DOUBLE_MIN)); // avoid log(0) if (neighbor == gridPointIndex && grid.covers(coordState_.coordValue())) { points_[neighbor].samplePmf(weightedBias); } else { points_[neighbor].updatePmfUnvisited(weightedBias); } } } } else { /* Only save coordinate data that is in range (the given index is always * in range even if the coordinate value is not). */ if (grid.covers(coordState_.coordValue())) { /* Save PMF sum and keep a histogram of the sampled coordinate values */ points_[gridPointIndex].samplePmf(convolvedBias); } } /* Save probability weights for the update */ sampleProbabilityWeights(grid, probWeightNeighbor); } void BiasState::initHistoryFromState(AwhBiasHistory* biasHistory) const { biasHistory->pointState.resize(points_.size()); } void BiasState::updateHistory(AwhBiasHistory* biasHistory, const BiasGrid& grid) const { GMX_RELEASE_ASSERT(biasHistory->pointState.size() == points_.size(), "The AWH history setup does not match the AWH state."); AwhBiasStateHistory* stateHistory = &biasHistory->state; stateHistory->umbrellaGridpoint = coordState_.umbrellaGridpoint(); for (size_t m = 0; m < biasHistory->pointState.size(); m++) { AwhPointStateHistory* psh = &biasHistory->pointState[m]; points_[m].storeState(psh); psh->weightsum_covering = weightSumCovering_[m]; } histogramSize_.storeState(stateHistory); stateHistory->origin_index_updatelist = multiDimGridIndexToLinear(grid, originUpdatelist_); stateHistory->end_index_updatelist = multiDimGridIndexToLinear(grid, endUpdatelist_); } void BiasState::restoreFromHistory(const AwhBiasHistory& biasHistory, const BiasGrid& grid) { const AwhBiasStateHistory& stateHistory = biasHistory.state; coordState_.restoreFromHistory(stateHistory); if (biasHistory.pointState.size() != points_.size()) { GMX_THROW( InvalidInputError("Bias grid size in checkpoint and simulation do not match. " "Likely you provided a checkpoint from a different simulation.")); } for (size_t m = 0; m < points_.size(); m++) { points_[m].setFromHistory(biasHistory.pointState[m]); } for (size_t m = 0; m < weightSumCovering_.size(); m++) { weightSumCovering_[m] = biasHistory.pointState[m].weightsum_covering; } histogramSize_.restoreFromHistory(stateHistory); linearGridindexToMultiDim(grid, stateHistory.origin_index_updatelist, originUpdatelist_); linearGridindexToMultiDim(grid, stateHistory.end_index_updatelist, endUpdatelist_); } void BiasState::broadcast(const t_commrec* commRecord) { gmx_bcast(sizeof(coordState_), &coordState_, commRecord->mpi_comm_mygroup); gmx_bcast(points_.size() * sizeof(PointState), points_.data(), commRecord->mpi_comm_mygroup); gmx_bcast(weightSumCovering_.size() * sizeof(double), weightSumCovering_.data(), commRecord->mpi_comm_mygroup); gmx_bcast(sizeof(histogramSize_), &histogramSize_, commRecord->mpi_comm_mygroup); } void BiasState::setFreeEnergyToConvolvedPmf(ArrayRef<const DimParams> dimParams, const BiasGrid& grid) { std::vector<float> convolvedPmf; calcConvolvedPmf(dimParams, grid, &convolvedPmf); for (size_t m = 0; m < points_.size(); m++) { points_[m].setFreeEnergy(convolvedPmf[m]); } } /*! \brief * Count trailing data rows containing only zeros. * * \param[in] data 2D data array. * \param[in] numRows Number of rows in array. * \param[in] numColumns Number of cols in array. * \returns the number of trailing zero rows. */ static int countTrailingZeroRows(const double* const* data, int numRows, int numColumns) { int numZeroRows = 0; for (int m = numRows - 1; m >= 0; m--) { bool rowIsZero = true; for (int d = 0; d < numColumns; d++) { if (data[d][m] != 0) { rowIsZero = false; break; } } if (!rowIsZero) { /* At a row with non-zero data */ break; } else { /* Still at a zero data row, keep checking rows higher up. */ numZeroRows++; } } return numZeroRows; } /*! \brief * Initializes the PMF and target with data read from an input table. * * \param[in] dimParams The dimension parameters. * \param[in] grid The grid. * \param[in] filename The filename to read PMF and target from. * \param[in] numBias Number of biases. * \param[in] biasIndex The index of the bias. * \param[in,out] pointState The state of the points in this bias. */ static void readUserPmfAndTargetDistribution(ArrayRef<const DimParams> dimParams, const BiasGrid& grid, const std::string& filename, int numBias, int biasIndex, std::vector<PointState>* pointState) { /* Read the PMF and target distribution. From the PMF, the convolved PMF, or the reference value free energy, can be calculated base on the force constant. The free energy and target together determine the bias. */ std::string filenameModified(filename); if (numBias > 1) { size_t n = filenameModified.rfind('.'); GMX_RELEASE_ASSERT(n != std::string::npos, "The filename should contain an extension starting with ."); filenameModified.insert(n, formatString("%d", biasIndex)); } std::string correctFormatMessage = formatString( "%s is expected in the following format. " "The first ndim column(s) should contain the coordinate values for each point, " "each column containing values of one dimension (in ascending order). " "For a multidimensional coordinate, points should be listed " "in the order obtained by traversing lower dimensions first. " "E.g. for two-dimensional grid of size nxn: " "(1, 1), (1, 2),..., (1, n), (2, 1), (2, 2), ..., , (n, n - 1), (n, n). " "Column ndim + 1 should contain the PMF value for each coordinate value. " "The target distribution values should be in column ndim + 2 or column ndim + 5. " "Make sure the input file ends with a new line but has no trailing new lines.", filename.c_str()); gmx::TextLineWrapper wrapper; wrapper.settings().setLineLength(c_linewidth); correctFormatMessage = wrapper.wrapToString(correctFormatMessage); double** data; int numColumns; int numRows = read_xvg(filenameModified.c_str(), &data, &numColumns); /* Check basic data properties here. BiasGrid takes care of more complicated things. */ if (numRows <= 0) { std::string mesg = gmx::formatString( "%s is empty!.\n\n%s", filename.c_str(), correctFormatMessage.c_str()); GMX_THROW(InvalidInputError(mesg)); } /* Less than 2 points is not useful for PMF or target. */ if (numRows < 2) { std::string mesg = gmx::formatString( "%s contains too few data points (%d)." "The minimum number of points is 2.", filename.c_str(), numRows); GMX_THROW(InvalidInputError(mesg)); } /* Make sure there are enough columns of data. Two formats are allowed. Either with columns {coords, PMF, target} or {coords, PMF, x, y, z, target, ...}. The latter format is allowed since that is how AWH output is written (x, y, z being other AWH variables). For this format, trailing columns are ignored. */ int columnIndexTarget; int numColumnsMin = dimParams.size() + 2; int columnIndexPmf = dimParams.size(); if (numColumns == numColumnsMin) { columnIndexTarget = columnIndexPmf + 1; } else { columnIndexTarget = columnIndexPmf + 4; } if (numColumns < numColumnsMin) { std::string mesg = gmx::formatString( "The number of columns in %s should be at least %d." "\n\n%s", filename.c_str(), numColumnsMin, correctFormatMessage.c_str()); GMX_THROW(InvalidInputError(mesg)); } /* read_xvg can give trailing zero data rows for trailing new lines in the input. We allow 1 zero row, since this could be real data. But multiple trailing zero rows cannot correspond to valid data. */ int numZeroRows = countTrailingZeroRows(data, numRows, numColumns); if (numZeroRows > 1) { std::string mesg = gmx::formatString( "Found %d trailing zero data rows in %s. Please remove trailing empty lines and " "try again.", numZeroRows, filename.c_str()); GMX_THROW(InvalidInputError(mesg)); } /* Convert from user units to internal units before sending the data of to grid. */ for (size_t d = 0; d < dimParams.size(); d++) { double scalingFactor = dimParams[d].scaleUserInputToInternal(1); if (scalingFactor == 1) { continue; } for (size_t m = 0; m < pointState->size(); m++) { data[d][m] *= scalingFactor; } } /* Get a data point for each AWH grid point so that they all get data. */ std::vector<int> gridIndexToDataIndex(grid.numPoints()); mapGridToDataGrid(&gridIndexToDataIndex, data, numRows, filename, grid, correctFormatMessage); /* Extract the data for each grid point. * We check if the target distribution is zero for all points. */ bool targetDistributionIsZero = true; for (size_t m = 0; m < pointState->size(); m++) { (*pointState)[m].setLogPmfSum(-data[columnIndexPmf][gridIndexToDataIndex[m]]); double target = data[columnIndexTarget][gridIndexToDataIndex[m]]; /* Check if the values are allowed. */ if (target < 0) { std::string mesg = gmx::formatString( "Target distribution weight at point %zu (%g) in %s is negative.", m, target, filename.c_str()); GMX_THROW(InvalidInputError(mesg)); } if (target > 0) { targetDistributionIsZero = false; } (*pointState)[m].setTargetConstantWeight(target); } if (targetDistributionIsZero) { std::string mesg = gmx::formatString("The target weights given in column %d in %s are all 0", columnIndexTarget, filename.c_str()); GMX_THROW(InvalidInputError(mesg)); } /* Free the arrays. */ for (int m = 0; m < numColumns; m++) { sfree(data[m]); } sfree(data); } void BiasState::normalizePmf(int numSharingSims) { /* The normalization of the PMF estimate matters because it determines how big effect the next sample has. Approximately (for large enough force constant) we should have: sum_x(exp(-pmf(x)) = nsamples*sum_xref(exp(-f(xref)). */ /* Calculate the normalization factor, i.e. divide by the pmf sum, multiply by the number of samples and the f sum */ double expSumPmf = 0; double expSumF = 0; for (const PointState& pointState : points_) { if (pointState.inTargetRegion()) { expSumPmf += std::exp(pointState.logPmfSum()); expSumF += std::exp(-pointState.freeEnergy()); } } double numSamples = histogramSize_.histogramSize() / numSharingSims; /* Renormalize */ double logRenorm = std::log(numSamples * expSumF / expSumPmf); for (PointState& pointState : points_) { if (pointState.inTargetRegion()) { pointState.setLogPmfSum(pointState.logPmfSum() + logRenorm); } } } void BiasState::initGridPointState(const AwhBiasParams& awhBiasParams, ArrayRef<const DimParams> dimParams, const BiasGrid& grid, const BiasParams& params, const std::string& filename, int numBias) { /* Modify PMF, free energy and the constant target distribution factor * to user input values if there is data given. */ if (awhBiasParams.userPMFEstimate()) { readUserPmfAndTargetDistribution(dimParams, grid, filename, numBias, params.biasIndex, &points_); setFreeEnergyToConvolvedPmf(dimParams, grid); } /* The local Boltzmann distribution is special because the target distribution is updated as a function of the reference weighthistogram. */ GMX_RELEASE_ASSERT(params.eTarget != AwhTargetType::LocalBoltzmann || points_[0].weightSumRef() != 0, "AWH reference weight histogram not initialized properly with local " "Boltzmann target distribution."); updateTargetDistribution(points_, params); for (PointState& pointState : points_) { if (pointState.inTargetRegion()) { pointState.updateBias(); } else { /* Note that for zero target this is a value that represents -infinity but should not be used for biasing. */ pointState.setTargetToZero(); } } /* Set the initial reference weighthistogram. */ const double histogramSize = histogramSize_.histogramSize(); for (auto& pointState : points_) { pointState.setInitialReferenceWeightHistogram(histogramSize); } /* Make sure the pmf is normalized consistently with the histogram size. Note: the target distribution and free energy need to be set here. */ normalizePmf(params.numSharedUpdate); } BiasState::BiasState(const AwhBiasParams& awhBiasParams, double histogramSizeInitial, ArrayRef<const DimParams> dimParams, const BiasGrid& grid, const BiasSharing* biasSharing) : coordState_(awhBiasParams, dimParams, grid), points_(grid.numPoints()), weightSumCovering_(grid.numPoints()), histogramSize_(awhBiasParams, histogramSizeInitial), biasSharing_(biasSharing) { /* The minimum and maximum multidimensional point indices that are affected by the next update */ for (size_t d = 0; d < dimParams.size(); d++) { int index = grid.point(coordState_.gridpointIndex()).index[d]; originUpdatelist_[d] = index; endUpdatelist_[d] = index; } } } // namespace gmx <|start_filename|>src/gromacs/ewald/tests/pmegathertest.cpp<|end_filename|> /* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2016,2017,2018,2019,2020,2021, by the GROMACS development team, led by * <NAME>, <NAME>, <NAME>, and <NAME>, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS 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. * * GROMACS 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 GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ /*! \internal \file * \brief * Implements PME force gathering tests. * * \author <NAME> <<EMAIL>> * \ingroup module_ewald */ #include "gmxpre.h" #include <string> #include <gmock/gmock.h> #include "gromacs/mdtypes/inputrec.h" #include "gromacs/utility/stringutil.h" #include "testutils/refdata.h" #include "testutils/test_hardware_environment.h" #include "testutils/testasserts.h" #include "pmetestcommon.h" namespace gmx { namespace test { namespace { /* Valid input instances */ //! A couple of valid inputs for boxes. std::vector<Matrix3x3> const c_sampleBoxes{ // normal box Matrix3x3{ { 8.0F, 0.0F, 0.0F, 0.0F, 3.4F, 0.0F, 0.0F, 0.0F, 2.0F } }, // triclinic box Matrix3x3{ { 7.0F, 0.0F, 0.0F, 0.0F, 4.1F, 0.0F, 3.5F, 2.0F, 12.2F } }, }; //! A couple of valid inputs for grid sizes std::vector<IVec> const c_sampleGridSizes{ IVec{ 16, 12, 14 }, IVec{ 13, 15, 11 } }; //! Random charges std::vector<real> const c_sampleChargesFull{ 4.95F, 3.11F, 3.97F, 1.08F, 2.09F, 1.1F, 4.13F, 3.31F, 2.8F, 5.83F, 5.09F, 6.1F, 2.86F, 0.24F, 5.76F, 5.19F, 0.72F }; //! All the input atom gridline indices std::vector<IVec> const c_sampleGridLineIndicesFull{ IVec{ 4, 2, 6 }, IVec{ 1, 4, 10 }, IVec{ 0, 6, 6 }, IVec{ 0, 1, 4 }, IVec{ 6, 3, 0 }, IVec{ 7, 2, 2 }, IVec{ 8, 3, 1 }, IVec{ 4, 0, 3 }, IVec{ 0, 0, 0 }, IVec{ 8, 5, 8 }, IVec{ 4, 4, 2 }, IVec{ 7, 1, 7 }, IVec{ 8, 5, 5 }, IVec{ 2, 6, 5 }, IVec{ 1, 6, 2 }, IVec{ 7, 1, 8 }, IVec{ 3, 5, 1 }, }; // Spline values/derivatives below are also generated randomly, so they are bogus, // but that should not affect the reproducibility, which we're after //! A lot of bogus input spline values - should have at list (max PME order = 5) * (DIM = 3) * (total unique atom number in all test cases = 16) values std::vector<real> const c_sampleSplineValuesFull{ 0.12F, 0.81F, 0.29F, 0.22F, 0.13F, 0.19F, 0.12F, 0.8F, 0.44F, 0.38F, 0.32F, 0.36F, 0.27F, 0.11F, 0.17F, 0.94F, 0.07F, 0.9F, 0.98F, 0.96F, 0.07F, 0.94F, 0.77F, 0.24F, 0.84F, 0.16F, 0.77F, 0.57F, 0.52F, 0.27F, 0.39F, 0.45F, 0.6F, 0.59F, 0.44F, 0.91F, 0.97F, 0.43F, 0.24F, 0.52F, 0.73F, 0.55F, 0.99F, 0.39F, 0.97F, 0.35F, 0.1F, 0.68F, 0.19F, 0.1F, 0.77F, 0.2F, 0.43F, 0.69F, 0.76F, 0.32F, 0.31F, 0.94F, 0.53F, 0.6F, 0.93F, 0.57F, 0.94F, 0.88F, 0.75F, 0.77F, 0.91F, 0.72F, 0.07F, 0.78F, 0.09F, 0.02F, 0.48F, 0.97F, 0.89F, 0.39F, 0.48F, 0.19F, 0.02F, 0.92F, 0.8F, 0.41F, 0.53F, 0.32F, 0.38F, 0.58F, 0.36F, 0.46F, 0.92F, 0.91F, 0.01F, 0.86F, 0.54F, 0.86F, 0.94F, 0.37F, 0.35F, 0.81F, 0.89F, 0.48F, 0.34F, 0.18F, 0.11F, 0.02F, 0.87F, 0.95F, 0.66F, 0.67F, 0.38F, 0.45F, 0.04F, 0.94F, 0.54F, 0.76F, 0.58F, 0.83F, 0.31F, 0.73F, 0.71F, 0.06F, 0.35F, 0.32F, 0.35F, 0.61F, 0.27F, 0.98F, 0.83F, 0.11F, 0.3F, 0.42F, 0.95F, 0.69F, 0.58F, 0.29F, 0.1F, 0.68F, 0.94F, 0.62F, 0.51F, 0.47F, 0.04F, 0.47F, 0.34F, 0.71F, 0.52F, 0.19F, 0.69F, 0.5F, 0.59F, 0.05F, 0.74F, 0.11F, 0.4F, 0.81F, 0.24F, 0.53F, 0.71F, 0.07F, 0.17F, 0.41F, 0.23F, 0.78F, 0.27F, 0.1F, 0.71F, 0.36F, 0.67F, 0.6F, 0.94F, 0.69F, 0.19F, 0.58F, 0.68F, 0.5F, 0.62F, 0.38F, 0.29F, 0.44F, 0.04F, 0.89F, 0.0F, 0.76F, 0.22F, 0.16F, 0.08F, 0.62F, 0.51F, 0.62F, 0.83F, 0.72F, 0.96F, 0.99F, 0.4F, 0.79F, 0.83F, 0.21F, 0.43F, 0.32F, 0.44F, 0.72F, 0.21F, 0.4F, 0.93F, 0.07F, 0.11F, 0.41F, 0.24F, 0.04F, 0.36F, 0.15F, 0.92F, 0.08F, 0.99F, 0.35F, 0.42F, 0.7F, 0.17F, 0.39F, 0.69F, 0.0F, 0.86F, 0.89F, 0.59F, 0.81F, 0.77F, 0.15F, 0.89F, 0.17F, 0.76F, 0.67F, 0.58F, 0.78F, 0.26F, 0.19F, 0.69F, 0.18F, 0.46F, 0.6F, 0.69F, 0.23F, 0.34F, 0.3F, 0.64F, 0.34F, 0.6F, 0.99F, 0.69F, 0.57F, 0.75F, 0.07F, 0.36F, 0.75F, 0.81F, 0.8F, 0.42F, 0.09F, 0.94F, 0.66F, 0.35F, 0.67F, 0.34F, 0.66F, 0.02F, 0.47F, 0.78F, 0.21F, 0.02F, 0.18F, 0.42F, 0.2F, 0.46F, 0.34F, 0.4F, 0.46F, 0.96F, 0.86F, 0.25F, 0.25F, 0.22F, 0.37F, 0.59F, 0.19F, 0.45F, 0.61F, 0.04F, 0.71F, 0.77F, 0.51F, 0.77F, 0.15F, 0.78F, 0.36F, 0.62F, 0.24F, 0.86F, 0.2F, 0.77F, 0.08F, 0.09F, 0.3F, 0.0F, 0.6F, 0.99F, 0.69F, }; //! A lot of bogus input spline derivatives - should have at list (max PME order = 5) * (DIM = 3) * (total unique atom number in all test cases = 16) values std::vector<real> const c_sampleSplineDerivativesFull{ 0.82F, 0.88F, 0.83F, 0.11F, 0.93F, 0.32F, 0.71F, 0.37F, 0.69F, 0.88F, 0.11F, 0.38F, 0.25F, 0.5F, 0.36F, 0.81F, 0.78F, 0.31F, 0.66F, 0.32F, 0.27F, 0.35F, 0.53F, 0.83F, 0.08F, 0.08F, 0.94F, 0.71F, 0.65F, 0.24F, 0.13F, 0.01F, 0.33F, 0.65F, 0.24F, 0.53F, 0.45F, 0.84F, 0.33F, 0.97F, 0.31F, 0.7F, 0.03F, 0.31F, 0.41F, 0.76F, 0.12F, 0.3F, 0.57F, 0.65F, 0.87F, 0.99F, 0.42F, 0.97F, 0.32F, 0.39F, 0.73F, 0.23F, 0.03F, 0.67F, 0.97F, 0.57F, 0.42F, 0.38F, 0.54F, 0.17F, 0.53F, 0.54F, 0.18F, 0.8F, 0.76F, 0.13F, 0.29F, 0.83F, 0.77F, 0.56F, 0.4F, 0.87F, 0.36F, 0.18F, 0.59F, 0.04F, 0.05F, 0.61F, 0.26F, 0.91F, 0.62F, 0.16F, 0.89F, 0.23F, 0.26F, 0.59F, 0.33F, 0.2F, 0.49F, 0.41F, 0.25F, 0.4F, 0.16F, 0.83F, 0.44F, 0.82F, 0.21F, 0.95F, 0.14F, 0.8F, 0.37F, 0.31F, 0.41F, 0.53F, 0.15F, 0.85F, 0.78F, 0.17F, 0.92F, 0.03F, 0.13F, 0.2F, 0.03F, 0.33F, 0.87F, 0.38F, 0, 0.08F, 0.79F, 0.36F, 0.53F, 0.05F, 0.07F, 0.94F, 0.23F, 0.85F, 0.13F, 0.27F, 0.23F, 0.22F, 0.26F, 0.38F, 0.15F, 0.48F, 0.18F, 0.33F, 0.23F, 0.62F, 0.1F, 0.36F, 0.99F, 0.07F, 0.02F, 0.04F, 0.09F, 0.29F, 0.52F, 0.29F, 0.83F, 0.97F, 0.61F, 0.81F, 0.49F, 0.56F, 0.08F, 0.09F, 0.03F, 0.65F, 0.46F, 0.1F, 0.06F, 0.06F, 0.39F, 0.29F, 0.04F, 0.03F, 0.1F, 0.83F, 0.94F, 0.59F, 0.97F, 0.82F, 0.2F, 0.66F, 0.23F, 0.11F, 0.03F, 0.16F, 0.27F, 0.53F, 0.94F, 0.46F, 0.43F, 0.29F, 0.97F, 0.64F, 0.46F, 0.37F, 0.43F, 0.48F, 0.37F, 0.93F, 0.5F, 0.2F, 0.92F, 0.09F, 0.74F, 0.55F, 0.44F, 0.05F, 0.13F, 0.17F, 0.79F, 0.44F, 0.11F, 0.6F, 0.64F, 0.05F, 0.96F, 0.3F, 0.45F, 0.47F, 0.42F, 0.74F, 0.91F, 0.06F, 0.89F, 0.24F, 0.26F, 0.68F, 0.4F, 0.88F, 0.5F, 0.65F, 0.48F, 0.15F, 0.0F, 0.41F, 0.67F, 0.4F, 0.31F, 0.73F, 0.77F, 0.36F, 0.26F, 0.74F, 0.46F, 0.56F, 0.78F, 0.92F, 0.32F, 0.9F, 0.06F, 0.55F, 0.6F, 0.13F, 0.38F, 0.93F, 0.5F, 0.92F, 0.96F, 0.82F, 0.0F, 0.04F, 0.9F, 0.55F, 0.97F, 1.0F, 0.23F, 0.46F, 0.52F, 0.49F, 0.0F, 0.32F, 0.16F, 0.4F, 0.62F, 0.36F, 0.03F, 0.63F, 0.16F, 0.58F, 0.97F, 0.03F, 0.44F, 0.07F, 0.22F, 0.75F, 0.32F, 0.61F, 0.94F, 0.33F, 0.7F, 0.57F, 0.5F, 0.84F, 0.7F, 0.47F, 0.18F, 0.09F, 0.25F, 0.77F, 0.94F, 0.85F, 0.09F, 0.83F, 0.02F, 0.91F, }; //! 2 c_sample grids - only non-zero values have to be listed std::vector<SparseRealGridValuesInput> const c_sampleGrids{ SparseRealGridValuesInput{ { IVec{ 0, 0, 0 }, 3.5F }, { IVec{ 7, 0, 0 }, -2.5F }, { IVec{ 3, 5, 7 }, -0.006F }, { IVec{ 1, 6, 7 }, -2.76F }, { IVec{ 3, 1, 2 }, 0.6F }, { IVec{ 6, 2, 4 }, 7.1F }, { IVec{ 4, 5, 6 }, 4.1F }, { IVec{ 4, 4, 6 }, -3.7F }, }, SparseRealGridValuesInput{ { IVec{ 0, 4, 0 }, 6.F }, { IVec{ 4, 2, 7 }, 13.76F }, { IVec{ 0, 6, 7 }, 3.6F }, { IVec{ 3, 2, 8 }, 0.61F }, { IVec{ 5, 4, 3 }, 2.1F }, { IVec{ 2, 5, 10 }, 3.6F }, { IVec{ 5, 3, 6 }, 2.1F }, { IVec{ 6, 6, 6 }, 6.1F }, } }; //! Input forces for reduction std::vector<RVec> const c_sampleForcesFull{ RVec{ 0.02F, 0.87F, 0.95F }, RVec{ 0.66F, 0.67F, 0.38F }, RVec{ 0.45F, 0.04F, 0.94F }, RVec{ 0.54F, 0.76F, 0.58F }, RVec{ 0.83F, 0.31F, 0.73F }, RVec{ 0.71F, 0.06F, 0.35F }, RVec{ 0.32F, 0.35F, 0.61F }, RVec{ 0.27F, 0.98F, 0.83F }, RVec{ 0.11F, 0.3F, 0.42F }, RVec{ 0.95F, 0.69F, 0.58F }, RVec{ 0.29F, 0.1F, 0.68F }, RVec{ 0.94F, 0.62F, 0.51F }, RVec{ 0.47F, 0.04F, 0.47F }, RVec{ 0.34F, 0.71F, 0.52F } }; //! PME orders to test std::vector<int> const pmeOrders{ 3, 4, 5 }; //! Atom counts to test std::vector<size_t> const atomCounts{ 1, 2, 13 }; /* Helper structures for test input */ //! A structure for all the spline data which depends in size both on the PME order and atom count struct AtomAndPmeOrderSizedData { //! Spline values SplineParamsVector splineValues; //! Spline derivatives SplineParamsVector splineDerivatives; }; //! A structure for all the input atom data which depends in size on atom count - including a range of spline data for different PME orders struct AtomSizedData { //! Gridline indices GridLineIndicesVector gridLineIndices; //! Charges ChargesVector charges; //! Coordinates CoordinatesVector coordinates; //! Spline data for different orders std::map<int, AtomAndPmeOrderSizedData> splineDataByPmeOrder; }; //! A range of the test input data sets, uniquely identified by the atom count typedef std::map<size_t, AtomSizedData> InputDataByAtomCount; /*! \brief Convenience typedef of the test input parameters - unit cell box, PME interpolation * order, grid dimensions, grid values, overwriting/reducing the input forces, atom count. * * The rest of the atom-related input data - gridline indices, spline theta values, spline dtheta * values, atom charges - is looked up in the inputAtomDataSets_ test fixture variable. */ typedef std::tuple<Matrix3x3, int, IVec, SparseRealGridValuesInput, size_t> GatherInputParameters; //! Test fixture class PmeGatherTest : public ::testing::TestWithParam<GatherInputParameters> { private: //! Storage of all the input atom datasets static InputDataByAtomCount s_inputAtomDataSets_; public: PmeGatherTest() = default; //! Sets the input atom data references and programs once static void SetUpTestSuite() { size_t start = 0; for (auto atomCount : atomCounts) { AtomSizedData atomData; atomData.gridLineIndices = GridLineIndicesVector(c_sampleGridLineIndicesFull).subArray(start, atomCount); atomData.charges = ChargesVector(c_sampleChargesFull).subArray(start, atomCount); start += atomCount; atomData.coordinates.resize(atomCount, RVec{ 1e6, 1e7, -1e8 }); /* The coordinates are intentionally bogus in this test - only the size matters; the gridline indices are fed directly as inputs */ for (auto pmeOrder : pmeOrders) { AtomAndPmeOrderSizedData splineData; const size_t dimSize = atomCount * pmeOrder; for (int dimIndex = 0; dimIndex < DIM; dimIndex++) { splineData.splineValues[dimIndex] = SplineParamsDimVector(c_sampleSplineValuesFull).subArray(dimIndex * dimSize, dimSize); splineData.splineDerivatives[dimIndex] = SplineParamsDimVector(c_sampleSplineDerivativesFull).subArray(dimIndex * dimSize, dimSize); } atomData.splineDataByPmeOrder[pmeOrder] = splineData; } s_inputAtomDataSets_[atomCount] = atomData; } s_pmeTestHardwareContexts = createPmeTestHardwareContextList(); g_allowPmeWithSyclForTesting = true; // We support PmeGather with SYCL } static void TearDownTestSuite() { // Revert the value back. g_allowPmeWithSyclForTesting = false; } //! The test static void runTest() { /* Getting the input */ Matrix3x3 box; int pmeOrder; IVec gridSize; size_t atomCount; SparseRealGridValuesInput nonZeroGridValues; std::tie(box, pmeOrder, gridSize, nonZeroGridValues, atomCount) = GetParam(); auto inputAtomData = s_inputAtomDataSets_[atomCount]; auto inputAtomSplineData = inputAtomData.splineDataByPmeOrder[pmeOrder]; /* Storing the input where it's needed, running the test */ t_inputrec inputRec; inputRec.nkx = gridSize[XX]; inputRec.nky = gridSize[YY]; inputRec.nkz = gridSize[ZZ]; inputRec.pme_order = pmeOrder; inputRec.coulombtype = CoulombInteractionType::Pme; inputRec.epsilon_r = 1.0; TestReferenceData refData; for (const auto& pmeTestHardwareContext : s_pmeTestHardwareContexts) { pmeTestHardwareContext->activate(); CodePath codePath = pmeTestHardwareContext->codePath(); const bool supportedInput = pmeSupportsInputForMode( *getTestHardwareEnvironment()->hwinfo(), &inputRec, codePath); if (!supportedInput) { /* Testing the failure for the unsupported input */ EXPECT_THROW_GMX(pmeInitWrapper(&inputRec, codePath, nullptr, nullptr, nullptr, box), NotImplementedError); continue; } /* Describing the test uniquely */ SCOPED_TRACE( formatString("Testing force gathering on %s for PME grid size %d %d %d" ", order %d, %zu atoms", pmeTestHardwareContext->description().c_str(), gridSize[XX], gridSize[YY], gridSize[ZZ], pmeOrder, atomCount)); PmeSafePointer pmeSafe = pmeInitWrapper(&inputRec, codePath, pmeTestHardwareContext->deviceContext(), pmeTestHardwareContext->deviceStream(), pmeTestHardwareContext->pmeGpuProgram(), box); std::unique_ptr<StatePropagatorDataGpu> stateGpu = (codePath == CodePath::GPU) ? makeStatePropagatorDataGpu(*pmeSafe.get(), pmeTestHardwareContext->deviceContext(), pmeTestHardwareContext->deviceStream()) : nullptr; pmeInitAtoms(pmeSafe.get(), stateGpu.get(), codePath, inputAtomData.coordinates, inputAtomData.charges); /* Setting some more inputs */ pmeSetRealGrid(pmeSafe.get(), codePath, nonZeroGridValues); pmeSetGridLineIndices(pmeSafe.get(), codePath, inputAtomData.gridLineIndices); for (int dimIndex = 0; dimIndex < DIM; dimIndex++) { pmeSetSplineData(pmeSafe.get(), codePath, inputAtomSplineData.splineValues[dimIndex], PmeSplineDataType::Values, dimIndex); pmeSetSplineData(pmeSafe.get(), codePath, inputAtomSplineData.splineDerivatives[dimIndex], PmeSplineDataType::Derivatives, dimIndex); } /* Explicitly copying the sample forces to be able to modify them */ auto inputForcesFull(c_sampleForcesFull); GMX_RELEASE_ASSERT(inputForcesFull.size() >= atomCount, "Bad input forces size"); auto forces = ForcesVector(inputForcesFull).subArray(0, atomCount); /* Running the force gathering itself */ pmePerformGather(pmeSafe.get(), codePath, forces); pmeFinalizeTest(pmeSafe.get(), codePath); /* Check the output forces correctness */ TestReferenceChecker forceChecker(refData.rootChecker()); const auto ulpTolerance = 3 * pmeOrder; forceChecker.setDefaultTolerance(relativeToleranceAsUlp(1.0, ulpTolerance)); forceChecker.checkSequence(forces.begin(), forces.end(), "Forces"); } } static std::vector<std::unique_ptr<PmeTestHardwareContext>> s_pmeTestHardwareContexts; }; std::vector<std::unique_ptr<PmeTestHardwareContext>> PmeGatherTest::s_pmeTestHardwareContexts; // An instance of static atom data InputDataByAtomCount PmeGatherTest::s_inputAtomDataSets_; //! Test for PME force gathering TEST_P(PmeGatherTest, ReproducesOutputs) { EXPECT_NO_THROW_GMX(runTest()); } //! Instantiation of the PME gathering test INSTANTIATE_TEST_SUITE_P(SaneInput, PmeGatherTest, ::testing::Combine(::testing::ValuesIn(c_sampleBoxes), ::testing::ValuesIn(pmeOrders), ::testing::ValuesIn(c_sampleGridSizes), ::testing::ValuesIn(c_sampleGrids), ::testing::ValuesIn(atomCounts))); } // namespace } // namespace test } // namespace gmx <|start_filename|>src/gromacs/utility/tests/message_string_collector.cpp<|end_filename|> /* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2021, by the GROMACS development team, led by * <NAME>, <NAME>, <NAME>, and <NAME>, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS 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. * * GROMACS 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 GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ /*! \internal \file * \brief Tests for MessageStringCollector. * * \author <NAME> <<EMAIL>> * \ingroup module_utility */ #include "gmxpre.h" #include "gromacs/utility/message_string_collector.h" #include <gtest/gtest.h> namespace gmx { namespace { TEST(MessageStringCollectorTest, CanAddAndClearMessagesNoContext) { MessageStringCollector messages; EXPECT_TRUE(messages.isEmpty()); messages.append("Message1"); EXPECT_FALSE(messages.isEmpty()); messages.append("Message2"); EXPECT_FALSE(messages.isEmpty()); messages.clear(); EXPECT_TRUE(messages.isEmpty()); } TEST(MessageStringCollectorTest, CanAddAndClearMessagesWithContext) { MessageStringCollector messages; messages.startContext("Context1"); EXPECT_TRUE(messages.isEmpty()); messages.append("Message1"); EXPECT_FALSE(messages.isEmpty()); messages.append("Message1"); EXPECT_FALSE(messages.isEmpty()); messages.finishContext(); messages.clear(); EXPECT_TRUE(messages.isEmpty()); } TEST(MessageStringCollectorTest, CanAddStringMessages) { std::string context1 = "Context1"; std::string message1 = "Message1"; MessageStringCollector messagesChar; MessageStringCollector messagesString; messagesChar.startContext(context1.c_str()); messagesChar.append(message1.c_str()); messagesChar.finishContext(); messagesString.startContext(context1); messagesString.append(message1); messagesString.finishContext(); EXPECT_EQ(messagesChar.toString(), messagesString.toString()); } TEST(MessageStringCollectorTest, CanAddCharMessagesConditionally) { std::string context1 = "Context1"; std::string message1 = "Message1"; std::string message2 = "Message2"; bool conditional1 = true; bool conditional2 = false; MessageStringCollector messagesDirect; MessageStringCollector messagesConditional; messagesDirect.startContext(context1); if (conditional1) { messagesDirect.append(message1.c_str()); } if (conditional2) { messagesDirect.append(message2.c_str()); } messagesDirect.finishContext(); messagesConditional.startContext(context1); messagesConditional.appendIf(conditional1, message1.c_str()); messagesConditional.appendIf(conditional2, message2.c_str()); messagesConditional.finishContext(); EXPECT_EQ(messagesDirect.toString(), messagesConditional.toString()); } TEST(MessageStringCollectorTest, CanAddStringMessagesConditionally) { std::string context1 = "Context1"; std::string message1 = "Message1"; std::string message2 = "Message2"; bool conditional1 = true; bool conditional2 = false; MessageStringCollector messagesDirect; MessageStringCollector messagesConditional; messagesDirect.startContext(context1); if (conditional1) { messagesDirect.append(message1); } if (conditional2) { messagesDirect.append(message2); } messagesDirect.finishContext(); messagesConditional.startContext(context1); messagesConditional.appendIf(conditional1, message1); messagesConditional.appendIf(conditional2, message2); messagesConditional.finishContext(); EXPECT_EQ(messagesDirect.toString(), messagesConditional.toString()); } } // namespace } // namespace gmx <|start_filename|>src/gromacs/mdlib/calc_verletbuf.h<|end_filename|> /* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2012,2013,2014,2015,2017 by the GROMACS development team. * Copyright (c) 2018,2019,2020, by the GROMACS development team, led by * <NAME>, <NAME>, <NAME>, and <NAME>, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS 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. * * GROMACS 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 GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ #ifndef GMX_MDLIB_CALC_VERLETBUF_H #define GMX_MDLIB_CALC_VERLETBUF_H #include "gromacs/utility/basedefinitions.h" #include "gromacs/utility/real.h" struct gmx_mtop_t; struct t_inputrec; namespace gmx { template<typename> class ArrayRef; class RangePartitioning; } // namespace gmx namespace Nbnxm { enum class KernelType; } // namespace Nbnxm struct VerletbufListSetup { int cluster_size_i; /* Cluster pair-list i-cluster size atom count */ int cluster_size_j; /* Cluster pair-list j-cluster size atom count */ }; /* Add a 5% and 10% rlist buffer for simulations without dynamics (EM, NM, ...) * and NVE simulations with zero initial temperature, respectively. * 10% should be enough for any NVE simulation with PME and nstlist=10, * for other settings it might not be enough, but then it's difficult * to come up with any reasonable (not crazily expensive) value * and grompp will notify the user when using the 10% buffer. */ static const real verlet_buffer_ratio_nodynamics = 0.05; static const real verlet_buffer_ratio_NVE_T0 = 0.10; /* Returns the pair-list setup for the given nbnxn kernel type. */ VerletbufListSetup verletbufGetListSetup(Nbnxm::KernelType nbnxnKernelType); /* Enum for choosing the list type for verletbufGetSafeListSetup() */ enum class ListSetupType { CpuNoSimd, /* CPU Plain-C 4x4 list */ CpuSimdWhenSupported, /* CPU 4xN list, where N=4 when the binary doesn't support SIMD or the smallest N supported by SIMD in this binary */ Gpu /* GPU (8x2x)8x4 list */ }; /* Returns the pair-list setup assumed for the current Gromacs configuration. * The setup with smallest cluster sizes is returned, such that the Verlet * buffer size estimated with this setup will be conservative. */ VerletbufListSetup verletbufGetSafeListSetup(ListSetupType listType); /* Returns the non-bonded pair-list radius including computed buffer * * Calculate the non-bonded pair-list buffer size for the Verlet list * based on the particle masses, temperature, LJ types, charges * and constraints as well as the non-bonded force behavior at the cut-off. * The pair list update frequency and the list lifetime, which is nstlist-1 * for normal pair-list buffering, are passed separately, as in some cases * we want an estimate for different values than the ones set in the inputrec. * If referenceTemperature < 0, the maximum coupling temperature will be used. * The target is a maximum average energy jump per atom of * inputrec.verletbuf_tol*nstlist*inputrec.delta_t over the lifetime of the list. * * \note For non-linear virtual sites it can be problematic to determine their * contribution to the drift exaclty, so we approximate. * * \param[in] mtop The system topology * \param[in] boxVolume The volume of the unit cell * \param[in] inputrec The input record * \param[in] nstlist The pair list update frequency in steps (is not taken from \p inputrec) * \param[in] listLifetime The lifetime of the pair-list, usually nstlist-1, but could be different * for dynamic pruning \param[in] referenceTemperature The reference temperature for the ensemble * \param[in] listSetup The pair-list setup * \returns The computed pair-list radius including buffer */ real calcVerletBufferSize(const gmx_mtop_t& mtop, real boxVolume, const t_inputrec& inputrec, int nstlist, int listLifetime, real referenceTemperature, const VerletbufListSetup& listSetup); /* Convenience type */ using PartitioningPerMoltype = gmx::ArrayRef<const gmx::RangePartitioning>; /* Determines the mininum cell size based on atom displacement * * The value returned is the minimum size for which the chance that * an atom or update group crosses to non nearest-neighbor cells * is <= chanceRequested within ir.nstlist steps. * Update groups are used when !updateGrouping.empty(). * Without T-coupling, SD or BD, we can not estimate atom displacements * and fall back to the, crude, estimate of using the pairlist buffer size. * * Note: Like the Verlet buffer estimate, this estimate is based on * non-interacting atoms and constrained atom-pairs. Therefore for * any system that is not an ideal gas, this will be an overestimate. * * Note: This size increases (very slowly) with system size. */ real minCellSizeForAtomDisplacement(const gmx_mtop_t& mtop, const t_inputrec& ir, PartitioningPerMoltype updateGrouping, real chanceRequested); /* Struct for unique atom type for calculating the energy drift. * The atom displacement depends on mass and constraints. * The energy jump for given distance depend on LJ type and q. */ struct atom_nonbonded_kinetic_prop_t { real mass = 0; /* mass */ int type = 0; /* type (used for LJ parameters) */ real q = 0; /* charge */ bool bConstr = false; /* constrained, if TRUE, use #DOF=2 iso 3 */ real con_mass = 0; /* mass of heaviest atom connected by constraints */ real con_len = 0; /* constraint length to the heaviest atom */ }; /* This function computes two components of the estimate of the variance * in the displacement of one atom in a system of two constrained atoms. * Returns in sigma2_2d the variance due to rotation of the constrained * atom around the atom to which it constrained. * Returns in sigma2_3d the variance due to displacement of the COM * of the whole system of the two constrained atoms. * * Only exposed here for testing purposes. */ void constrained_atom_sigma2(real kT_fac, const atom_nonbonded_kinetic_prop_t* prop, real* sigma2_2d, real* sigma2_3d); #endif <|start_filename|>src/gromacs/gmxlib/nonbonded/nb_free_energy.cpp<|end_filename|> /* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 1991-2000, University of Groningen, The Netherlands. * Copyright (c) 2001-2004, The GROMACS development team. * Copyright (c) 2013,2014,2015,2016,2017 by the GROMACS development team. * Copyright (c) 2018,2019,2020,2021, by the GROMACS development team, led by * <NAME>, <NAME>, <NAME>, and <NAME>, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS 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. * * GROMACS 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 GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ #include "gmxpre.h" #include "nb_free_energy.h" #include "config.h" #include <cmath> #include <set> #include <algorithm> #include "gromacs/gmxlib/nrnb.h" #include "gromacs/gmxlib/nonbonded/nonbonded.h" #include "gromacs/math/arrayrefwithpadding.h" #include "gromacs/math/functions.h" #include "gromacs/math/vec.h" #include "gromacs/mdtypes/forceoutput.h" #include "gromacs/mdtypes/forcerec.h" #include "gromacs/mdtypes/interaction_const.h" #include "gromacs/mdtypes/md_enums.h" #include "gromacs/mdtypes/mdatom.h" #include "gromacs/mdtypes/nblist.h" #include "gromacs/pbcutil/ishift.h" #include "gromacs/simd/simd.h" #include "gromacs/simd/simd_math.h" #include "gromacs/utility/fatalerror.h" #include "gromacs/utility/arrayref.h" #include "nb_softcore.h" //! Scalar (non-SIMD) data types. struct ScalarDataTypes { using RealType = real; //!< The data type to use as real. using IntType = int; //!< The data type to use as int. using BoolType = bool; //!< The data type to use as bool for real value comparison. static constexpr int simdRealWidth = 1; //!< The width of the RealType. static constexpr int simdIntWidth = 1; //!< The width of the IntType. }; #if GMX_SIMD_HAVE_REAL && GMX_SIMD_HAVE_INT32_ARITHMETICS //! SIMD data types. struct SimdDataTypes { using RealType = gmx::SimdReal; //!< The data type to use as real. using IntType = gmx::SimdInt32; //!< The data type to use as int. using BoolType = gmx::SimdBool; //!< The data type to use as bool for real value comparison. static constexpr int simdRealWidth = GMX_SIMD_REAL_WIDTH; //!< The width of the RealType. # if GMX_SIMD_HAVE_DOUBLE && GMX_DOUBLE static constexpr int simdIntWidth = GMX_SIMD_DINT32_WIDTH; //!< The width of the IntType. # else static constexpr int simdIntWidth = GMX_SIMD_FINT32_WIDTH; //!< The width of the IntType. # endif }; #endif /*! \brief Lower limit for square interaction distances in nonbonded kernels. * * This is a mimimum on r^2 to avoid overflows when computing r^6. * This will only affect results for soft-cored interaction at distances smaller * than 1e-6 and will limit extremely high foreign energies for overlapping atoms. * Note that we could use a somewhat smaller minimum in double precision. * But because invsqrt in double precision can use single precision, this number * can not be much smaller, we use the same number for simplicity. */ constexpr real c_minDistanceSquared = 1.0e-12_real; /*! \brief Higher limit for r^-6 used for Lennard-Jones interactions * * This is needed to avoid overflow of LJ energy and force terms for excluded * atoms and foreign energies of hard-core states of overlapping atoms. * Note that in single precision this value leaves room for C12 coefficients up to 3.4e8. */ constexpr real c_maxRInvSix = 1.0e15_real; template<bool computeForces, class RealType> static inline void pmeCoulombCorrectionVF(const RealType rSq, const real beta, RealType* pot, RealType gmx_unused* force) { const RealType brsq = rSq * beta * beta; if constexpr (computeForces) { *force = -brsq * beta * gmx::pmeForceCorrection(brsq); } *pot = beta * gmx::pmePotentialCorrection(brsq); } template<bool computeForces, class RealType, class BoolType> static inline void pmeLJCorrectionVF(const RealType rInv, const RealType rSq, const real ewaldLJCoeffSq, const real ewaldLJCoeffSixDivSix, RealType* pot, RealType gmx_unused* force, const BoolType mask, const BoolType bIiEqJnr) { // We mask rInv to get zero force and potential for masked out pair interactions const RealType rInvSq = rInv * rInv; const RealType rInvSix = rInvSq * rInvSq * rInvSq; // Mask rSq to avoid underflow in exp() const RealType coeffSqRSq = ewaldLJCoeffSq * gmx::selectByMask(rSq, mask); const RealType expNegCoeffSqRSq = gmx::exp(-coeffSqRSq); const RealType poly = 1.0_real + coeffSqRSq + 0.5_real * coeffSqRSq * coeffSqRSq; if constexpr (computeForces) { *force = rInvSix - expNegCoeffSqRSq * (rInvSix * poly + ewaldLJCoeffSixDivSix); *force = *force * rInvSq; } // The self interaction is the limit for r -> 0 which we need to compute separately *pot = gmx::blend( rInvSix * (1.0_real - expNegCoeffSqRSq * poly), 0.5_real * ewaldLJCoeffSixDivSix, bIiEqJnr); } //! Computes r^(1/6) and 1/r^(1/6) template<class RealType> static inline void sixthRoot(const RealType r, RealType* sixthRoot, RealType* invSixthRoot) { RealType cbrtRes = gmx::cbrt(r); *invSixthRoot = gmx::invsqrt(cbrtRes); *sixthRoot = gmx::inv(*invSixthRoot); } template<class RealType> static inline RealType calculateRinv6(const RealType rInvV) { RealType rInv6 = rInvV * rInvV; return (rInv6 * rInv6 * rInv6); } template<class RealType> static inline RealType calculateVdw6(const RealType c6, const RealType rInv6) { return (c6 * rInv6); } template<class RealType> static inline RealType calculateVdw12(const RealType c12, const RealType rInv6) { return (c12 * rInv6 * rInv6); } /* reaction-field electrostatics */ template<class RealType> static inline RealType reactionFieldScalarForce(const RealType qq, const RealType rInv, const RealType r, const real krf, const real two) { return (qq * (rInv - two * krf * r * r)); } template<class RealType> static inline RealType reactionFieldPotential(const RealType qq, const RealType rInv, const RealType r, const real krf, const real potentialShift) { return (qq * (rInv + krf * r * r - potentialShift)); } /* Ewald electrostatics */ template<class RealType> static inline RealType ewaldScalarForce(const RealType coulomb, const RealType rInv) { return (coulomb * rInv); } template<class RealType> static inline RealType ewaldPotential(const RealType coulomb, const RealType rInv, const real potentialShift) { return (coulomb * (rInv - potentialShift)); } /* cutoff LJ */ template<class RealType> static inline RealType lennardJonesScalarForce(const RealType v6, const RealType v12) { return (v12 - v6); } template<class RealType> static inline RealType lennardJonesPotential(const RealType v6, const RealType v12, const RealType c6, const RealType c12, const real repulsionShift, const real dispersionShift, const real oneSixth, const real oneTwelfth) { return ((v12 + c12 * repulsionShift) * oneTwelfth - (v6 + c6 * dispersionShift) * oneSixth); } /* Ewald LJ */ template<class RealType> static inline RealType ewaldLennardJonesGridSubtract(const RealType c6grid, const real potentialShift, const real oneSixth) { return (c6grid * potentialShift * oneSixth); } /* LJ Potential switch */ template<class RealType, class BoolType> static inline RealType potSwitchScalarForceMod(const RealType fScalarInp, const RealType potential, const RealType sw, const RealType r, const RealType dsw, const BoolType mask) { /* The mask should select on rV < rVdw */ return (gmx::selectByMask(fScalarInp * sw - r * potential * dsw, mask)); } template<class RealType, class BoolType> static inline RealType potSwitchPotentialMod(const RealType potentialInp, const RealType sw, const BoolType mask) { /* The mask should select on rV < rVdw */ return (gmx::selectByMask(potentialInp * sw, mask)); } //! Templated free-energy non-bonded kernel template<typename DataTypes, KernelSoftcoreType softcoreType, bool scLambdasOrAlphasDiffer, bool vdwInteractionTypeIsEwald, bool elecInteractionTypeIsEwald, bool vdwModifierIsPotSwitch, bool computeForces> static void nb_free_energy_kernel(const t_nblist& nlist, const gmx::ArrayRefWithPadding<const gmx::RVec>& coords, const int ntype, const real rlist, const interaction_const_t& ic, gmx::ArrayRef<const gmx::RVec> shiftvec, gmx::ArrayRef<const real> nbfp, gmx::ArrayRef<const real> gmx_unused nbfp_grid, gmx::ArrayRef<const real> chargeA, gmx::ArrayRef<const real> chargeB, gmx::ArrayRef<const int> typeA, gmx::ArrayRef<const int> typeB, int flags, gmx::ArrayRef<const real> lambda, t_nrnb* gmx_restrict nrnb, gmx::ArrayRefWithPadding<gmx::RVec> threadForceBuffer, rvec gmx_unused* threadForceShiftBuffer, gmx::ArrayRef<real> threadVc, gmx::ArrayRef<real> threadVv, gmx::ArrayRef<real> threadDvdl) { #define STATE_A 0 #define STATE_B 1 #define NSTATES 2 using RealType = typename DataTypes::RealType; using IntType = typename DataTypes::IntType; using BoolType = typename DataTypes::BoolType; constexpr real oneTwelfth = 1.0_real / 12.0_real; constexpr real oneSixth = 1.0_real / 6.0_real; constexpr real zero = 0.0_real; constexpr real half = 0.5_real; constexpr real one = 1.0_real; constexpr real two = 2.0_real; constexpr real six = 6.0_real; // Extract pair list data const int nri = nlist.nri; gmx::ArrayRef<const int> iinr = nlist.iinr; gmx::ArrayRef<const int> jindex = nlist.jindex; gmx::ArrayRef<const int> jjnr = nlist.jjnr; gmx::ArrayRef<const int> shift = nlist.shift; gmx::ArrayRef<const int> gid = nlist.gid; const real lambda_coul = lambda[static_cast<int>(FreeEnergyPerturbationCouplingType::Coul)]; const real lambda_vdw = lambda[static_cast<int>(FreeEnergyPerturbationCouplingType::Vdw)]; // Extract softcore parameters const auto& scParams = *ic.softCoreParameters; const real lam_power = scParams.lambdaPower; const real gmx_unused alpha_coul = scParams.alphaCoulomb; const real gmx_unused alpha_vdw = scParams.alphaVdw; const real gmx_unused sigma6_def = scParams.sigma6WithInvalidSigma; const real gmx_unused sigma6_min = scParams.sigma6Minimum; const real gmx_unused gapsysScaleLinpointCoul = scParams.gapsysScaleLinpointCoul; const real gmx_unused gapsysScaleLinpointVdW = scParams.gapsysScaleLinpointVdW; const real gmx_unused gapsysSigma6VdW = scParams.gapsysSigma6VdW; const bool gmx_unused doShiftForces = ((flags & GMX_NONBONDED_DO_SHIFTFORCE) != 0); const bool doPotential = ((flags & GMX_NONBONDED_DO_POTENTIAL) != 0); // Extract data from interaction_const_t const real facel = ic.epsfac; const real rCoulomb = ic.rcoulomb; const real krf = ic.reactionFieldCoefficient; const real crf = ic.reactionFieldShift; const real gmx_unused shLjEwald = ic.sh_lj_ewald; const real rVdw = ic.rvdw; const real dispersionShift = ic.dispersion_shift.cpot; const real repulsionShift = ic.repulsion_shift.cpot; const real ewaldBeta = ic.ewaldcoeff_q; real gmx_unused ewaldLJCoeffSq; real gmx_unused ewaldLJCoeffSixDivSix; if constexpr (vdwInteractionTypeIsEwald) { ewaldLJCoeffSq = ic.ewaldcoeff_lj * ic.ewaldcoeff_lj; ewaldLJCoeffSixDivSix = ewaldLJCoeffSq * ewaldLJCoeffSq * ewaldLJCoeffSq / six; } // Note that the nbnxm kernels do not support Coulomb potential switching at all GMX_ASSERT(ic.coulomb_modifier != InteractionModifiers::PotSwitch, "Potential switching is not supported for Coulomb with FEP"); const real rVdwSwitch = ic.rvdw_switch; real gmx_unused vdw_swV3, vdw_swV4, vdw_swV5, vdw_swF2, vdw_swF3, vdw_swF4; if constexpr (vdwModifierIsPotSwitch) { const real d = rVdw - rVdwSwitch; vdw_swV3 = -10.0_real / (d * d * d); vdw_swV4 = 15.0_real / (d * d * d * d); vdw_swV5 = -6.0_real / (d * d * d * d * d); vdw_swF2 = -30.0_real / (d * d * d); vdw_swF3 = 60.0_real / (d * d * d * d); vdw_swF4 = -30.0_real / (d * d * d * d * d); } else { /* Avoid warnings from stupid compilers (looking at you, Clang!) */ vdw_swV3 = vdw_swV4 = vdw_swV5 = vdw_swF2 = vdw_swF3 = vdw_swF4 = zero; } NbkernelElecType icoul; if (ic.eeltype == CoulombInteractionType::Cut || EEL_RF(ic.eeltype)) { icoul = NbkernelElecType::ReactionField; } else { icoul = NbkernelElecType::None; } real rcutoff_max2 = std::max(ic.rcoulomb, ic.rvdw); rcutoff_max2 = rcutoff_max2 * rcutoff_max2; const real gmx_unused rCutoffCoul = ic.rcoulomb; real gmx_unused sh_ewald = 0; if constexpr (elecInteractionTypeIsEwald || vdwInteractionTypeIsEwald) { sh_ewald = ic.sh_ewald; } /* For Ewald/PME interactions we cannot easily apply the soft-core component to * reciprocal space. When we use non-switched Ewald interactions, we * assume the soft-coring does not significantly affect the grid contribution * and apply the soft-core only to the full 1/r (- shift) pair contribution. * * However, we cannot use this approach for switch-modified since we would then * effectively end up evaluating a significantly different interaction here compared to the * normal (non-free-energy) kernels, either by applying a cutoff at a different * position than what the user requested, or by switching different * things (1/r rather than short-range Ewald). For these settings, we just * use the traditional short-range Ewald interaction in that case. */ GMX_RELEASE_ASSERT(!(vdwInteractionTypeIsEwald && vdwModifierIsPotSwitch), "Can not apply soft-core to switched Ewald potentials"); const RealType minDistanceSquared(c_minDistanceSquared); const RealType maxRInvSix(c_maxRInvSix); const RealType gmx_unused floatMin(GMX_FLOAT_MIN); RealType dvdlCoul(zero); RealType dvdlVdw(zero); /* Lambda factor for state A, 1-lambda*/ real LFC[NSTATES], LFV[NSTATES]; LFC[STATE_A] = one - lambda_coul; LFV[STATE_A] = one - lambda_vdw; /* Lambda factor for state B, lambda*/ LFC[STATE_B] = lambda_coul; LFV[STATE_B] = lambda_vdw; /*derivative of the lambda factor for state A and B */ real DLF[NSTATES]; DLF[STATE_A] = -one; DLF[STATE_B] = one; real gmx_unused lFacCoul[NSTATES], dlFacCoul[NSTATES], lFacVdw[NSTATES], dlFacVdw[NSTATES]; constexpr real sc_r_power = six; for (int i = 0; i < NSTATES; i++) { lFacCoul[i] = (lam_power == 2 ? (1 - LFC[i]) * (1 - LFC[i]) : (1 - LFC[i])); dlFacCoul[i] = DLF[i] * lam_power / sc_r_power * (lam_power == 2 ? (1 - LFC[i]) : 1); lFacVdw[i] = (lam_power == 2 ? (1 - LFV[i]) * (1 - LFV[i]) : (1 - LFV[i])); dlFacVdw[i] = DLF[i] * lam_power / sc_r_power * (lam_power == 2 ? (1 - LFV[i]) : 1); } // We need pointers to real for SIMD access const real* gmx_restrict x = coords.paddedConstArrayRef().data()[0]; real* gmx_restrict forceRealPtr; if constexpr (computeForces) { GMX_ASSERT(nri == 0 || !threadForceBuffer.empty(), "need a valid threadForceBuffer"); forceRealPtr = threadForceBuffer.paddedArrayRef().data()[0]; if (doShiftForces) { GMX_ASSERT(threadForceShiftBuffer != nullptr, "need a valid threadForceShiftBuffer"); } } const real rlistSquared = gmx::square(rlist); bool haveExcludedPairsBeyondRlist = false; for (int n = 0; n < nri; n++) { bool havePairsWithinCutoff = false; const int is = shift[n]; const real shX = shiftvec[is][XX]; const real shY = shiftvec[is][YY]; const real shZ = shiftvec[is][ZZ]; const int nj0 = jindex[n]; const int nj1 = jindex[n + 1]; const int ii = iinr[n]; const int ii3 = 3 * ii; const real ix = shX + x[ii3 + 0]; const real iy = shY + x[ii3 + 1]; const real iz = shZ + x[ii3 + 2]; const real iqA = facel * chargeA[ii]; const real iqB = facel * chargeB[ii]; const int ntiA = ntype * typeA[ii]; const int ntiB = ntype * typeB[ii]; RealType vCTot(0); RealType vVTot(0); RealType fIX(0); RealType fIY(0); RealType fIZ(0); #if GMX_SIMD_HAVE_REAL alignas(GMX_SIMD_ALIGNMENT) int preloadIi[DataTypes::simdRealWidth]; alignas(GMX_SIMD_ALIGNMENT) int gmx_unused preloadIs[DataTypes::simdRealWidth]; #else int preloadIi[DataTypes::simdRealWidth]; int gmx_unused preloadIs[DataTypes::simdRealWidth]; #endif for (int s = 0; s < DataTypes::simdRealWidth; s++) { preloadIi[s] = ii; preloadIs[s] = shift[n]; } IntType ii_s = gmx::load<IntType>(preloadIi); for (int k = nj0; k < nj1; k += DataTypes::simdRealWidth) { RealType r, rInv; #if GMX_SIMD_HAVE_REAL alignas(GMX_SIMD_ALIGNMENT) real preloadPairIsValid[DataTypes::simdRealWidth]; alignas(GMX_SIMD_ALIGNMENT) real preloadPairIncluded[DataTypes::simdRealWidth]; alignas(GMX_SIMD_ALIGNMENT) int32_t preloadJnr[DataTypes::simdRealWidth]; alignas(GMX_SIMD_ALIGNMENT) int32_t typeIndices[NSTATES][DataTypes::simdRealWidth]; alignas(GMX_SIMD_ALIGNMENT) real preloadQq[NSTATES][DataTypes::simdRealWidth]; alignas(GMX_SIMD_ALIGNMENT) real gmx_unused preloadSigma6[NSTATES][DataTypes::simdRealWidth]; alignas(GMX_SIMD_ALIGNMENT) real gmx_unused preloadAlphaVdwEff[DataTypes::simdRealWidth]; alignas(GMX_SIMD_ALIGNMENT) real gmx_unused preloadAlphaCoulEff[DataTypes::simdRealWidth]; alignas(GMX_SIMD_ALIGNMENT) real gmx_unused preloadGapsysScaleLinpointVdW[DataTypes::simdRealWidth]; alignas(GMX_SIMD_ALIGNMENT) real gmx_unused preloadGapsysScaleLinpointCoul[DataTypes::simdRealWidth]; alignas(GMX_SIMD_ALIGNMENT) real gmx_unused preloadGapsysSigma6VdW[NSTATES][DataTypes::simdRealWidth]; alignas(GMX_SIMD_ALIGNMENT) real preloadLjPmeC6Grid[NSTATES][DataTypes::simdRealWidth]; #else real preloadPairIsValid[DataTypes::simdRealWidth]; real preloadPairIncluded[DataTypes::simdRealWidth]; int preloadJnr[DataTypes::simdRealWidth]; int typeIndices[NSTATES][DataTypes::simdRealWidth]; real preloadQq[NSTATES][DataTypes::simdRealWidth]; real gmx_unused preloadSigma6[NSTATES][DataTypes::simdRealWidth]; real gmx_unused preloadAlphaVdwEff[DataTypes::simdRealWidth]; real gmx_unused preloadAlphaCoulEff[DataTypes::simdRealWidth]; real gmx_unused preloadGapsysScaleLinpointVdW[DataTypes::simdRealWidth]; real gmx_unused preloadGapsysScaleLinpointCoul[DataTypes::simdRealWidth]; real gmx_unused preloadGapsysSigma6VdW[NSTATES][DataTypes::simdRealWidth]; real preloadLjPmeC6Grid[NSTATES][DataTypes::simdRealWidth]; #endif for (int s = 0; s < DataTypes::simdRealWidth; s++) { if (k + s < nj1) { preloadPairIsValid[s] = true; /* Check if this pair on the exclusions list.*/ preloadPairIncluded[s] = (nlist.excl_fep.empty() || nlist.excl_fep[k + s]); const int jnr = jjnr[k + s]; preloadJnr[s] = jnr; typeIndices[STATE_A][s] = ntiA + typeA[jnr]; typeIndices[STATE_B][s] = ntiB + typeB[jnr]; preloadQq[STATE_A][s] = iqA * chargeA[jnr]; preloadQq[STATE_B][s] = iqB * chargeB[jnr]; for (int i = 0; i < NSTATES; i++) { if constexpr (vdwInteractionTypeIsEwald) { preloadLjPmeC6Grid[i][s] = nbfp_grid[2 * typeIndices[i][s]]; } else { preloadLjPmeC6Grid[i][s] = 0; } if constexpr (softcoreType == KernelSoftcoreType::Beutler) { const real c6 = nbfp[2 * typeIndices[i][s]]; const real c12 = nbfp[2 * typeIndices[i][s] + 1]; if (c6 > 0 && c12 > 0) { /* c12 is stored scaled with 12.0 and c6 is scaled with 6.0 - correct for this */ preloadSigma6[i][s] = 0.5_real * c12 / c6; if (preloadSigma6[i][s] < sigma6_min) /* for disappearing coul and vdw with soft core at the same time */ { preloadSigma6[i][s] = sigma6_min; } } else { preloadSigma6[i][s] = sigma6_def; } } if constexpr (softcoreType == KernelSoftcoreType::Gapsys) { const real c6 = nbfp[2 * typeIndices[i][s]]; const real c12 = nbfp[2 * typeIndices[i][s] + 1]; if (c6 > 0 && c12 > 0) { /* c12 is stored scaled with 12.0 and c6 is scaled with 6.0 - correct for this */ preloadGapsysSigma6VdW[i][s] = 0.5_real * c12 / c6; } else { preloadGapsysSigma6VdW[i][s] = gapsysSigma6VdW; } } } if constexpr (softcoreType == KernelSoftcoreType::Beutler) { /* only use softcore if one of the states has a zero endstate - softcore is for avoiding infinities!*/ const real c12A = nbfp[2 * typeIndices[STATE_A][s] + 1]; const real c12B = nbfp[2 * typeIndices[STATE_B][s] + 1]; if (c12A > 0 && c12B > 0) { preloadAlphaVdwEff[s] = 0; preloadAlphaCoulEff[s] = 0; } else { preloadAlphaVdwEff[s] = alpha_vdw; preloadAlphaCoulEff[s] = alpha_coul; } } if constexpr (softcoreType == KernelSoftcoreType::Gapsys) { /* only use softcore if one of the states has a zero endstate - softcore is for avoiding infinities!*/ const real c12A = nbfp[2 * typeIndices[STATE_A][s] + 1]; const real c12B = nbfp[2 * typeIndices[STATE_B][s] + 1]; if (c12A > 0 && c12B > 0) { preloadGapsysScaleLinpointVdW[s] = 0; preloadGapsysScaleLinpointCoul[s] = 0; } else { preloadGapsysScaleLinpointVdW[s] = gapsysScaleLinpointVdW; preloadGapsysScaleLinpointCoul[s] = gapsysScaleLinpointCoul; } } } else { preloadJnr[s] = jjnr[k]; preloadPairIsValid[s] = false; preloadPairIncluded[s] = false; preloadAlphaVdwEff[s] = 0; preloadAlphaCoulEff[s] = 0; preloadGapsysScaleLinpointVdW[s] = 0; preloadGapsysScaleLinpointCoul[s] = 0; for (int i = 0; i < NSTATES; i++) { typeIndices[STATE_A][s] = ntiA + typeA[jjnr[k]]; typeIndices[STATE_B][s] = ntiB + typeB[jjnr[k]]; preloadLjPmeC6Grid[i][s] = 0; preloadQq[i][s] = 0; preloadSigma6[i][s] = 0; preloadGapsysSigma6VdW[i][s] = 0; } } } RealType jx, jy, jz; gmx::gatherLoadUTranspose<3>(reinterpret_cast<const real*>(x), preloadJnr, &jx, &jy, &jz); const RealType pairIsValid = gmx::load<RealType>(preloadPairIsValid); const RealType pairIncluded = gmx::load<RealType>(preloadPairIncluded); const BoolType bPairIncluded = (pairIncluded != zero); const BoolType bPairExcluded = (pairIncluded == zero && pairIsValid != zero); const RealType dX = ix - jx; const RealType dY = iy - jy; const RealType dZ = iz - jz; RealType rSq = dX * dX + dY * dY + dZ * dZ; BoolType withinCutoffMask = (rSq < rcutoff_max2); if (!gmx::anyTrue(withinCutoffMask || bPairExcluded)) { /* We save significant time by skipping all code below. * Note that with soft-core interactions, the actual cut-off * check might be different. But since the soft-core distance * is always larger than r, checking on r here is safe. * Exclusions outside the cutoff can not be skipped as * when using Ewald: the reciprocal-space * Ewald component still needs to be subtracted. */ continue; } else { havePairsWithinCutoff = true; } if (gmx::anyTrue(rlistSquared < rSq && bPairExcluded)) { haveExcludedPairsBeyondRlist = true; } const IntType jnr_s = gmx::load<IntType>(preloadJnr); const BoolType bIiEqJnr = gmx::cvtIB2B(ii_s == jnr_s); RealType c6[NSTATES]; RealType c12[NSTATES]; RealType gmx_unused sigma6[NSTATES]; RealType qq[NSTATES]; RealType gmx_unused ljPmeC6Grid[NSTATES]; RealType gmx_unused alphaVdwEff; RealType gmx_unused alphaCoulEff; RealType gmx_unused gapsysScaleLinpointVdWEff; RealType gmx_unused gapsysScaleLinpointCoulEff; RealType gmx_unused gapsysSigma6VdWEff[NSTATES]; for (int i = 0; i < NSTATES; i++) { gmx::gatherLoadTranspose<2>(nbfp.data(), typeIndices[i], &c6[i], &c12[i]); qq[i] = gmx::load<RealType>(preloadQq[i]); ljPmeC6Grid[i] = gmx::load<RealType>(preloadLjPmeC6Grid[i]); if constexpr (softcoreType == KernelSoftcoreType::Beutler) { sigma6[i] = gmx::load<RealType>(preloadSigma6[i]); } if constexpr (softcoreType == KernelSoftcoreType::Gapsys) { gapsysSigma6VdWEff[i] = gmx::load<RealType>(preloadGapsysSigma6VdW[i]); } } if constexpr (softcoreType == KernelSoftcoreType::Beutler) { alphaVdwEff = gmx::load<RealType>(preloadAlphaVdwEff); alphaCoulEff = gmx::load<RealType>(preloadAlphaCoulEff); } if constexpr (softcoreType == KernelSoftcoreType::Gapsys) { gapsysScaleLinpointVdWEff = gmx::load<RealType>(preloadGapsysScaleLinpointVdW); gapsysScaleLinpointCoulEff = gmx::load<RealType>(preloadGapsysScaleLinpointCoul); } // Avoid overflow of r^-12 at distances near zero rSq = gmx::max(rSq, minDistanceSquared); rInv = gmx::invsqrt(rSq); r = rSq * rInv; RealType gmx_unused rp, rpm2; if constexpr (softcoreType == KernelSoftcoreType::Beutler) { rpm2 = rSq * rSq; /* r4 */ rp = rpm2 * rSq; /* r6 */ } else { /* The soft-core power p will not affect the results * with not using soft-core, so we use power of 0 which gives * the simplest math and cheapest code. */ rpm2 = rInv * rInv; rp = one; } RealType fScal(0); /* The following block is masked to only calculate values having bPairIncluded. If * bPairIncluded is true then withinCutoffMask must also be true. */ if (gmx::anyTrue(withinCutoffMask && bPairIncluded)) { RealType gmx_unused fScalC[NSTATES], fScalV[NSTATES]; RealType vCoul[NSTATES], vVdw[NSTATES]; for (int i = 0; i < NSTATES; i++) { fScalC[i] = zero; fScalV[i] = zero; vCoul[i] = zero; vVdw[i] = zero; RealType gmx_unused rInvC, rInvV, rC, rV, rPInvC, rPInvV; /* The following block is masked to require (qq[i] != 0 || c6[i] != 0 || c12[i] * != 0) in addition to bPairIncluded, which in turn requires withinCutoffMask. */ BoolType nonZeroState = ((qq[i] != zero || c6[i] != zero || c12[i] != zero) && bPairIncluded && withinCutoffMask); if (gmx::anyTrue(nonZeroState)) { if constexpr (softcoreType == KernelSoftcoreType::Beutler) { RealType divisor = (alphaCoulEff * lFacCoul[i] * sigma6[i] + rp); rPInvC = gmx::inv(divisor); sixthRoot(rPInvC, &rInvC, &rC); if constexpr (scLambdasOrAlphasDiffer) { RealType divisor = (alphaVdwEff * lFacVdw[i] * sigma6[i] + rp); rPInvV = gmx::inv(divisor); sixthRoot(rPInvV, &rInvV, &rV); } else { /* We can avoid one expensive pow and one / operation */ rPInvV = rPInvC; rInvV = rInvC; rV = rC; } } else { rPInvC = one; rInvC = rInv; rC = r; rPInvV = one; rInvV = rInv; rV = r; } /* Only process the coulomb interactions if we either * include all entries in the list (no cutoff * used in the kernel), or if we are within the cutoff. */ BoolType computeElecInteraction; if constexpr (elecInteractionTypeIsEwald) { computeElecInteraction = (r < rCoulomb && qq[i] != zero && bPairIncluded); } else { computeElecInteraction = (rC < rCoulomb && qq[i] != zero && bPairIncluded); } if (gmx::anyTrue(computeElecInteraction)) { if constexpr (elecInteractionTypeIsEwald) { vCoul[i] = ewaldPotential(qq[i], rInvC, sh_ewald); if constexpr (computeForces) { fScalC[i] = ewaldScalarForce(qq[i], rInvC); } if constexpr (softcoreType == KernelSoftcoreType::Gapsys) { ewaldQuadraticPotential<computeForces>(qq[i], facel, rC, rCutoffCoul, LFC[i], DLF[i], gapsysScaleLinpointCoulEff, sh_ewald, &fScalC[i], &vCoul[i], &dvdlCoul, computeElecInteraction); } } else { vCoul[i] = reactionFieldPotential(qq[i], rInvC, rC, krf, crf); if constexpr (computeForces) { fScalC[i] = reactionFieldScalarForce(qq[i], rInvC, rC, krf, two); } if constexpr (softcoreType == KernelSoftcoreType::Gapsys) { reactionFieldQuadraticPotential<computeForces>( qq[i], facel, rC, rCutoffCoul, LFC[i], DLF[i], gapsysScaleLinpointCoulEff, krf, crf, &fScalC[i], &vCoul[i], &dvdlCoul, computeElecInteraction); } } vCoul[i] = gmx::selectByMask(vCoul[i], computeElecInteraction); if constexpr (computeForces) { fScalC[i] = gmx::selectByMask(fScalC[i], computeElecInteraction); } } /* Only process the VDW interactions if we either * include all entries in the list (no cutoff used * in the kernel), or if we are within the cutoff. */ BoolType computeVdwInteraction; if constexpr (vdwInteractionTypeIsEwald) { computeVdwInteraction = (r < rVdw && (c6[i] != 0 || c12[i] != 0) && bPairIncluded); } else { computeVdwInteraction = (rV < rVdw && (c6[i] != 0 || c12[i] != 0) && bPairIncluded); } if (gmx::anyTrue(computeVdwInteraction)) { RealType rInv6; if constexpr (softcoreType == KernelSoftcoreType::Beutler) { rInv6 = rPInvV; } else { rInv6 = calculateRinv6(rInvV); } // Avoid overflow at short distance for masked exclusions and // for foreign energy calculations at a hard core end state. // Note that we should limit r^-6, and thus also r^-12, and // not only r^-12, as that could lead to erroneously low instead // of very high foreign energies. rInv6 = gmx::min(rInv6, maxRInvSix); RealType vVdw6 = calculateVdw6(c6[i], rInv6); RealType vVdw12 = calculateVdw12(c12[i], rInv6); vVdw[i] = lennardJonesPotential( vVdw6, vVdw12, c6[i], c12[i], repulsionShift, dispersionShift, oneSixth, oneTwelfth); if constexpr (computeForces) { fScalV[i] = lennardJonesScalarForce(vVdw6, vVdw12); } if constexpr (softcoreType == KernelSoftcoreType::Gapsys) { lennardJonesQuadraticPotential<computeForces>(c6[i], c12[i], r, rSq, LFV[i], DLF[i], gapsysSigma6VdWEff[i], gapsysScaleLinpointVdWEff, repulsionShift, dispersionShift, &fScalV[i], &vVdw[i], &dvdlVdw, computeVdwInteraction); } if constexpr (vdwInteractionTypeIsEwald) { /* Subtract the grid potential at the cut-off */ vVdw[i] = vVdw[i] + gmx::selectByMask(ewaldLennardJonesGridSubtract( ljPmeC6Grid[i], shLjEwald, oneSixth), computeVdwInteraction); } if constexpr (vdwModifierIsPotSwitch) { RealType d = rV - rVdwSwitch; BoolType zeroMask = zero < d; BoolType potSwitchMask = rV < rVdw; d = gmx::selectByMask(d, zeroMask); const RealType d2 = d * d; const RealType sw = one + d2 * d * (vdw_swV3 + d * (vdw_swV4 + d * vdw_swV5)); if constexpr (computeForces) { const RealType dsw = d2 * (vdw_swF2 + d * (vdw_swF3 + d * vdw_swF4)); fScalV[i] = potSwitchScalarForceMod( fScalV[i], vVdw[i], sw, rV, dsw, potSwitchMask); } vVdw[i] = potSwitchPotentialMod(vVdw[i], sw, potSwitchMask); } vVdw[i] = gmx::selectByMask(vVdw[i], computeVdwInteraction); if constexpr (computeForces) { fScalV[i] = gmx::selectByMask(fScalV[i], computeVdwInteraction); } } if constexpr (computeForces) { /* fScalC (and fScalV) now contain: dV/drC * rC * Now we multiply by rC^-6, so it will be: dV/drC * rC^-5 * Further down we first multiply by r^4 and then by * the vector r, which in total gives: dV/drC * (r/rC)^-5 */ fScalC[i] = fScalC[i] * rPInvC; fScalV[i] = fScalV[i] * rPInvV; } } // end of block requiring nonZeroState } // end for (int i = 0; i < NSTATES; i++) /* Assemble A and B states. */ BoolType assembleStates = (bPairIncluded && withinCutoffMask); if (gmx::anyTrue(assembleStates)) { for (int i = 0; i < NSTATES; i++) { vCTot = vCTot + LFC[i] * vCoul[i]; vVTot = vVTot + LFV[i] * vVdw[i]; if constexpr (computeForces) { fScal = fScal + LFC[i] * fScalC[i] * rpm2; fScal = fScal + LFV[i] * fScalV[i] * rpm2; } if constexpr (softcoreType == KernelSoftcoreType::Beutler) { dvdlCoul = dvdlCoul + vCoul[i] * DLF[i] + LFC[i] * alphaCoulEff * dlFacCoul[i] * fScalC[i] * sigma6[i]; dvdlVdw = dvdlVdw + vVdw[i] * DLF[i] + LFV[i] * alphaVdwEff * dlFacVdw[i] * fScalV[i] * sigma6[i]; } else { dvdlCoul = dvdlCoul + vCoul[i] * DLF[i]; dvdlVdw = dvdlVdw + vVdw[i] * DLF[i]; } } } } // end of block requiring bPairIncluded && withinCutoffMask /* In the following block bPairIncluded should be false in the masks. */ if (icoul == NbkernelElecType::ReactionField) { const BoolType computeReactionField = bPairExcluded; if (gmx::anyTrue(computeReactionField)) { /* For excluded pairs we don't use soft-core. * As there is no singularity, there is no need for soft-core. */ const RealType FF = -two * krf; RealType VV = krf * rSq - crf; /* If ii == jnr the i particle (ii) has itself (jnr) * in its neighborlist. This corresponds to a self-interaction * that will occur twice. Scale it down by 50% to only include * it once. */ VV = VV * gmx::blend(one, half, bIiEqJnr); for (int i = 0; i < NSTATES; i++) { vCTot = vCTot + gmx::selectByMask(LFC[i] * qq[i] * VV, computeReactionField); fScal = fScal + gmx::selectByMask(LFC[i] * qq[i] * FF, computeReactionField); dvdlCoul = dvdlCoul + gmx::selectByMask(DLF[i] * qq[i] * VV, computeReactionField); } } } const BoolType computeElecEwaldInteraction = (bPairExcluded || r < rCoulomb); if (elecInteractionTypeIsEwald && gmx::anyTrue(computeElecEwaldInteraction)) { /* See comment in the preamble. When using Ewald interactions * (unless we use a switch modifier) we subtract the reciprocal-space * Ewald component here which made it possible to apply the free * energy interaction to 1/r (vanilla coulomb short-range part) * above. This gets us closer to the ideal case of applying * the softcore to the entire electrostatic interaction, * including the reciprocal-space component. */ RealType v_lr, f_lr; pmeCoulombCorrectionVF<computeForces>(rSq, ewaldBeta, &v_lr, &f_lr); if constexpr (computeForces) { f_lr = f_lr * rInv * rInv; } /* Note that any possible Ewald shift has already been applied in * the normal interaction part above. */ /* If ii == jnr the i particle (ii) has itself (jnr) * in its neighborlist. This corresponds to a self-interaction * that will occur twice. Scale it down by 50% to only include * it once. */ v_lr = v_lr * gmx::blend(one, half, bIiEqJnr); for (int i = 0; i < NSTATES; i++) { vCTot = vCTot - gmx::selectByMask(LFC[i] * qq[i] * v_lr, computeElecEwaldInteraction); if constexpr (computeForces) { fScal = fScal - gmx::selectByMask(LFC[i] * qq[i] * f_lr, computeElecEwaldInteraction); } dvdlCoul = dvdlCoul - gmx::selectByMask(DLF[i] * qq[i] * v_lr, computeElecEwaldInteraction); } } const BoolType computeVdwEwaldInteraction = (bPairExcluded || r < rVdw); if (vdwInteractionTypeIsEwald && gmx::anyTrue(computeVdwEwaldInteraction)) { /* See comment in the preamble. When using LJ-Ewald interactions * (unless we use a switch modifier) we subtract the reciprocal-space * Ewald component here which made it possible to apply the free * energy interaction to r^-6 (vanilla LJ6 short-range part) * above. This gets us closer to the ideal case of applying * the softcore to the entire VdW interaction, * including the reciprocal-space component. */ RealType v_lr, f_lr; pmeLJCorrectionVF<computeForces>( rInv, rSq, ewaldLJCoeffSq, ewaldLJCoeffSixDivSix, &v_lr, &f_lr, computeVdwEwaldInteraction, bIiEqJnr); v_lr = v_lr * oneSixth; for (int i = 0; i < NSTATES; i++) { vVTot = vVTot + gmx::selectByMask(LFV[i] * ljPmeC6Grid[i] * v_lr, computeVdwEwaldInteraction); if constexpr (computeForces) { fScal = fScal + gmx::selectByMask(LFV[i] * ljPmeC6Grid[i] * f_lr, computeVdwEwaldInteraction); } dvdlVdw = dvdlVdw + gmx::selectByMask(DLF[i] * ljPmeC6Grid[i] * v_lr, computeVdwEwaldInteraction); } } if (computeForces && gmx::anyTrue(fScal != zero)) { const RealType tX = fScal * dX; const RealType tY = fScal * dY; const RealType tZ = fScal * dZ; fIX = fIX + tX; fIY = fIY + tY; fIZ = fIZ + tZ; gmx::transposeScatterDecrU<3>(forceRealPtr, preloadJnr, tX, tY, tZ); } } // end for (int k = nj0; k < nj1; k += DataTypes::simdRealWidth) if (havePairsWithinCutoff) { if constexpr (computeForces) { gmx::transposeScatterIncrU<3>(forceRealPtr, preloadIi, fIX, fIY, fIZ); if (doShiftForces) { gmx::transposeScatterIncrU<3>( reinterpret_cast<real*>(threadForceShiftBuffer), preloadIs, fIX, fIY, fIZ); } } if (doPotential) { int ggid = gid[n]; threadVc[ggid] += gmx::reduce(vCTot); threadVv[ggid] += gmx::reduce(vVTot); } } } // end for (int n = 0; n < nri; n++) if (gmx::anyTrue(dvdlCoul != zero)) { threadDvdl[static_cast<int>(FreeEnergyPerturbationCouplingType::Coul)] += gmx::reduce(dvdlCoul); } if (gmx::anyTrue(dvdlVdw != zero)) { threadDvdl[static_cast<int>(FreeEnergyPerturbationCouplingType::Vdw)] += gmx::reduce(dvdlVdw); } /* Estimate flops, average for free energy stuff: * 12 flops per outer iteration * 150 flops per inner iteration * TODO: Update the number of flops and/or use different counts for different code paths. */ atomicNrnbIncrement(nrnb, eNR_NBKERNEL_FREE_ENERGY, nlist.nri * 12 + nlist.jindex[nri] * 150); if (haveExcludedPairsBeyondRlist > 0) { gmx_fatal(FARGS, "There are perturbed non-bonded pair interactions beyond the pair-list cutoff " "of %g nm, which is not supported. This can happen because the system is " "unstable or because intra-molecular interactions at long distances are " "excluded. If the " "latter is the case, you can try to increase nstlist or rlist to avoid this." "The error is likely triggered by the use of couple-intramol=no " "and the maximal distance in the decoupled molecule exceeding rlist.", rlist); } } typedef void (*KernelFunction)(const t_nblist& nlist, const gmx::ArrayRefWithPadding<const gmx::RVec>& coords, const int ntype, const real rlist, const interaction_const_t& ic, gmx::ArrayRef<const gmx::RVec> shiftvec, gmx::ArrayRef<const real> nbfp, gmx::ArrayRef<const real> nbfp_grid, gmx::ArrayRef<const real> chargeA, gmx::ArrayRef<const real> chargeB, gmx::ArrayRef<const int> typeA, gmx::ArrayRef<const int> typeB, int flags, gmx::ArrayRef<const real> lambda, t_nrnb* gmx_restrict nrnb, gmx::ArrayRefWithPadding<gmx::RVec> threadForceBuffer, rvec* threadForceShiftBuffer, gmx::ArrayRef<real> threadVc, gmx::ArrayRef<real> threadVv, gmx::ArrayRef<real> threadDvdl); template<KernelSoftcoreType softcoreType, bool scLambdasOrAlphasDiffer, bool vdwInteractionTypeIsEwald, bool elecInteractionTypeIsEwald, bool vdwModifierIsPotSwitch, bool computeForces> static KernelFunction dispatchKernelOnUseSimd(const bool useSimd) { if (useSimd) { #if GMX_SIMD_HAVE_REAL && GMX_SIMD_HAVE_INT32_ARITHMETICS && GMX_USE_SIMD_KERNELS return (nb_free_energy_kernel<SimdDataTypes, softcoreType, scLambdasOrAlphasDiffer, vdwInteractionTypeIsEwald, elecInteractionTypeIsEwald, vdwModifierIsPotSwitch, computeForces>); #else return (nb_free_energy_kernel<ScalarDataTypes, softcoreType, scLambdasOrAlphasDiffer, vdwInteractionTypeIsEwald, elecInteractionTypeIsEwald, vdwModifierIsPotSwitch, computeForces>); #endif } else { return (nb_free_energy_kernel<ScalarDataTypes, softcoreType, scLambdasOrAlphasDiffer, vdwInteractionTypeIsEwald, elecInteractionTypeIsEwald, vdwModifierIsPotSwitch, computeForces>); } } template<KernelSoftcoreType softcoreType, bool scLambdasOrAlphasDiffer, bool vdwInteractionTypeIsEwald, bool elecInteractionTypeIsEwald, bool vdwModifierIsPotSwitch> static KernelFunction dispatchKernelOnComputeForces(const bool computeForces, const bool useSimd) { if (computeForces) { return (dispatchKernelOnUseSimd<softcoreType, scLambdasOrAlphasDiffer, vdwInteractionTypeIsEwald, elecInteractionTypeIsEwald, vdwModifierIsPotSwitch, true>( useSimd)); } else { return (dispatchKernelOnUseSimd<softcoreType, scLambdasOrAlphasDiffer, vdwInteractionTypeIsEwald, elecInteractionTypeIsEwald, vdwModifierIsPotSwitch, false>( useSimd)); } } template<KernelSoftcoreType softcoreType, bool scLambdasOrAlphasDiffer, bool vdwInteractionTypeIsEwald, bool elecInteractionTypeIsEwald> static KernelFunction dispatchKernelOnVdwModifier(const bool vdwModifierIsPotSwitch, const bool computeForces, const bool useSimd) { if (vdwModifierIsPotSwitch) { return (dispatchKernelOnComputeForces<softcoreType, scLambdasOrAlphasDiffer, vdwInteractionTypeIsEwald, elecInteractionTypeIsEwald, true>( computeForces, useSimd)); } else { return (dispatchKernelOnComputeForces<softcoreType, scLambdasOrAlphasDiffer, vdwInteractionTypeIsEwald, elecInteractionTypeIsEwald, false>( computeForces, useSimd)); } } template<KernelSoftcoreType softcoreType, bool scLambdasOrAlphasDiffer, bool vdwInteractionTypeIsEwald> static KernelFunction dispatchKernelOnElecInteractionType(const bool elecInteractionTypeIsEwald, const bool vdwModifierIsPotSwitch, const bool computeForces, const bool useSimd) { if (elecInteractionTypeIsEwald) { return (dispatchKernelOnVdwModifier<softcoreType, scLambdasOrAlphasDiffer, vdwInteractionTypeIsEwald, true>( vdwModifierIsPotSwitch, computeForces, useSimd)); } else { return (dispatchKernelOnVdwModifier<softcoreType, scLambdasOrAlphasDiffer, vdwInteractionTypeIsEwald, false>( vdwModifierIsPotSwitch, computeForces, useSimd)); } } template<KernelSoftcoreType softcoreType, bool scLambdasOrAlphasDiffer> static KernelFunction dispatchKernelOnVdwInteractionType(const bool vdwInteractionTypeIsEwald, const bool elecInteractionTypeIsEwald, const bool vdwModifierIsPotSwitch, const bool computeForces, const bool useSimd) { if (vdwInteractionTypeIsEwald) { return (dispatchKernelOnElecInteractionType<softcoreType, scLambdasOrAlphasDiffer, true>( elecInteractionTypeIsEwald, vdwModifierIsPotSwitch, computeForces, useSimd)); } else { return (dispatchKernelOnElecInteractionType<softcoreType, scLambdasOrAlphasDiffer, false>( elecInteractionTypeIsEwald, vdwModifierIsPotSwitch, computeForces, useSimd)); } } template<KernelSoftcoreType softcoreType> static KernelFunction dispatchKernelOnScLambdasOrAlphasDifference(const bool scLambdasOrAlphasDiffer, const bool vdwInteractionTypeIsEwald, const bool elecInteractionTypeIsEwald, const bool vdwModifierIsPotSwitch, const bool computeForces, const bool useSimd) { if (scLambdasOrAlphasDiffer) { return (dispatchKernelOnVdwInteractionType<softcoreType, true>( vdwInteractionTypeIsEwald, elecInteractionTypeIsEwald, vdwModifierIsPotSwitch, computeForces, useSimd)); } else { return (dispatchKernelOnVdwInteractionType<softcoreType, false>( vdwInteractionTypeIsEwald, elecInteractionTypeIsEwald, vdwModifierIsPotSwitch, computeForces, useSimd)); } } static KernelFunction dispatchKernel(const bool scLambdasOrAlphasDiffer, const bool vdwInteractionTypeIsEwald, const bool elecInteractionTypeIsEwald, const bool vdwModifierIsPotSwitch, const bool computeForces, const bool useSimd, const interaction_const_t& ic) { const auto& scParams = *ic.softCoreParameters; if (scParams.softcoreType == SoftcoreType::Beutler) { if (scParams.alphaCoulomb == 0 && scParams.alphaVdw == 0) { return (dispatchKernelOnScLambdasOrAlphasDifference<KernelSoftcoreType::None>( scLambdasOrAlphasDiffer, vdwInteractionTypeIsEwald, elecInteractionTypeIsEwald, vdwModifierIsPotSwitch, computeForces, useSimd)); } return (dispatchKernelOnScLambdasOrAlphasDifference<KernelSoftcoreType::Beutler>( scLambdasOrAlphasDiffer, vdwInteractionTypeIsEwald, elecInteractionTypeIsEwald, vdwModifierIsPotSwitch, computeForces, useSimd)); } else // Gapsys { if (scParams.gapsysScaleLinpointCoul == 0 && scParams.gapsysScaleLinpointVdW == 0) { return (dispatchKernelOnScLambdasOrAlphasDifference<KernelSoftcoreType::None>( scLambdasOrAlphasDiffer, vdwInteractionTypeIsEwald, elecInteractionTypeIsEwald, vdwModifierIsPotSwitch, computeForces, useSimd)); } return (dispatchKernelOnScLambdasOrAlphasDifference<KernelSoftcoreType::Gapsys>( scLambdasOrAlphasDiffer, vdwInteractionTypeIsEwald, elecInteractionTypeIsEwald, vdwModifierIsPotSwitch, computeForces, useSimd)); } } void gmx_nb_free_energy_kernel(const t_nblist& nlist, const gmx::ArrayRefWithPadding<const gmx::RVec>& coords, const bool useSimd, const int ntype, const real rlist, const interaction_const_t& ic, gmx::ArrayRef<const gmx::RVec> shiftvec, gmx::ArrayRef<const real> nbfp, gmx::ArrayRef<const real> nbfp_grid, gmx::ArrayRef<const real> chargeA, gmx::ArrayRef<const real> chargeB, gmx::ArrayRef<const int> typeA, gmx::ArrayRef<const int> typeB, int flags, gmx::ArrayRef<const real> lambda, t_nrnb* nrnb, gmx::ArrayRefWithPadding<gmx::RVec> threadForceBuffer, rvec* threadForceShiftBuffer, gmx::ArrayRef<real> threadVc, gmx::ArrayRef<real> threadVv, gmx::ArrayRef<real> threadDvdl) { GMX_ASSERT(EEL_PME_EWALD(ic.eeltype) || ic.eeltype == CoulombInteractionType::Cut || EEL_RF(ic.eeltype), "Unsupported eeltype with free energy"); GMX_ASSERT(ic.softCoreParameters, "We need soft-core parameters"); // Not all SIMD implementations need padding, but we provide padding anyhow so we can assert GMX_ASSERT(!GMX_SIMD_HAVE_REAL || threadForceBuffer.empty() || threadForceBuffer.size() > threadForceBuffer.unpaddedArrayRef().ssize(), "We need actual padding with at least one element for SIMD scatter operations"); const auto& scParams = *ic.softCoreParameters; const bool vdwInteractionTypeIsEwald = (EVDW_PME(ic.vdwtype)); const bool elecInteractionTypeIsEwald = (EEL_PME_EWALD(ic.eeltype)); const bool vdwModifierIsPotSwitch = (ic.vdw_modifier == InteractionModifiers::PotSwitch); const bool computeForces = ((flags & GMX_NONBONDED_DO_FORCE) != 0); bool scLambdasOrAlphasDiffer = true; if (scParams.alphaCoulomb == 0 && scParams.alphaVdw == 0) { scLambdasOrAlphasDiffer = false; } else { if (lambda[static_cast<int>(FreeEnergyPerturbationCouplingType::Coul)] == lambda[static_cast<int>(FreeEnergyPerturbationCouplingType::Vdw)] && scParams.alphaCoulomb == scParams.alphaVdw) { scLambdasOrAlphasDiffer = false; } } KernelFunction kernelFunc; kernelFunc = dispatchKernel(scLambdasOrAlphasDiffer, vdwInteractionTypeIsEwald, elecInteractionTypeIsEwald, vdwModifierIsPotSwitch, computeForces, useSimd, ic); kernelFunc(nlist, coords, ntype, rlist, ic, shiftvec, nbfp, nbfp_grid, chargeA, chargeB, typeA, typeB, flags, lambda, nrnb, threadForceBuffer, threadForceShiftBuffer, threadVc, threadVv, threadDvdl); }
gromacs/gromacs
<|start_filename|>.eslintrc.js<|end_filename|> module.exports = { 'extends': 'standard', 'rules': { 'arrow-parens': ['error', 'always'], 'brace-style': ['error', 'stroustrup'], 'comma-dangle': ['error', 'always-multiline'], 'line-comment-position': ['error', { 'position': 'above' }], 'padded-blocks': 'off', 'semi': ['error', 'always'], 'quotes': ['error', 'single', { 'avoidEscape': true }], // disabled for now 'camelcase': 'off', 'operator-linebreak': ['error', 'before'], }, }; <|start_filename|>src/models/send-to-api.js<|end_filename|> 'use strict'; const Logger = require('../logger.js'); const { addOauthHeader } = require('@clevercloud/client/cjs/oauth.node.js'); const { conf, loadOAuthConf } = require('../models/configuration.js'); const { execWarpscript } = require('@clevercloud/client/cjs/request-warp10.superagent.js'); const { prefixUrl } = require('@clevercloud/client/cjs/prefix-url.js'); const { request } = require('@clevercloud/client/cjs/request.superagent.js'); async function loadTokens () { const tokens = await loadOAuthConf(); return { OAUTH_CONSUMER_KEY: conf.OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET: conf.OAUTH_CONSUMER_SECRET, API_OAUTH_TOKEN: tokens.<PASSWORD>, API_OAUTH_TOKEN_SECRET: tokens.secret, }; } async function sendToApi (requestParams) { const tokens = await loadTokens(); return Promise.resolve(requestParams) .then(prefixUrl(conf.API_HOST)) .then(addOauthHeader(tokens)) .then((requestParams) => { if (process.env.CLEVER_VERBOSE) { Logger.debug(`${requestParams.method.toUpperCase()} ${requestParams.url} ? ${JSON.stringify(requestParams.queryParams)}`); } return requestParams; }) .then((requestParams) => request(requestParams, { retry: 1 })); } function sendToWarp10 (requestParams) { return Promise.resolve(requestParams) .then(prefixUrl(conf.WARP_10_EXEC_URL)) .then((requestParams) => execWarpscript(requestParams, { retry: 1 })); } async function getHostAndTokens () { const tokens = await loadTokens(); return { apiHost: conf.API_HOST, tokens, }; } module.exports = { sendToApi, sendToWarp10, getHostAndTokens }; <|start_filename|>src/commands/profile.js<|end_filename|> 'use strict'; const colors = require('colors/safe'); const Logger = require('../logger.js'); const User = require('../models/user.js'); async function profile () { const { id, name, email, preferredMFA } = await User.getCurrent(); const has2FA = (preferredMFA != null && preferredMFA !== 'NONE') ? 'yes' : 'no'; const formattedName = name || colors.red.bold('[not specified]'); Logger.println('You\'re currently logged in as:'); Logger.println('User id ' + id); Logger.println('Name ' + formattedName); Logger.println('Email ' + email); Logger.println('Two factor auth ' + has2FA); }; module.exports = { profile }; <|start_filename|>spec/logger.spec.js<|end_filename|> 'use strict'; var expect = require('chai').expect; var Logger = require("../src/logger.js"); describe("logger.processApiError", function() { it("leave unchanged errors not emitted by the CCAPI", function() { var error = "Regular error message"; expect(Logger.processApiError(error)).to.equal("Regular error message"); }); it("Display code and message for API errors", function() { var error = { id: 4002, message: "The provided application id doesn't belong to you", type: "error" }; expect(Logger.processApiError(error)).to.equal("The provided application id doesn't belong to you [4002]"); }); it("Display code, message and fields errors for API errors", function() { var error = { id: 501, message: "Your application did not satisfy our requirements", type: "error", fields: { zone: "Wrong zone", other: "Wrong other" } }; expect(Logger.processApiError(error)).to.equal( "Your application did not satisfy our requirements [501]\n" + "zone: Wrong zone\n" + "other: Wrong other" ); }); }); <|start_filename|>src/commands/version.js<|end_filename|> 'use strict'; const Logger = require('../logger.js'); const pkg = require('../../package.json'); async function version () { Logger.println(pkg.version); } module.exports = { version }; <|start_filename|>src/commands/logs.js<|end_filename|> 'use strict'; const AppConfig = require('../models/app_configuration.js'); const Log = require('../models/log.js'); const Logger = require('../logger.js'); async function appLogs (params) { const { alias, after: since, before: until, search, 'deployment-id': deploymentId } = params.options; const { addon: addonId } = params.options; // ignore --search "" const filter = (search !== '') ? search : null; const appAddonId = addonId || await AppConfig.getAppDetails({ alias }).then(({ appId }) => appId); Logger.println('Waiting for application logs…'); return Log.displayLogs({ appAddonId, since, until, filter, deploymentId }); } module.exports = { appLogs }; <|start_filename|>src/models/addon.js<|end_filename|> 'use strict'; const application = require('@clevercloud/client/cjs/api/v2/application.js'); const autocomplete = require('cliparse').autocomplete; const colors = require('colors/safe'); const { get: getAddon, getAll: getAllAddons, remove: removeAddon, create: createAddon, preorder: preorderAddon, update: updateAddon } = require('@clevercloud/client/cjs/api/v2/addon.js'); const { getAllAddonProviders } = require('@clevercloud/client/cjs/api/v2/product.js'); const { getSummary } = require('@clevercloud/client/cjs/api/v2/user.js'); const { getAddonProvider } = require('@clevercloud/client/cjs/api/v4/addon-providers.js'); const Interact = require('./interact.js'); const Logger = require('../logger.js'); const { sendToApi } = require('../models/send-to-api.js'); function listProviders () { return getAllAddonProviders({}).then(sendToApi); } async function getProvider (providerName) { const providers = await listProviders(); const provider = providers.find((p) => p.id === providerName); if (provider == null) { throw new Error('invalid provider name'); } return provider; } function getProviderInfos (providerName) { return getAddonProvider({ providerId: providerName }).then(sendToApi) .catch(() => { // An error can occur because the add-on api doesn't implement this endpoint yet // This is fine, just ignore it Logger.debug(`${providerName} doesn't yet implement the provider info endpoint`); return Promise.resolve(null); }); } async function list (ownerId, appId, showAll) { const allAddons = await getAllAddons({ id: ownerId }).then(sendToApi); if (appId == null) { // Not linked to a specific app, show everything return allAddons; } const myAddons = await application.getAllLinkedAddons({ id: ownerId, appId }).then(sendToApi); if (showAll == null) { return myAddons; } const myAddonIds = myAddons.map((addon) => addon.id); return allAddons.map((addon) => { const isLinked = myAddonIds.includes(addon.id); return { ...addon, isLinked }; }); } function validateAddonVersionAndOptions (region, version, addonOptions, providerInfos, planType) { if (providerInfos != null) { if (version != null) { const type = planType.value.toLowerCase(); if (type === 'shared') { const cluster = providerInfos.clusters.find(({ zone }) => zone === region); if (cluster == null) { throw new Error(`Can't find cluster for region ${region}`); } else if (cluster.version !== version) { throw new Error(`Invalid version ${version}, selected shared cluster only supports version ${cluster.version}`); } } else if (type === 'dedicated') { const availableVersions = Object.keys(providerInfos.dedicated); const hasVersion = availableVersions.find((availableVersion) => availableVersion === version); if (hasVersion == null) { throw new Error(`Invalid version ${addonOptions.version}, available versions are: ${availableVersions.join(', ')}`); } } } const chosenVersion = version != null ? version : providerInfos.defaultDedicatedVersion; // Check the selected options to see if the chosen plan / region offers them // If not, abort the creation if (Object.keys(addonOptions).length > 0) { const type = planType.value.toLowerCase(); let availableOptions = []; if (type === 'shared') { const cluster = providerInfos.clusters.find(({ zone }) => zone === region); if (cluster == null) { throw new Error(`Can't find cluster for region ${region}`); } availableOptions = cluster.features; } else if (type === 'dedicated') { availableOptions = providerInfos.dedicated[chosenVersion].features; } for (const selectedOption in addonOptions) { const isAvailable = availableOptions.find(({ name }) => name === selectedOption); if (isAvailable == null) { const optionNames = availableOptions.map(({ name }) => name).join(','); let availableOptionsError = null; if (optionNames.length > 0) { availableOptionsError = `Avalailble options are: ${optionNames}.`; } else { availableOptionsError = 'No options are available for this plan.'; } throw new Error(`Option "${selectedOption}" is not available on this plan. ${availableOptionsError}`); } } } return { version: chosenVersion, ...addonOptions, }; } else { if (version != null) { throw new Error('You provided a version for an add-on that doesn\'t support choosing the version.'); } return {}; } } async function create ({ ownerId, name, providerName, planName, region, skipConfirmation, version, addonOptions }) { // TODO: We should be able to use it without {} const providers = await listProviders(); const provider = providers.find((p) => p.id === providerName); if (provider == null) { throw new Error('invalid provider name'); } if (!provider.regions.includes(region)) { throw new Error(`invalid region name. Available regions: ${provider.regions.join(', ')}`); } const plan = provider.plans.find((p) => p.slug.toLowerCase() === planName.toLowerCase()); if (plan == null) { const availablePlans = provider.plans.map((p) => p.slug); throw new Error(`invalid plan name. Available plans: ${availablePlans.join(', ')}`); } const providerInfos = await getProviderInfos(provider.id); const planType = plan.features.find(({ name }) => name.toLowerCase() === 'type'); // If we have a providerInfos but we don't have a planType, we won't be able to go further // The process should stop here to make sure users don't create something they don't intend to // This missing feature should have been added during the add-on's development phase // The console has a similar check so I believe we shouldn't hit this if (providerInfos != null && planType == null) { throw new Error('Internal error. The selected plan misses the TYPE feature. Please contact our support with the command line you used'); } const createOptions = validateAddonVersionAndOptions(region, version, addonOptions, providerInfos, planType); const addonToCreate = { name, plan: plan.id, providerId: provider.id, region, options: createOptions, }; const result = await preorderAddon({ id: ownerId }, addonToCreate).then(sendToApi); if (result.totalTTC > 0 && !skipConfirmation) { result.lines.forEach(({ description, VAT, price }) => Logger.println(`${description}\tVAT: ${VAT}%\tPrice: ${price}€`)); Logger.println(`Total (without taxes): ${result.totalHT}€`); Logger.println(colors.bold(`Total (with taxes): ${result.totalTTC}€`)); await Interact.confirm( `You're about to pay ${result.totalTTC}€, confirm? (yes or no) `, 'No confirmation, aborting addon creation', ); } return createAddon({ id: ownerId }, addonToCreate).then(sendToApi); } async function getByName (ownerId, addonNameOrRealId) { const addons = await getAllAddons({ id: ownerId }).then(sendToApi); const filteredAddons = addons.filter(({ name, realId }) => { return name === addonNameOrRealId || realId === addonNameOrRealId; }); if (filteredAddons.length === 1) { return filteredAddons[0]; } if (filteredAddons.length === 0) { throw new Error('Addon not found'); } throw new Error('Ambiguous addon name'); } async function getId (ownerId, addon) { if (addon.addon_id) { return addon.addon_id; } const addonDetails = await getByName(ownerId, addon.addon_name); return addonDetails.id; } async function link (ownerId, appId, addon) { const addonId = await getId(ownerId, addon); return application.linkAddon({ id: ownerId, appId }, JSON.stringify(addonId)).then(sendToApi); } async function unlink (ownerId, appId, addon) { const addonId = await getId(ownerId, addon); return application.unlinkAddon({ id: ownerId, appId, addonId }).then(sendToApi); } async function deleteAddon (ownerId, addonIdOrName, skipConfirmation) { const addonId = await getId(ownerId, addonIdOrName); if (!skipConfirmation) { await Interact.confirm('Deleting the addon can\'t be undone, are you sure? ', 'No confirmation, aborting addon deletion'); } return removeAddon({ id: ownerId, addonId }).then(sendToApi); } async function rename (ownerId, addon, name) { const addonId = await getId(ownerId, addon); return updateAddon({ id: ownerId, addonId }, { name }).then(sendToApi); } function completeRegion () { return autocomplete.words(['par', 'mtl']); } // TODO: We need to fix this function completePlan () { return autocomplete.words(['dev', 's', 'm', 'l', 'xl', 'xxl']); } async function findById (addonId) { const { user, organisations } = await getSummary({}).then(sendToApi); for (const orga of [user, ...organisations]) { for (const simpleAddon of orga.addons) { if (simpleAddon.id === addonId) { const addon = await getAddon({ id: orga.id, addonId }).then(sendToApi); return { ...addon, orgaId: orga.id, }; } } } throw new Error(`Could not find add-on with ID: ${addonId}`); } function parseAddonOptions (options) { if (options == null) { return {}; } return options.split(',').reduce((options, option) => { const [key, value] = option.split('='); if (value == null) { throw new Error("Options are malformed. Usage is '--option name=enabled|disabled|true|false'"); } let formattedValue = value; if (value === 'true' || value === 'enabled') { formattedValue = 'true'; } else if (value === 'false' || value === 'disabled') { formattedValue = 'false'; } else { throw new Error(`Can't parse option value: ${value}. Accepted values are: enabled, disabled, true, false`); } options[key] = formattedValue; return options; }, {}); } module.exports = { completePlan, completeRegion, create, delete: deleteAddon, findById, getProvider, getProviderInfos, link, list, listProviders, parseAddonOptions, rename, unlink, }; <|start_filename|>src/models/application_configuration.js<|end_filename|> 'use strict'; const cliparse = require('cliparse'); const colors = require('colors/safe'); const Logger = require('../logger.js'); const CONFIG_KEYS = [ { id: 'name', name: 'name', displayName: 'Name', kind: 'string' }, { id: 'description', name: 'description', displayName: 'Description', kind: 'string' }, { id: 'zero-downtime', name: 'homogeneous', displayName: 'Zero-downtime deployment', kind: 'inverted-bool' }, { id: 'sticky-sessions', name: 'stickySessions', displayName: 'Sticky sessions', kind: 'bool' }, { id: 'cancel-on-push', name: 'cancelOnPush', displayName: 'Cancel current deployment on push', kind: 'bool' }, { id: 'force-https', name: 'forceHttps', displayName: 'Force redirection of HTTP to HTTPS', kind: 'force-https' }, ]; function listAvailableIds () { return CONFIG_KEYS.map((config) => config.id); } function getById (id) { const config = CONFIG_KEYS.find((config) => config.id === id); if (config == null) { Logger.error(`Invalid configuration name: ${id}.`); Logger.error(`Available configuration names are: ${listAvailableIds().join(', ')}.`); } return config; } function display (config, value) { switch (config.kind) { case 'bool': { return (value) ? 'enabled' : 'disabled'; } case 'inverted-bool': { return (value) ? 'disabled' : 'enabled'; } case 'force-https': { return value.toLowerCase(); } default: { return String(value); } } } function parse (config, value) { switch (config.kind) { case 'bool': { return (value !== 'false'); } case 'inverted-bool': { return (value === 'false'); } case 'force-https': { return (value === 'false') ? 'DISABLED' : 'ENABLED'; } default: { return value; } } } function getUpdateOptions () { return CONFIG_KEYS .map((config) => getConfigOptions(config)) .reduce((a, b) => [...a, ...b], []); } function getConfigOptions (config) { switch (config.kind) { case 'bool': case 'inverted-bool': case 'force-https': { return [ cliparse.flag(`enable-${config.id}`, { description: `Enable ${config.id}` }), cliparse.flag(`disable-${config.id}`, { description: `Disable ${config.id}` }), ]; } default: { return [ cliparse.option(`${config.id}`, { description: `Set ${config.id}` }), ]; } } } function parseOptions (options) { const newOptions = CONFIG_KEYS .map((config) => parseConfigOption(config, options)) .filter((a) => a != null); return Object.fromEntries(newOptions); } function parseConfigOption (config, options) { switch (config.kind) { case 'bool': { const enable = options[`enable-${config.id}`]; const disable = options[`disable-${config.id}`]; if (enable && disable) { Logger.warn(`${config.id} is both enabled and disabled, ignoring`); } else if (enable || disable) { return [config.name, enable]; } return null; } case 'inverted-bool': { const disable = options[`enable-${config.id}`]; const enable = options[`disable-${config.id}`]; if (enable && disable) { Logger.warn(`${config.id} is both enabled and disabled, ignoring`); } else if (enable || disable) { return [config.name, enable]; } return null; } case 'force-https': { const enable = options[`enable-${config.id}`]; const disable = options[`disable-${config.id}`]; if (enable && disable) { Logger.warn(`${config.id} is both enabled and disabled, ignoring`); } else if (enable || disable) { const value = (enable) ? 'ENABLED' : 'DISABLED'; return [config.name, value]; } return null; } default: { if (options[config.id] !== null) { return [config.name, options[config.id]]; } return null; } } } function printConfig (app, config) { if (app[config.name] != null) { Logger.println(`${config.displayName}: ${colors.bold(display(config, app[config.name]))}`); } } function printById (app, id) { const config = getById(id); if (config != null) { printConfig(app, config); } } function printByName (app, name) { const config = CONFIG_KEYS.find((config) => config.name === name); printConfig(app, config); } function print (app) { for (const config of CONFIG_KEYS) { printConfig(app, config); } } module.exports = { listAvailableIds, getById, getUpdateOptions, parse, parseOptions, printById, printByName, print }; <|start_filename|>src/commands/activity.js<|end_filename|> 'use strict'; const colors = require('colors/safe'); const moment = require('moment'); const Activity = require('../models/activity.js'); const AppConfig = require('../models/app_configuration.js'); const formatTable = require('../format-table'); const Logger = require('../logger.js'); const { Deferred } = require('../models/utils.js'); const { EventsStream } = require('@clevercloud/client/cjs/streams/events.node.js'); const { getHostAndTokens } = require('../models/send-to-api.js'); function getColoredState (state, isLast) { if (state === 'OK') { return colors.bold.green(state); } if (state === 'FAIL' || state === 'CANCELLED') { return colors.bold.red(state); } if (state === 'WIP' && !isLast) { return colors.bold.red('FAIL'); } if (state === 'WIP' && isLast) { return colors.bold.blue('IN PROGRESS'); } Logger.warn(`Unknown deployment state: ${state}`); return 'UNKNOWN'; } // We use examples of maximum width text to have a clean display const formatActivityTable = formatTable([ moment().format(), 'IN PROGRESS', 'downscale', // a git commit id is 40 chars long 40, 0, ]); function formatActivityLine (event) { return formatActivityTable([ [ moment(event.date).format(), getColoredState(event.state, event.isLast), event.action, event.commit || 'not specified', event.cause, ], ]); }; function isTemporaryEvent (ev) { if (ev == null) { return false; } return (ev.state === 'WIP' && ev.isLast) || ev.state === 'CANCELLED'; } function clearPreviousLine () { if (process.stdout.isTTY) { process.stdout.moveCursor(0, -1); process.stdout.cursorTo(0); process.stdout.clearLine(0); } } function handleEvent (previousEvent, event) { if (isTemporaryEvent(previousEvent)) { clearPreviousLine(); } const activityLine = formatActivityLine(event); Logger.println(activityLine); return event; } function onEvent (previousEvent, newEvent) { const { event, date, data: { state, action, commit, cause } } = newEvent; if (event !== 'DEPLOYMENT_ACTION_BEGIN' && event !== 'DEPLOYMENT_ACTION_END') { return previousEvent; } return handleEvent(previousEvent, { date, state, action, commit, cause, isLast: true }); } async function activity (params) { const { alias, 'show-all': showAll, follow } = params.options; const { ownerId, appId } = await AppConfig.getAppDetails({ alias }); const events = await Activity.list(ownerId, appId, showAll); const reversedArrayWithIndex = events .reverse() .map((event, index, all) => { const isLast = index === all.length - 1; return ({ ...event, isLast }); }); let lastEvent = reversedArrayWithIndex.reduce(handleEvent, {}); if (!follow) { return lastEvent; } const { apiHost, tokens } = await getHostAndTokens(); const eventsStream = new EventsStream({ apiHost, tokens, appId }); const deferred = new Deferred(); eventsStream .on('open', () => Logger.debug('WS for events (open) ' + JSON.stringify({ appId }))) .on('event', (event) => { lastEvent = onEvent(lastEvent, event); return lastEvent; }) .on('ping', () => Logger.debug('WS for events (ping)')) .on('close', ({ reason }) => Logger.debug('WS for events (close) ' + reason)) .on('error', deferred.reject); eventsStream.open({ autoRetry: true, maxRetryCount: 6 }); return deferred.promise; } module.exports = { activity }; <|start_filename|>src/commands/create.js<|end_filename|> 'use strict'; const Application = require('../models/application.js'); const AppConfig = require('../models/app_configuration.js'); const Logger = require('../logger.js'); async function create (params) { const { type: typeName } = params.options; const [name] = params.args; const { org: orgaIdOrName, alias, region, github: githubOwnerRepo } = params.options; const github = getGithubDetails(githubOwnerRepo); const app = await Application.create(name, typeName, region, orgaIdOrName, github); await AppConfig.addLinkedApplication(app, alias); Logger.println('Your application has been successfully created!'); }; function getGithubDetails (githubOwnerRepo) { if (githubOwnerRepo != null) { const [owner, name] = githubOwnerRepo.split('/'); return { owner, name }; } } module.exports = { create }; <|start_filename|>src/commands/restart.js<|end_filename|> 'use strict'; const colors = require('colors/safe'); const AppConfig = require('../models/app_configuration.js'); const Application = require('../models/application.js'); const git = require('../models/git.js'); const Log = require('../models/log.js'); const Logger = require('../logger.js'); // Once the API call to redeploy() has been triggerred successfully, // the rest (waiting for deployment state to evolve and displaying logs) is done with auto retry (resilient to network pb) async function restart (params) { const { alias, quiet, commit, 'without-cache': withoutCache, follow } = params.options; const { ownerId, appId, name: appName } = await AppConfig.getAppDetails({ alias }); const fullCommitId = await git.resolveFullCommitId(commit); const app = await Application.get(ownerId, appId); const remoteCommitId = app.commitId; const commitId = fullCommitId || remoteCommitId; if (commitId != null) { const cacheSuffix = withoutCache ? ' without using cache' : ''; Logger.println(`Restarting ${appName} on commit ${colors.green(commitId)}${cacheSuffix}`); } const redeploy = await Application.redeploy(ownerId, appId, fullCommitId, withoutCache); return Log.watchDeploymentAndDisplayLogs({ ownerId, appId, deploymentId: redeploy.deploymentId, quiet, follow }); } module.exports = { restart }; <|start_filename|>src/commands/service.js<|end_filename|> 'use strict'; const Addon = require('../models/addon.js'); const AppConfig = require('../models/app_configuration.js'); const Application = require('../models/application.js'); const Logger = require('../logger.js'); async function list (params) { const { alias, 'show-all': showAll, 'only-apps': onlyApps, 'only-addons': onlyAddons } = params.options; if (onlyApps && onlyAddons) { throw new Error('--only-apps and --only-addons are mutually exclusive'); } const { ownerId, appId } = await AppConfig.getAppDetails({ alias }); if (!onlyAddons) { const apps = await Application.listDependencies(ownerId, appId, showAll); Logger.println('Applications:'); apps.forEach(({ isLinked, name }) => Logger.println(`${isLinked ? '*' : ' '} ${name}`)); } if (!onlyApps) { const addons = await Addon.list(ownerId, appId, showAll); Logger.println('Addons:'); addons.forEach(({ isLinked, name, realId }) => Logger.println(`${isLinked ? '*' : ' '} ${name} (${realId})`)); } } async function linkApp (params) { const { alias } = params.options; const [dependency] = params.args; const { ownerId, appId } = await AppConfig.getAppDetails({ alias }); await Application.link(ownerId, appId, dependency); Logger.println(`App ${dependency.app_id || dependency.app_name} successfully linked`); } async function unlinkApp (params) { const { alias } = params.options; const [dependency] = params.args; const { ownerId, appId } = await AppConfig.getAppDetails({ alias }); await Application.unlink(ownerId, appId, dependency); Logger.println(`App ${dependency.app_id || dependency.app_name} successfully unlinked`); } async function linkAddon (params) { const { alias } = params.options; const [addon] = params.args; const { ownerId, appId } = await AppConfig.getAppDetails({ alias }); await Addon.link(ownerId, appId, addon); Logger.println(`Addon ${addon.addon_id || addon.addon_name} successfully linked`); } async function unlinkAddon (params) { const { alias } = params.options; const [addon] = params.args; const { ownerId, appId } = await AppConfig.getAppDetails({ alias }); await Addon.unlink(ownerId, appId, addon); Logger.println(`Addon ${addon.addon_id || addon.addon_name} successfully unlinked`); } module.exports = { list, linkApp, unlinkApp, linkAddon, unlinkAddon, }; <|start_filename|>spec/email-notify.spec.js<|end_filename|> 'use strict'; const expect = require('chai').expect; const notifications = require('../src/commands/notify-email.js'); describe('notifications.getEmailNotificationTargets', function () { it('handle default case', function () { const input = null; const output = notifications.getEmailNotificationTargets(input); const expected = []; expect(output).to.deep.equal(expected); }); it('handle single user id', function () { const input = ['user_20ebac08-8531-4296-98c9-8dbc7abcd3f4']; const output = notifications.getEmailNotificationTargets(input); const expected = [{ type: 'userid', target: 'user_20ebac08-8531-4296-98c9-8dbc7abcd3f4' }]; expect(output).to.deep.equal(expected); }); it('handle single email address', function () { const input = ['<EMAIL>']; const output = notifications.getEmailNotificationTargets(input); const expected = [{ type: 'email', target: '<EMAIL>' }]; expect(output).to.deep.equal(expected); }); it('handle single organisation token', function () { const input = ['organisation']; const output = notifications.getEmailNotificationTargets(input); const expected = [{ type: 'organisation' }]; expect(output).to.deep.equal(expected); }); it('handle mixed targets', function () { const input = ['organisation', '<EMAIL>', 'user_20ebac08-8531-4296-98c9-8dbc7abcd3f4']; const output = notifications.getEmailNotificationTargets(input); const expected = [ { type: 'organisation' }, { type: 'email', target: '<EMAIL>' }, { type: 'userid', target: 'user_20ebac08-8531-4296-98c9-8dbc7abcd3f4' }, ]; expect(output).to.deep.equal(expected); }); }); <|start_filename|>src/command-promise-handler.js<|end_filename|> 'use strict'; const Logger = require('./logger.js'); const pkg = require('../package.json'); const semver = require('semver'); function handleCommandPromise (promise) { promise.catch((error) => { Logger.error(error); const semverIsOk = semver.satisfies(process.version, pkg.engines.node); if (!semverIsOk) { Logger.warn(`You are using node ${process.version}, some of our commands require node ${pkg.engines.node}. The error may be caused by this.`); } process.exit(1); }); } module.exports = handleCommandPromise; <|start_filename|>src/commands/drain.js<|end_filename|> 'use strict'; const AppConfig = require('../models/app_configuration.js'); const { createDrainBody } = require('../models/drain.js'); const Logger = require('../logger.js'); const { getDrains, createDrain, deleteDrain, updateDrainState } = require('@clevercloud/client/cjs/api/v2/log.js'); const { sendToApi } = require('../models/send-to-api.js'); // TODO: This could be useful in other commands async function getAppOrAddonId ({ alias, addonId }) { return (addonId != null) ? addonId : AppConfig.getAppDetails({ alias }).then(({ appId }) => appId); } async function list (params) { const { alias, addon: addonId } = params.options; const appIdOrAddonId = await getAppOrAddonId({ alias, addonId }); const drains = await getDrains({ appId: appIdOrAddonId }).then(sendToApi); if (drains.length === 0) { Logger.println(`There are no drains for ${appIdOrAddonId}`); } drains.forEach((drain) => { const { id, state, target: { url, drainType } } = drain; Logger.println(`${id} -> ${state} for ${url} as ${drainType}`); }); } async function create (params) { const [drainTargetType, drainTargetURL] = params.args; const { alias, addon: addonId, username, password, 'api-key': apiKey } = params.options; const drainTargetCredentials = { username, password }; const drainTargetConfig = { apiKey }; const appIdOrAddonId = await getAppOrAddonId({ alias, addonId }); const body = createDrainBody(appIdOrAddonId, drainTargetURL, drainTargetType, drainTargetCredentials, drainTargetConfig); await createDrain({ appId: appIdOrAddonId }, body).then(sendToApi); Logger.println('Your drain has been successfully saved'); } async function rm (params) { const [drainId] = params.args; const { alias, addon: addonId } = params.options; const appIdOrAddonId = await getAppOrAddonId({ alias, addonId }); await deleteDrain({ appId: appIdOrAddonId, drainId }).then(sendToApi); Logger.println('Your drain has been successfully removed'); } async function enable (params) { const [drainId] = params.args; const { alias, addon: addonId } = params.options; const appIdOrAddonId = await getAppOrAddonId({ alias, addonId }); await updateDrainState({ appId: appIdOrAddonId, drainId }, { state: 'ENABLED' }).then(sendToApi); Logger.println('Your drain has been enabled'); } async function disable (params) { const [drainId] = params.args; const { alias, addon: addonId } = params.options; const appIdOrAddonId = await getAppOrAddonId({ alias, addonId }); await updateDrainState({ appId: appIdOrAddonId, drainId }, { state: 'DISABLED' }).then(sendToApi); Logger.println('Your drain has been disabled'); } module.exports = { list, create, rm, enable, disable, }; <|start_filename|>src/models/interact.js<|end_filename|> 'use strict'; const readline = require('readline'); function ask (question) { const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); return new Promise((resolve) => { rl.question(question, (answer) => { rl.close(); resolve(answer); }); }); } async function confirm (question, rejectionMessage, expectedAnswers = ['yes', 'y']) { const answer = await ask(question); if (!expectedAnswers.includes(answer)) { throw new Error(rejectionMessage); } return true; } module.exports = { confirm }; <|start_filename|>src/models/application.js<|end_filename|> 'use strict'; const _ = require('lodash'); const application = require('@clevercloud/client/cjs/api/v2/application.js'); const autocomplete = require('cliparse').autocomplete; const product = require('@clevercloud/client/cjs/api/v2/product.js'); const AppConfiguration = require('./app_configuration.js'); const Interact = require('./interact.js'); const Logger = require('../logger.js'); const Organisation = require('./organisation.js'); const User = require('./user.js'); const { sendToApi } = require('../models/send-to-api.js'); function listAvailableTypes () { return autocomplete.words(['docker', 'elixir', 'go', 'gradle', 'haskell', 'jar', 'maven', 'node', 'php', 'play1', 'play2', 'python', 'ruby', 'rust', 'sbt', 'static-apache', 'war']); }; function listAvailableZones () { return autocomplete.words(['par', 'mtl']); }; function listAvailableAliases () { return AppConfiguration.loadApplicationConf().then(({ apps }) => autocomplete.words(_.map(apps, 'alias'))); }; function listAvailableFlavors () { return ['pico', 'nano', 'XS', 'S', 'M', 'L', 'XL', '2XL', '3XL']; }; async function getId (ownerId, dependency) { if (dependency.app_id) { return dependency.app_id; } const app = await getByName(ownerId, dependency.app_name); return app.id; }; async function getInstanceType (type) { // TODO: We should be able to use it without {} const types = await product.getAvailableInstances({}).then(sendToApi); const enabledTypes = types.filter((t) => t.enabled); const matchingVariants = enabledTypes.filter((t) => t.variant != null && t.variant.slug === type); const instanceVariant = _.sortBy(matchingVariants, 'version').reverse()[0]; if (instanceVariant == null) { throw new Error(type + ' type does not exist.'); } return instanceVariant; }; async function create (name, typeName, region, orgaIdOrName, github) { Logger.debug('Create the application…'); const ownerId = (orgaIdOrName != null) ? await Organisation.getId(orgaIdOrName) : await User.getCurrentId(); const instanceType = await getInstanceType(typeName); const newApp = { deploy: 'git', description: name, instanceType: instanceType.type, instanceVersion: instanceType.version, instanceVariant: instanceType.variant.id, maxFlavor: instanceType.defaultFlavor.name, maxInstances: 1, minFlavor: instanceType.defaultFlavor.name, minInstances: 1, name: name, zone: region, }; if (github != null) { newApp.oauthService = 'github'; newApp.oauthApp = github; } return application.create({ id: ownerId }, newApp).then(sendToApi); }; async function deleteApp (addDetails, skipConfirmation) { Logger.debug('Deleting app: ' + addDetails.name + ' (' + addDetails.appId + ')'); if (!skipConfirmation) { await Interact.confirm( `Deleting the application ${addDetails.name} can't be undone, please type '${addDetails.name}' to confirm: `, 'No confirmation, aborting application deletion', [addDetails.name], ); } return application.remove({ id: addDetails.ownerId, appId: addDetails.appId }).then(sendToApi); }; function getApplicationByName (apps, name) { const filteredApps = apps.filter((app) => app.name === name); if (filteredApps.length === 1) { return filteredApps[0]; } else if (filteredApps.length === 0) { throw new Error('Application not found'); } throw new Error('Ambiguous application name'); }; async function getByName (ownerId, name) { const apps = await application.getAll({ id: ownerId }).then(sendToApi); return getApplicationByName(apps, name); }; function get (ownerId, appId) { Logger.debug(`Get information for the app: ${appId}`); return application.get({ id: ownerId, appId }).then(sendToApi); }; function getFromSelf (appId) { Logger.debug(`Get information for the app: ${appId}`); // /self differs from /organisations only for this one: // it fallbacks to the organisations of which the user // is a member, if it doesn't belong to Personal Space. return application.get({ appId }).then(sendToApi); }; async function linkRepo (app, orgaIdOrName, alias, ignoreParentConfig) { Logger.debug(`Linking current repository to the app: ${app.app_id || app.app_name}`); const ownerId = (orgaIdOrName != null) ? await Organisation.getId(orgaIdOrName) : await User.getCurrentId(); const appData = (app.app_id != null) ? await getFromSelf(app.app_id) : await getByName(ownerId, app.app_name); return AppConfiguration.addLinkedApplication(appData, alias, ignoreParentConfig); }; function unlinkRepo (alias) { Logger.debug(`Unlinking current repository from the app: ${alias}`); return AppConfiguration.removeLinkedApplication(alias); }; function redeploy (ownerId, appId, commit, withoutCache) { Logger.debug(`Redeploying the app: ${appId}`); const useCache = (withoutCache) ? 'no' : null; return application.redeploy({ id: ownerId, appId, commit, useCache }).then(sendToApi); }; function mergeScalabilityParameters (scalabilityParameters, instance) { const flavors = listAvailableFlavors(); if (scalabilityParameters.minFlavor) { instance.minFlavor = scalabilityParameters.minFlavor; if (flavors.indexOf(instance.minFlavor) > flavors.indexOf(instance.maxFlavor)) { instance.maxFlavor = instance.minFlavor; } } if (scalabilityParameters.maxFlavor) { instance.maxFlavor = scalabilityParameters.maxFlavor; if (flavors.indexOf(instance.minFlavor) > flavors.indexOf(instance.maxFlavor) && scalabilityParameters.minFlavor == null) { instance.minFlavor = instance.maxFlavor; } } if (scalabilityParameters.minInstances) { instance.minInstances = scalabilityParameters.minInstances; if (instance.minInstances > instance.maxInstances) { instance.maxInstances = instance.minInstances; } } if (scalabilityParameters.maxInstances) { instance.maxInstances = scalabilityParameters.maxInstances; if (instance.minInstances > instance.maxInstances && scalabilityParameters.minInstances == null) { instance.minInstances = instance.maxInstances; } } return instance; }; async function setScalability (appId, ownerId, scalabilityParameters, buildFlavor) { Logger.info('Scaling the app: ' + appId); const app = await application.get({ id: ownerId, appId }).then(sendToApi); const instance = _.cloneDeep(app.instance); instance.minFlavor = instance.minFlavor.name; instance.maxFlavor = instance.maxFlavor.name; const newConfig = mergeScalabilityParameters(scalabilityParameters, instance); if (buildFlavor != null) { newConfig.separateBuild = (buildFlavor !== 'disabled'); if (buildFlavor !== 'disabled') { newConfig.buildFlavor = buildFlavor; } else { Logger.info('No build size given, disabling dedicated build instance'); } } return application.update({ id: ownerId, appId }, newConfig).then(sendToApi); }; async function listDependencies (ownerId, appId, showAll) { const applicationDeps = await application.getAllDependencies({ id: ownerId, appId }).then(sendToApi); if (!showAll) { return applicationDeps; } const allApps = await application.getAll({ id: ownerId }).then(sendToApi); const applicationDepsIds = applicationDeps.map((app) => app.id); return allApps.map((app) => { const isLinked = applicationDepsIds.includes(app.id); return { ...app, isLinked }; }); } async function link (ownerId, appId, dependency) { const dependencyId = await getId(ownerId, dependency); return application.addDependency({ id: ownerId, appId, dependencyId }).then(sendToApi); }; async function unlink (ownerId, appId, dependency) { const dependencyId = await getId(ownerId, dependency); return application.removeDependency({ id: ownerId, appId, dependencyId }).then(sendToApi); }; module.exports = { create, deleteApp, get, link, linkRepo, listAvailableAliases, listAvailableFlavors, listAvailableTypes, listAvailableZones, listDependencies, __mergeScalabilityParameters: mergeScalabilityParameters, redeploy, setScalability, unlink, unlinkRepo, }; <|start_filename|>src/commands/stop.js<|end_filename|> 'use strict'; const AppConfig = require('../models/app_configuration.js'); const application = require('@clevercloud/client/cjs/api/v2/application.js'); const Logger = require('../logger.js'); const { sendToApi } = require('../models/send-to-api.js'); async function stop (params) { const { alias } = params.options; const { ownerId, appId } = await AppConfig.getAppDetails({ alias }); await application.undeploy({ id: ownerId, appId }).then(sendToApi); Logger.println('App successfully stopped!'); } module.exports = { stop }; <|start_filename|>spec/configuration.spec.js<|end_filename|> 'use strict'; const path = require('path'); const { expect } = require('chai'); describe('configuration', () => { it('should retrieve configuration in a JSON file', async () => { const { conf, loadOAuthConf } = require('../src/models/configuration.js'); conf.CONFIGURATION_FILE = path.resolve(__dirname, './configuration.json'); const oauthData = await loadOAuthConf(); expect(oauthData.token).to.equal('aaaa'); expect(oauthData.secret).to.equal('bbbb'); }); it('should return an empty configuration if the configuration file does not exist', async () => { const { conf, loadOAuthConf } = require('../src/models/configuration.js'); conf.CONFIGURATION_FILE = path.resolve(__dirname, './configuration-that-does-not-exist.json'); const oauthData = await loadOAuthConf(); expect(oauthData.token).to.be.an('undefined'); expect(oauthData.secret).to.be.an('undefined'); }); }); <|start_filename|>src/commands/delete.js<|end_filename|> 'use strict'; const AppConfig = require('../models/app_configuration.js'); const Application = require('../models/application.js'); const Logger = require('../logger.js'); async function deleteApp (params) { const { alias, yes: skipConfirmation } = params.options; const appDetails = await AppConfig.getAppDetails({ alias }); await Application.deleteApp(appDetails, skipConfirmation); await Application.unlinkRepo(appDetails.alias); Logger.println('The application has been deleted'); }; module.exports = { deleteApp }; <|start_filename|>src/models/app_configuration.js<|end_filename|> 'use strict'; const { promises: fs } = require('fs'); const path = require('path'); const _ = require('lodash'); const slugify = require('slugify'); const Logger = require('../logger.js'); const User = require('./user.js'); const { conf } = require('./configuration.js'); // TODO: Maybe use fs-utils findPath() async function loadApplicationConf (ignoreParentConfig = false, pathToFolder) { if (pathToFolder == null) { pathToFolder = path.dirname(conf.APP_CONFIGURATION_FILE); } const fileName = path.basename(conf.APP_CONFIGURATION_FILE); const fullPath = path.join(pathToFolder, fileName); Logger.debug('Loading app configuration from ' + fullPath); try { const contents = await fs.readFile(fullPath); return JSON.parse(contents); } catch (error) { Logger.info('Cannot load app configuration from ' + conf.APP_CONFIGURATION_FILE + ' (' + error + ')'); if (ignoreParentConfig || path.parse(pathToFolder).root === pathToFolder) { return { apps: [] }; } return loadApplicationConf(ignoreParentConfig, path.normalize(path.join(pathToFolder, '..'))); } }; async function addLinkedApplication (appData, alias, ignoreParentConfig) { const currentConfig = await loadApplicationConf(ignoreParentConfig); const appEntry = { app_id: appData.id, org_id: appData.ownerId, deploy_url: appData.deployment.httpUrl || appData.deployment.url, name: appData.name, alias: alias || slugify(appData.name), }; const isPresent = currentConfig.apps.find((app) => app.app_id === appEntry.app_id) != null; // ToDo see what to do when there is a conflict between an existing entry // and the entry we want to add (same app_id, different other values) if (!isPresent) { currentConfig.apps.push(appEntry); } return persistConfig(currentConfig); }; async function removeLinkedApplication (alias) { const currentConfig = await loadApplicationConf(); const newConfig = { ...currentConfig, apps: currentConfig.apps.filter((appEntry) => appEntry.alias !== alias), }; return persistConfig(newConfig); }; function findApp (config, alias) { if (_.isEmpty(config.apps)) { throw new Error('There are no applications linked. You can add one with `clever link`'); } if (alias != null) { const [appByAlias, secondAppByAlias] = _.filter(config.apps, { alias }); if (appByAlias == null) { throw new Error(`There are no applications matching alias ${alias}`); } if (secondAppByAlias != null) { throw new Error(`There are several applications matching alias ${alias}. This should not happen, your \`.clever.json\` should be fixed.`); } return appByAlias; } if (config.default != null) { const defaultApp = _.find(config.apps, { app_id: config.default }); if (defaultApp == null) { throw new Error('The default application is not listed anymore. This should not happen, your `.clever.json` should be fixed.'); } return defaultApp; } if (config.apps.length === 1) { return config.apps[0]; } const aliases = _.map(config.apps, 'alias').join(', '); throw new Error(`Several applications are linked. You can specify one with the "--alias" option. Run "clever applications" to list linked applications. Available aliases: ${aliases}`); } async function getAppDetails ({ alias }) { const config = await loadApplicationConf(); const app = findApp(config, alias); const ownerId = (app.org_id != null) ? app.org_id : await User.getCurrentId(); return { appId: app.app_id, ownerId: ownerId, deployUrl: app.deploy_url, name: app.name, alias: app.alias, }; }; function persistConfig (modifiedConfig) { const jsonContents = JSON.stringify(modifiedConfig, null, 2); return fs.writeFile(conf.APP_CONFIGURATION_FILE, jsonContents); }; async function setDefault (alias) { const config = await loadApplicationConf(); const app = findApp(config, alias); const newConfig = { ...config, default: app.app_id }; return persistConfig(newConfig); } module.exports = { loadApplicationConf, addLinkedApplication, removeLinkedApplication, findApp, getAppDetails, setDefault, }; <|start_filename|>src/commands/scale.js<|end_filename|> 'use strict'; const AppConfig = require('../models/app_configuration.js'); const Application = require('../models/application.js'); const Logger = require('../logger.js'); function validateOptions (options) { let { flavor, 'min-flavor': minFlavor, 'max-flavor': maxFlavor } = options; let { instances, 'min-instances': minInstances, 'max-instances': maxInstances, 'build-flavor': buildFlavor } = options; if ([flavor, minFlavor, maxFlavor, instances, minInstances, maxInstances, buildFlavor].every((v) => v == null)) { throw new Error('You should provide at least 1 option'); } if (flavor != null) { if (minFlavor != null || maxFlavor != null) { throw new Error('You can\'t use --flavor and --min-flavor or --max-flavor at the same time'); } minFlavor = flavor; maxFlavor = flavor; } if (instances != null) { if (minInstances != null || maxInstances != null) { throw new Error('You can\'t use --instances and --min-instances or --max-instances at the same time'); } minInstances = instances; maxInstances = instances; } if (minInstances != null && maxInstances != null && minInstances > maxInstances) { throw new Error('min-instances can\'t be greater than max-instances'); } if (minFlavor != null && maxFlavor != null) { const minFlavorIndex = Application.listAvailableFlavors().indexOf(minFlavor); const maxFlavorIndex = Application.listAvailableFlavors().indexOf(maxFlavor); if (minFlavorIndex > maxFlavorIndex) { throw new Error('min-flavor can\'t be a greater flavor than max-flavor'); } } return { minFlavor, maxFlavor, minInstances, maxInstances, buildFlavor }; } async function scale (params) { const { alias } = params.options; const { minFlavor, maxFlavor, minInstances, maxInstances, buildFlavor } = validateOptions(params.options); const { ownerId, appId } = await AppConfig.getAppDetails({ alias }); await Application.setScalability(appId, ownerId, { minFlavor, maxFlavor, minInstances, maxInstances, }, buildFlavor); Logger.println('App rescaled successfully'); }; module.exports = { scale }; <|start_filename|>src/commands/logout.js<|end_filename|> 'use strict'; const Logger = require('../logger.js'); const { conf, writeOAuthConf } = require('../models/configuration.js'); async function logout () { // write empty object await writeOAuthConf({}); Logger.println(`${conf.CONFIGURATION_FILE} has been updated.`); } module.exports = { logout }; <|start_filename|>src/commands/applications.js<|end_filename|> 'use strict'; const colors = require('colors/safe'); const AppConfig = require('../models/app_configuration.js'); const Logger = require('../logger.js'); async function list (params) { const { 'only-aliases': onlyAliases } = params.options; const { apps } = await AppConfig.loadApplicationConf(); const formattedApps = formatApps(apps, onlyAliases); Logger.println(formattedApps); }; function formatApps (apps, onlyAliases) { if (onlyAliases) { return apps.map((a) => a.alis).join('\n'); } return apps .map((app) => { return [ `Application ${app.name}`, ` alias: ${colors.bold(app.alias)}`, ` id: ${app.app_id}`, ` deployment url: ${app.deploy_url}`].join('\n'); }) .join('\n\n'); } module.exports = { list }; <|start_filename|>src/commands/addon.js<|end_filename|> 'use strict'; const _ = require('lodash'); const colors = require('colors/safe'); const Addon = require('../models/addon.js'); const AppConfig = require('../models/app_configuration.js'); const formatTable = require('../format-table')(); const Logger = require('../logger.js'); const Organisation = require('../models/organisation.js'); const User = require('../models/user.js'); const { parseAddonOptions } = require('../models/addon.js'); async function list (params) { const { org: orgaIdOrName } = params.options; const ownerId = await Organisation.getId(orgaIdOrName); const addons = await Addon.list(ownerId); const formattedAddons = addons.map((addon) => { return [ addon.plan.name + ' ' + addon.provider.name, addon.region, colors.bold.green(addon.name), addon.id, ]; }); Logger.println(formatTable(formattedAddons)); } async function create (params) { const [providerName, name] = params.args; const { link: linkedAppAlias, plan: planName, region, yes: skipConfirmation, org: orgaIdOrName } = params.options; const version = params.options['addon-version']; const addonOptions = parseAddonOptions(params.options.option); const ownerId = (orgaIdOrName != null) ? await Organisation.getId(orgaIdOrName) : await User.getCurrentId(); if (linkedAppAlias != null) { const linkedAppData = await AppConfig.getAppDetails({ alias: linkedAppAlias }); if (orgaIdOrName != null && linkedAppData.ownerId !== ownerId) { Logger.warn('The specified application does not belong to the specified organisation. Ignoring the `--org` option'); } const newAddon = await Addon.create({ ownerId: linkedAppData.ownerId, name, providerName, planName, region, skipConfirmation, version, addonOptions, }); await Addon.link(linkedAppData.ownerId, linkedAppData.appId, { addon_id: newAddon.id }); Logger.println(`Addon ${name} (id: ${newAddon.id}) successfully created and linked to the application`); } else { const newAddon = await Addon.create({ ownerId, name, providerName, planName, region, skipConfirmation, version, addonOptions }); Logger.println(`Addon ${name} (id: ${newAddon.id}) successfully created`); } } async function deleteAddon (params) { const { yes: skipConfirmation, org: orgaIdOrName } = params.options; const [addon] = params.args; const ownerId = await Organisation.getId(orgaIdOrName); await Addon.delete(ownerId, addon, skipConfirmation); Logger.println(`Addon ${addon.addon_id || addon.addon_name} successfully deleted`); } async function rename (params) { const [addon, newName] = params.args; const { org: orgaIdOrName } = params.options; const ownerId = await Organisation.getId(orgaIdOrName); await Addon.rename(ownerId, addon, newName); Logger.println(`Addon ${addon.addon_id || addon.addon_name} successfully renamed to ${newName}`); } async function listProviders () { const providers = await Addon.listProviders(); const formattedProviders = providers.map((provider) => { return [ colors.bold(provider.id), provider.name, provider.shortDesc || '', ]; }); Logger.println(formatTable(formattedProviders)); } async function showProvider (params) { const [providerName] = params.args; const provider = await Addon.getProvider(providerName); const providerInfos = await Addon.getProviderInfos(providerName); const providerPlans = provider.plans.sort((a, b) => a.price - b.price); Logger.println(colors.bold(provider.id)); Logger.println(`${provider.name}: ${provider.shortDesc}`); Logger.println(); Logger.println(`Available regions: ${provider.regions.join(', ')}`); Logger.println(); Logger.println('Available plans'); providerPlans.forEach((plan) => { Logger.println(`Plan ${colors.bold(plan.slug)}`); _(plan.features) .sortBy('name') .forEach(({ name, value }) => Logger.println(` ${name}: ${value}`)); if (providerInfos != null) { const planType = plan.features.find(({ name }) => name.toLowerCase() === 'type'); if (planType != null && planType.value.toLowerCase() === 'dedicated') { const planVersions = Object.keys(providerInfos.dedicated); const versions = planVersions.map((version) => { if (version === providerInfos.defaultDedicatedVersion) { return `${version} (default)`; } else { return version; } }); Logger.println(` Available versions: ${versions.join(', ')}`); planVersions.forEach((version) => { const features = providerInfos.dedicated[version].features; Logger.println(` Options for version ${version}:`); features.forEach(({ name, enabled }) => { Logger.println(` ${name}: default=${enabled}`); }); }); } } }); } module.exports = { list, create, delete: deleteAddon, rename, listProviders, showProvider, }; <|start_filename|>src/models/variables.js<|end_filename|> 'use strict'; const _countBy = require('lodash/countBy.js'); const readline = require('readline'); const { ERROR_TYPES, parseRaw, toNameValueObject, validateName } = require('@clevercloud/client/cjs/utils/env-vars.js'); function readStdin () { return new Promise((resolve, reject) => { const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: false, }); const lines = []; rl.on('line', (line) => { lines.push(line); }); rl.on('close', () => { const text = lines.join('\n'); resolve(text); }); rl.on('error', reject); }); } // The JSON input format for variables is: // an array of objects, each having: // a "name" property with a string and value // a "value" property with a string and value // TODO: This should be moved and unit tested in the clever-client repo function parseFromJson (rawStdin) { let variables; try { variables = JSON.parse(rawStdin); } catch (e) { throw new Error(`Error when parsing JSON input: ${e.message}`); } if (!Array.isArray(variables) || variables.some((entry) => typeof entry !== 'object')) { throw new Error('The input was valid JSON but it does not follow the correct format. It must be an array of objects.'); } const someEntriesDontHaveNameAndValueAsString = variables.some(({ name, value }) => { return (typeof name !== 'string') || (typeof value !== 'string'); }); if (someEntriesDontHaveNameAndValueAsString) { throw new Error('The input was a valid JSON array of objects but all entries must have properties "name" and "value" of type string. Ex: { "name": "THE_NAME", "value": "the value" }'); } const namesOccurences = _countBy(variables, 'name'); const duplicatedNames = Object .entries(namesOccurences) .filter(([name, count]) => count > 1) .map(([name]) => `"${name}"`) .join(', '); if (duplicatedNames.length !== 0) { throw new Error(`Some variable names defined multiple times: ${duplicatedNames}`); } const invalidNames = variables .filter(({ name }) => !validateName(name)) .map(({ name }) => `"${name}"`) .join(', '); if (invalidNames.length !== 0) { throw new Error(`Some variable names are invalid: ${invalidNames}`); } return toNameValueObject(variables); } function parseFromNameEqualsValue (rawStdin) { const { variables, errors } = parseRaw(rawStdin); if (errors.length !== 0) { const formattedErrors = errors .map(({ type, name, pos }) => { if (type === ERROR_TYPES.INVALID_NAME) { return `line ${pos.line}: ${name} is not a valid variable name`; } if (type === ERROR_TYPES.DUPLICATED_NAME) { return `line ${pos.line}: be careful, the name ${name} is already defined`; } if (type === ERROR_TYPES.INVALID_LINE) { return `line ${pos.line}: this line is not valid, the correct pattern is: NAME="VALUE"`; } if (type === ERROR_TYPES.INVALID_VALUE) { return `line ${pos.line}: the value is not valid, if you use quotes, you need to escape them like this: \\" or quote the whole value.`; } return 'Unknown error in your input'; }).join('\n'); throw new Error(formattedErrors); } return toNameValueObject(variables); } async function readVariablesFromStdin (format) { const rawStdin = await readStdin(); switch (format) { case 'name-equals-value': return parseFromNameEqualsValue(rawStdin); case 'json': return parseFromJson(rawStdin); default: throw new Error('Unrecognized environment input format. Available formats are \'name-equals-value\' and \'json\''); } } module.exports = { readVariablesFromStdin, }; <|start_filename|>src/models/drain.js<|end_filename|> 'use strict'; const autocomplete = require('cliparse').autocomplete; const DRAIN_TYPES = [ { id: 'TCPSyslog' }, { id: 'UDPSyslog' }, { id: 'HTTP', credentials: 'OPTIONAL' }, { id: 'ElasticSearch', credentials: 'MANDATORY' }, { id: 'DatadogHTTP' }, ]; function createDrainBody (appId, drainTargetURL, drainTargetType, drainTargetCredentials, drainTargetConfig) { if (!authorizeDrainCreation(drainTargetType, drainTargetCredentials)) { throw new Error("Credentials are: optional for HTTP, mandatory for ElasticSearch and TCPSyslog/UDPSyslog don't need them."); } const body = { url: drainTargetURL, drainType: drainTargetType, }; if (credentialsExist(drainTargetCredentials)) { body.credentials = { username: drainTargetCredentials.username || '', password: drainTargetCredentials.password || '', }; } return body; } function authorizeDrainCreation (drainTargetType, drainTargetCredentials) { if (drainTypeExists(drainTargetType)) { // retrieve creds for drain type ('mandatory', 'optional', undefined) const status = credentialsStatus(drainTargetType).credentials; if (status === 'MANDATORY') { return credentialsExist(drainTargetCredentials); } if (status === 'OPTIONAL') { return true; } return credentialsEmpty(drainTargetCredentials); } } function credentialsStatus (drainTargetType) { return DRAIN_TYPES.find(({ id }) => id === drainTargetType); } function drainTypeExists (drainTargetType) { return DRAIN_TYPES.some(({ id }) => id === drainTargetType); } function credentialsExist ({ username, password }) { return username != null && password != null; } function credentialsEmpty ({ username, password }) { return username == null && password == null; } function listDrainTypes () { return autocomplete.words(DRAIN_TYPES.map((type) => type.id)); } module.exports = { createDrainBody, authorizeDrainCreation, listDrainTypes, }; <|start_filename|>src/commands/makeDefault.js<|end_filename|> 'use strict'; const AppConfig = require('../models/app_configuration.js'); const Logger = require('../logger.js'); async function makeDefault (params) { const [alias] = params.args; await AppConfig.setDefault(alias); Logger.println(`The application ${alias} has been set as default`); }; module.exports = { makeDefault }; <|start_filename|>src/models/utils.js<|end_filename|> 'use strict'; // Inspirations: // https://github.com/sindresorhus/p-defer/blob/master/index.js // https://github.com/ljharb/promise-deferred/blob/master/index.js // When you mix async/await APIs with event emitters callbacks, it's hard to keep a proper error flow without a good old deferred. class Deferred { constructor () { this.promise = new Promise((resolve, reject) => { this.resolve = resolve; this.reject = reject; }); } } module.exports = { Deferred }; <|start_filename|>src/commands/cancel-deploy.js<|end_filename|> 'use strict'; const AppConfig = require('../models/app_configuration.js'); const Logger = require('../logger.js'); const { getAllDeployments, cancelDeployment } = require('@clevercloud/client/cjs/api/v2/application.js'); const { sendToApi } = require('../models/send-to-api.js'); async function cancelDeploy (params) { const { alias } = params.options; const { ownerId, appId } = await AppConfig.getAppDetails({ alias }); const deployments = await getAllDeployments({ id: ownerId, appId, limit: 1 }).then(sendToApi); if (deployments.length === 0 || (deployments[0].action !== 'DEPLOY' || deployments[0].state !== 'WIP')) { throw new Error('There is no ongoing deployment for this application'); } const deploymentId = deployments[0].id; await cancelDeployment({ id: ownerId, appId, deploymentId }).then(sendToApi); Logger.println('Deployment cancelled!'); }; module.exports = { cancelDeploy }; <|start_filename|>src/commands/console.js<|end_filename|> 'use strict'; const AppConfig = require('../models/app_configuration.js'); const Logger = require('../logger.js'); const openPage = require('opn'); async function openConsole (params) { const { alias } = params.options; const { ownerId, appId } = await AppConfig.getAppDetails({ alias }); Logger.println('Opening the console in your browser'); const prefixPath = (ownerId.startsWith('user_')) ? 'users/me' : `organisations/${ownerId}`; const url = `https://console.clever-cloud.com/${prefixPath}/applications/${appId}`; await openPage(url, { wait: false }); } module.exports = { openConsole }; <|start_filename|>src/commands/accesslogs.js<|end_filename|> 'use strict'; const { getAccessLogsFromWarp10InBatches, getContinuousAccessLogsFromWarp10 } = require('@clevercloud/client/cjs/access-logs.js'); const { getWarp10AccessLogsToken } = require('@clevercloud/client/cjs/api/v2/warp-10.js'); const { ONE_HOUR_MICROS, ONE_SECOND_MICROS, toMicroTimestamp } = require('@clevercloud/client/cjs/utils/date.js'); const Addon = require('../models/addon.js'); const AppConfig = require('../models/app_configuration.js'); const Logger = require('../logger.js'); const { getFormatter } = require('../models/accesslogs.js'); const { sendToApi, sendToWarp10 } = require('../models/send-to-api.js'); const CONTINUOUS_DELAY = ONE_SECOND_MICROS * 5; async function accessLogs (params) { const { alias, format, before, after, addon: addonId, follow } = params.options; const { ownerId, appId, realAddonId } = await getIds(addonId, alias); const to = (before != null) ? toMicroTimestamp(before.toISOString()) : toMicroTimestamp(); const from = (after != null) ? toMicroTimestamp(after.toISOString()) : to - ONE_HOUR_MICROS; const warpToken = await getWarp10AccessLogsToken({ orgaId: ownerId }).then(sendToApi); if (follow && (before != null || after != null)) { Logger.warn('Access logs are displayed continuously with -f/--follow therefore --before and --after are ignored.'); } const emitter = follow ? getContinuousAccessLogsFromWarp10({ appId, realAddonId, warpToken, delay: CONTINUOUS_DELAY }, sendToWarp10) : getAccessLogsFromWarp10InBatches({ appId, realAddonId, from, to, warpToken }, sendToWarp10); const formatLogLine = getFormatter(format, addonId != null); emitter.on('data', (data) => { data.forEach((l) => Logger.println(formatLogLine(l))); }); return new Promise((resolve, reject) => { emitter.on('error', reject); }); } async function getIds (addonId, alias) { if (addonId != null) { const addon = await Addon.findById(addonId); return { ownerId: addon.orgaId, realAddonId: addon.realId, }; } return AppConfig.getAppDetails({ alias }); } module.exports = { accessLogs }; <|start_filename|>src/commands/published-config.js<|end_filename|> 'use strict'; const AppConfig = require('../models/app_configuration.js'); const Logger = require('../logger.js'); const variables = require('../models/variables.js'); const { sendToApi } = require('../models/send-to-api.js'); const { toNameEqualsValueString, validateName } = require('@clevercloud/client/cjs/utils/env-vars.js'); const application = require('@clevercloud/client/cjs/api/v2/application.js'); async function list (params) { const { alias } = params.options; const { ownerId, appId } = await AppConfig.getAppDetails({ alias }); const publishedConfigs = await application.getAllExposedEnvVars({ id: ownerId, appId }).then(sendToApi); const pairs = Object.entries(publishedConfigs) .map(([name, value]) => ({ name, value })); Logger.println('# Published configs'); Logger.println(toNameEqualsValueString(pairs)); }; async function set (params) { const [varName, varValue] = params.args; const { alias } = params.options; const nameIsValid = validateName(varName); if (!nameIsValid) { throw new Error(`Published config name ${varName} is invalid`); } const { ownerId, appId } = await AppConfig.getAppDetails({ alias }); const publishedConfigs = await application.getAllExposedEnvVars({ id: ownerId, appId }).then(sendToApi); publishedConfigs[varName] = varValue; await application.updateAllExposedEnvVars({ id: ownerId, appId }, publishedConfigs).then(sendToApi); Logger.println('Your published config item has been successfully saved'); }; async function rm (params) { const [varName] = params.args; const { alias } = params.options; const { ownerId, appId } = await AppConfig.getAppDetails({ alias }); const publishedConfigs = await application.getAllExposedEnvVars({ id: ownerId, appId }).then(sendToApi); delete publishedConfigs[varName]; await application.updateAllExposedEnvVars({ id: ownerId, appId }, publishedConfigs).then(sendToApi); Logger.println('Your published config item has been successfully removed'); }; async function importEnv (params) { const { alias, json } = params.options; const format = json ? 'json' : 'name-equals-value'; const { ownerId, appId } = await AppConfig.getAppDetails({ alias }); const publishedConfigs = await variables.readVariablesFromStdin(format); await application.updateAllExposedEnvVars({ id: ownerId, appId }, publishedConfigs).then(sendToApi); Logger.println('Your published configs have been set'); }; module.exports = { list, set, rm, importEnv }; <|start_filename|>src/commands/ssh.js<|end_filename|> 'use strict'; const { spawn } = require('child_process'); const AppConfig = require('../models/app_configuration.js'); const { conf } = require('../models/configuration.js'); async function ssh (params) { const { alias, 'identity-file': identityFile } = params.options; const { appId } = await AppConfig.getAppDetails({ alias }); const sshParams = ['-t', conf.SSH_GATEWAY, appId]; if (identityFile != null) { sshParams.push('-i', identityFile); } await new Promise((resolve, reject) => { // TODO: we should catch errors const sshProcess = spawn('ssh', sshParams, { stdio: 'inherit' }); sshProcess.on('exit', resolve); sshProcess.on('error', reject); }); } module.exports = { ssh }; <|start_filename|>spec/scale.spec.js<|end_filename|> 'use strict'; var _ = require("lodash"); var expect = require('chai').expect; var Application = require("../src/models/application.js"); var defaultInstance = { minFlavor: "S", maxFlavor: "S", minInstances: 5, maxInstances: 5 }; var defaultScalabilityParameters = { minFlavor: null, maxFlavor: null, minInstances: null, maxInstances: null }; describe("scale-merge-parameters", function() { it("should scale up max scalability", function() { var instance = _.cloneDeep(defaultInstance); var scalabilityParameters = _.cloneDeep(defaultScalabilityParameters); scalabilityParameters.minFlavor = "M"; instance = Application.__mergeScalabilityParameters(scalabilityParameters, instance); expect(instance.maxFlavor).to.equal("M"); }); it("should scale down min scalability", function() { var instance = _.cloneDeep(defaultInstance); var scalabilityParameters = _.cloneDeep(defaultScalabilityParameters); scalabilityParameters.maxFlavor = "XS"; instance = Application.__mergeScalabilityParameters(scalabilityParameters, instance); expect(instance.minFlavor).to.equal("XS"); }); it("should augment max instances", function() { var instance = _.cloneDeep(defaultInstance); var scalabilityParameters = _.cloneDeep(defaultScalabilityParameters); scalabilityParameters.minInstances = 6; instance = Application.__mergeScalabilityParameters(scalabilityParameters, instance); expect(instance.maxInstances).to.equal(6); }); it("should diminue min instances", function() { var instance = _.cloneDeep(defaultInstance); var scalabilityParameters = _.cloneDeep(defaultScalabilityParameters); scalabilityParameters.maxInstances = 4; instance = Application.__mergeScalabilityParameters(scalabilityParameters, instance); expect(instance.minInstances).to.equal(4); }); }); <|start_filename|>src/commands/link.js<|end_filename|> 'use strict'; const Application = require('../models/application.js'); const Logger = require('../logger.js'); async function link (params) { const [app] = params.args; const { org: orgaIdOrName, alias } = params.options; if (app.app_id != null && orgaIdOrName != null) { Logger.warn('You\'ve specified a unique application ID, organisation option will be ignored'); } await Application.linkRepo(app, orgaIdOrName, alias); Logger.println('Your application has been successfully linked!'); } module.exports = { link }; <|start_filename|>src/commands/unlink.js<|end_filename|> 'use strict'; const AppConfig = require('../models/app_configuration.js'); const Application = require('../models/application.js'); const Logger = require('../logger.js'); async function unlink (params) { const [alias] = params.args; const app = await AppConfig.getAppDetails({ alias }); await Application.unlinkRepo(app.alias); Logger.println('Your application has been successfully unlinked!'); }; module.exports = { unlink }; <|start_filename|>src/models/organisation.js<|end_filename|> 'use strict'; const _ = require('lodash'); const autocomplete = require('cliparse').autocomplete; const AppConfig = require('./app_configuration.js'); const organisation = require('@clevercloud/client/cjs/api/v2/organisation.js'); const { getSummary } = require('@clevercloud/client/cjs/api/v2/user.js'); const { sendToApi } = require('../models/send-to-api.js'); async function getId (orgaIdOrName) { if (orgaIdOrName == null) { return null; } if (orgaIdOrName.orga_id != null) { return orgaIdOrName.orga_id; } return getByName(orgaIdOrName.orga_name) .then((orga) => orga.id); } async function getByName (name) { const fullSummary = await getSummary({}).then(sendToApi); const filteredOrgs = _.filter(fullSummary.organisations, { name }); if (filteredOrgs.length === 0) { throw new Error('Organisation not found'); } if (filteredOrgs.length > 1) { throw new Error('Ambiguous organisation name'); } return filteredOrgs[0]; } async function getNamespaces (params) { const { alias } = params.options; const { ownerId } = await AppConfig.getAppDetails({ alias }); return organisation.getNamespaces({ id: ownerId }).then(sendToApi); } function completeNamespaces () { // Sadly we do not have access to current params in complete as of now const params = { options: {} }; return getNamespaces(params).then(autocomplete.words); }; module.exports = { getId, getNamespaces, completeNamespaces, };
aurrelhebert/clever-tools
<|start_filename|>package.json<|end_filename|> { "name": "styled-breakpoints", "version": "11.1.0", "description": "Simple and powerfull css breakpoints for styled-components and emotion", "main": "index.js", "types": "index.d.ts", "sideEffects": false, "scripts": { "commit": "cross-env git-cz", "test": "cross-env jest --coverage", "test:watch": "cross-env jest --coverage --watch", "lint": "cross-env eslint . --fix.", "pretty": "cross-env prettier './**/**/**.{json,js,ts}' --write", "coverage": "cross-env cat ./coverage/lcov.info | coveralls", "size": "cross-env size-limit", "semantic-release": "cross-env semantic-release", "contributors:add": "cross-env all-contributors add", "contributors:generate": "cross-env all-contributors generate", "prepare": "husky install" }, "license": "MIT", "homepage": "https://github.com/mg901/styled-breakpoints#readme", "repository": { "type": "git", "url": "https://github.com/mg901/styled-breakpoints.git" }, "bugs": { "url": "https://github.com/mg901/styled-breakpoints/issues" }, "author": "<NAME> <<EMAIL>> (https://github.com/mg901)", "keywords": [ "media", "query", "media-query", "media-queries", "styled", "react", "javascript", "css-in-js", "breakpoint", "breakpoints", "css-in-react", "typescript", "styled-media-query", "styled media query", "styled components", "styled-components" ], "publishConfig": { "access": "public" }, "size-limit": [ { "name": "core", "path": "./core", "import": "{ createBreakpoints }", "limit": "792 B" }, { "name": "core + styled-breakpoints", "import": { "index.js": "{ createBreakpoints }", "styled-breakpoints/index.js": "{ up, down, between, only }" }, "limit": "1.53 kB" }, { "name": "styled-breakpoints + react-styled", "import": { "styled-breakpoints/index.js": "{ up, down, between, only }", "react-styled/index.js": "{ useBreakpoint }" }, "limit": "1.74 kB" }, { "name": "styled-breakpoints + react-emotion", "import": { "styled-breakpoints/index.js": "{ up, down, between, only }", "react-emotion/index.js": "{ useBreakpoint }" }, "limit": "1.74 kB" } ], "prettier": { "singleQuote": true, "trailingComma": "es5", "arrowParens": "always" }, "commitlint": { "extends": [ "@commitlint/config-conventional" ] }, "lint-staged": { "*.{j,t}s": [ "eslint --fix", "prettier --write" ] }, "release": { "branch": "master", "plugins": [ "@semantic-release/commit-analyzer", "@semantic-release/release-notes-generator", "@semantic-release/changelog", "@semantic-release/npm", "@semantic-release/git", "@semantic-release/github" ] }, "peerDependencies": { "@emotion/react": "^11.0.0", "react": "^18.x.x", "styled-components": "^5.0.0" }, "peerDependenciesMeta": { "styled-components": { "optional": true }, "react": { "optional": true }, "@emotion/react": { "optional": true } }, "devDependencies": { "@commitlint/cli": "^17.0.0", "@commitlint/config-conventional": "^17.0.0", "@emotion/react": "^11.0.0", "@semantic-release/changelog": "^6.0.0", "@semantic-release/commit-analyzer": "^9.0.1", "@semantic-release/git": "^10.0.0", "@semantic-release/github": "^8.0.0", "@semantic-release/npm": "^9.0.0", "@semantic-release/release-notes-generator": "^10.0.2", "@size-limit/esbuild": "^7.0.8", "@size-limit/file": "^7.0.8", "@size-limit/webpack": "^7.0.1", "all-contributors-cli": "^6.17.4", "commitizen": "^4.2.1", "coveralls": "^3.1.0", "cross-env": "^7.0.2", "cz-conventional-changelog": "^3.3.0", "eslint": "^8.0.1", "eslint-config-airbnb": "19.0.4", "eslint-config-airbnb-base": "^15.0.0", "eslint-config-prettier": "^8.1.0", "eslint-plugin-import": "^2.22.1", "eslint-plugin-jest": "^26.0.0", "eslint-plugin-jsx-a11y": "^6.4.1", "eslint-plugin-prettier": "^4.0.0", "eslint-plugin-react": "^7.21.5", "eslint-plugin-react-hooks": "^4.2.0", "husky": "^7.0.4", "jest": "^28.0.0", "lint-staged": "^13.0.1", "prettier": "^2.1.2", "react": "^18.1.0", "rimraf": "^3.0.2", "size-limit": "^7.0.8", "styled-components": "^5.2.1" } } <|start_filename|>hooks/use-breakpoint.js<|end_filename|> const { useState, useEffect, useMemo } = require('react'); exports.createUseBreakpoint = ({ theme: useTheme }) => (breakpoint) => { const [isBreak, setIsBreak] = useState(null); const mediaQuery = breakpoint({ theme: useTheme(), }); const mq = useMemo( () => typeof window === 'undefined' ? false : window.matchMedia(mediaQuery.replace(/^@media\s*/, '')), [mediaQuery] ); useEffect(() => { const handleChange = (event) => { setIsBreak(event.matches); }; setIsBreak(mq.matches); // Safari < 14 can't use addEventListener on a MediaQueryList // https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryList#Browser_compatibility if (!mq.addEventListener) { // Update the state whenever the media query match state changes mq.addListener(handleChange); // Clean up on unmount and if the query changes return () => { mq.removeListener(handleChange); }; } mq.addEventListener('change', handleChange); return () => { mq.removeEventListener('change', handleChange); }; }, [mq]); return isBreak; }; <|start_filename|>styled-breakpoints/styled-breakpoints.spec.js<|end_filename|> const { createStyledBreakpoints, createTheme, } = require('./styled-breakpoints'); const ERROR_PREFIX = '[styled-breakpoints]: '; const PROPS_WITH_EMPTY_THEME = { theme: {}, }; describe('styled-breakpoints', () => { it('should show a message with invalid names and breakpoint values', () => { const { up } = createStyledBreakpoints(); const props = { theme: { breakpoints: { xs: '0dd9px', sm: '776px', md: '992rem', lg: '20em', xl: 'jflksdjdjkdpx', }, }, }; try { up('sm')(props); } catch (error) { expect(error.message).toEqual( `${ERROR_PREFIX}Check your theme. \`xs: 0dd9px, md: 992rem, lg: 20em, xl: jflksdjdjkdpx,\` are invalid breakpoints. Use only pixels.` ); } }); it('should pick up custom breakpoints from theme', () => { const { up } = createStyledBreakpoints(); const breakpoints = { mobile: '576px', tablet: '768px', desktop: '992px', }; const props = { theme: createTheme(breakpoints), }; Object.entries(breakpoints).forEach(([key, value]) => { expect(up(key)(props)).toEqual(`@media (min-width: ${value})`); }); }); describe('up', () => { let bp; beforeEach(() => { bp = createStyledBreakpoints(); }); it('should render a media query if the screen width is greater than or equal to 576px', () => { expect(bp.up('sm')(PROPS_WITH_EMPTY_THEME)).toEqual( '@media (min-width: 576px)' ); }); it('should render a media query if the screen width is greater than or equal to 576px for portrait orientation', () => { expect(bp.up('sm', 'portrait')(PROPS_WITH_EMPTY_THEME)).toEqual( '@media (min-width: 576px) and (orientation: portrait)' ); }); it('should render a media query if the screen width is greater than or equal to 576px for landscape orientation', () => { expect(bp.up('sm', 'landscape')(PROPS_WITH_EMPTY_THEME)).toEqual( '@media (min-width: 576px) and (orientation: landscape)' ); }); it('should throw an exception if device orientation is not valid', () => { try { bp.up('sm', 'wtf')(PROPS_WITH_EMPTY_THEME); } catch (error) { expect(error.message).toEqual( `${ERROR_PREFIX}\`wtf\` is invalid orientation. Use \`landscape\` or \`portrait\`.` ); } }); }); describe('down', () => { let bp; beforeEach(() => { bp = createStyledBreakpoints(); }); it('should render a media query if the screen width is less or equal to 575.98px', () => { expect(bp.down('sm')(PROPS_WITH_EMPTY_THEME)).toEqual( '@media (max-width: 575.98px)' ); }); it('should render a media query if the screen width is less or equal to 767.98px for portrait orientation', () => { expect(bp.down('sm', 'portrait')(PROPS_WITH_EMPTY_THEME)).toEqual( '@media (max-width: 575.98px) and (orientation: portrait)' ); }); it('should render a media query if the screen width is less or equal to 767.98px for landscape orientation', () => { expect(bp.down('sm', 'landscape')(PROPS_WITH_EMPTY_THEME)).toEqual( '@media (max-width: 575.98px) and (orientation: landscape)' ); }); it('should throw an exception if device orientation is not valid', () => { try { bp.down('sm', 'wtf')(PROPS_WITH_EMPTY_THEME); } catch (error) { expect(error.message).toEqual( `${ERROR_PREFIX}\`wtf\` is invalid orientation. Use \`landscape\` or \`portrait\`.` ); } }); }); describe('between', () => { let bp; beforeEach(() => { bp = createStyledBreakpoints(); }); it('should render a media query if the screen width greater than equal to 576px and less than or equal to 991.98px', () => { expect(bp.between('sm', 'md')(PROPS_WITH_EMPTY_THEME)).toEqual( '@media (min-width: 576px) and (max-width: 767.98px)' ); }); it('should render a media query if the screen width greater than equal to 576px and less than or equal to 991.98px and portrait orientation', () => { expect( bp.between('sm', 'md', 'portrait')(PROPS_WITH_EMPTY_THEME) ).toEqual( '@media (min-width: 576px) and (max-width: 767.98px) and (orientation: portrait)' ); }); it('should render a media query if the screen width greater than equal to 576px and less than or equal to 991.98px and landscape orientation', () => { expect( bp.between('sm', 'md', 'landscape')(PROPS_WITH_EMPTY_THEME) ).toEqual( '@media (min-width: 576px) and (max-width: 767.98px) and (orientation: landscape)' ); }); }); describe('only', () => { let bp; beforeEach(() => { bp = createStyledBreakpoints(); }); it('should render a media query if the screen width greater than equal to 576px and less than or equal to 767.98px', () => { expect(bp.only('sm')(PROPS_WITH_EMPTY_THEME)).toEqual( '@media (min-width: 576px) and (max-width: 767.98px)' ); }); }); describe('integration with other libraries', () => { const TYPOGRAPHIST_KEY = '@typographist/styled'; const PROPS_WITH_TYPOGRAPHIST_THEME = { theme: { [TYPOGRAPHIST_KEY]: { mediaQueries: { mobile: '768px', tablet: '992px', desktop: '1200px', }, }, }, }; it('should pick up custom breakpoints from Typographist theme', () => { const bp = createStyledBreakpoints({ pathToMediaQueries: `${TYPOGRAPHIST_KEY}.mediaQueries`, }); const props = PROPS_WITH_TYPOGRAPHIST_THEME; const mockBreakpoints = [ ['mobile', '768px'], ['tablet', '992px'], ['desktop', '1200px'], ]; mockBreakpoints.forEach(([key, value]) => { expect(bp.up(key)(props)).toEqual(`@media (min-width: ${value})`); }); }); }); });
maxinakenty/styled-breakpoints
<|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/beans/InheritedConfigBeanBViewConfig.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; @ViewOf(value = BeanB.class, genName = "BeanBViewWithInheritedConfig", includePattern = ".*") public class InheritedConfigBeanBViewConfig extends InheritedConfigBaseViewConfig { } <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/beans/ExtraParamsViewConfigure.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.ExtraParam; import io.github.vipcxj.beanknife.runtime.annotations.NewViewProperty; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; @ViewOf(value = SimpleBean.class, genName = "ExtraParamsBeanView") public class ExtraParamsViewConfigure extends IncludeAllBaseConfigure { @NewViewProperty("x") public static Class<?> x(@ExtraParam("x") Class<?> x) { return x; } @NewViewProperty("y") public static String y(@ExtraParam("x") Class<?> x) { return x.getName(); } @NewViewProperty("z") public static ExtraParamsBeanView z(@ExtraParam("z") ExtraParamsBeanView z) { return z; } } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/annotations/UsePropertyConverters.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ ElementType.FIELD, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) public @interface UsePropertyConverters { UsePropertyConverter[] value() default {}; } <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/beans/ExtraProperty2ViewConfigure.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.NewViewProperty; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; @ViewOf(value = SimpleBean.class, genName = "ExtraProperties2BeanView") public class ExtraProperty2ViewConfigure extends ExtraProperty1ViewConfigure { @NewViewProperty("y") private String y; @NewViewProperty("z") private Class<? extends String> z; } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/MethodHideFieldBeanMeta.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedMeta; @GeneratedMeta(targetClass = MethodHideFieldBean.class, configClass = MethodHideFieldBean.class) public class MethodHideFieldBeanMeta { } <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/beans/InheritedConfigBeanAViewConfig.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; @ViewOf(value = BeanA.class, genName = "BeanAViewWithInheritedConfig", includePattern = ".*") public class InheritedConfigBeanAViewConfig extends InheritedConfigBaseViewConfig { } <|start_filename|>beanknife-jpa-examples/src/test/java/io/github/vipcxj/beanknfie/jpa/examples/JpaConfig.java<|end_filename|> package io.github.vipcxj.beanknfie.jpa.examples; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; import java.util.Properties; @Configuration @EnableJpaRepositories @PropertySource("/persistence.properties") @EnableTransactionManagement public class JpaConfig { @Autowired private Environment env; @Bean public DataSource dataSource() { final DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName")); dataSource.setUrl(env.getProperty("jdbc.url")); return dataSource; } @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource()); em.setPackagesToScan("io.github.vipcxj.beanknfie.jpa.examples.models"); em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); em.setJpaProperties(additionalProperties()); return em; } @Bean JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) { JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(entityManagerFactory); return transactionManager; } final Properties additionalProperties() { final Properties hibernateProperties = new Properties(); hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); hibernateProperties.setProperty("hibernate.show_sql", "true"); return hibernateProperties; } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/otherbean/InheritedBeanMeta.java<|end_filename|> package io.github.vipcxj.beanknife.cases.otherbean; import io.github.vipcxj.beanknife.cases.beans.ChangePackageMetaConfig; import io.github.vipcxj.beanknife.cases.beans.InheritedBean; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedMeta; @GeneratedMeta(targetClass = InheritedBean.class, configClass = ChangePackageMetaConfig.class) public class InheritedBeanMeta { public static final String b = "b"; public static final String isProperty = "isProperty"; public static final String isObjectIsProperty = "isObjectIsProperty"; public static final String hideProperty = "hideProperty"; public static final String ABC = "ABC"; public static final String aBC = "aBC"; public static final String _Short = "_Short"; public static final String d = "d"; public static final String f = "f"; public static final String me = "me"; public static final String if_ = "if"; public static final String while_ = "while"; public static final String objectIsProperty = "objectIsProperty"; public static final String TV = "TV"; public static final String iI = "iI"; public static final String _boolean = "_boolean"; public static final String newProperty = "newProperty"; } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/MetaAndViewOfOnDiffBean2View.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedView; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; @GeneratedView(targetClass = MetaAndViewOfOnDiffBean2.class, configClass = MetaAndViewOfOnDiffBean2ViewConfig.class) public class MetaAndViewOfOnDiffBean2View { private String pa; public MetaAndViewOfOnDiffBean2View() { } public MetaAndViewOfOnDiffBean2View( String pa ) { this.pa = pa; } public MetaAndViewOfOnDiffBean2View(MetaAndViewOfOnDiffBean2View source) { this.pa = source.pa; } public MetaAndViewOfOnDiffBean2View(MetaAndViewOfOnDiffBean2 source) { if (source == null) { throw new NullPointerException("The input source argument of the read constructor of class io.github.vipcxj.beanknife.cases.beans.MetaAndViewOfOnDiffBean2View should not be null."); } this.pa = source.getPa(); } public static MetaAndViewOfOnDiffBean2View read(MetaAndViewOfOnDiffBean2 source) { if (source == null) { return null; } return new MetaAndViewOfOnDiffBean2View(source); } public static MetaAndViewOfOnDiffBean2View[] read(MetaAndViewOfOnDiffBean2[] sources) { if (sources == null) { return null; } MetaAndViewOfOnDiffBean2View[] results = new MetaAndViewOfOnDiffBean2View[sources.length]; for (int i = 0; i < sources.length; ++i) { results[i] = read(sources[i]); } return results; } public static List<MetaAndViewOfOnDiffBean2View> read(List<MetaAndViewOfOnDiffBean2> sources) { if (sources == null) { return null; } List<MetaAndViewOfOnDiffBean2View> results = new ArrayList<>(); for (MetaAndViewOfOnDiffBean2 source : sources) { results.add(read(source)); } return results; } public static Set<MetaAndViewOfOnDiffBean2View> read(Set<MetaAndViewOfOnDiffBean2> sources) { if (sources == null) { return null; } Set<MetaAndViewOfOnDiffBean2View> results = new HashSet<>(); for (MetaAndViewOfOnDiffBean2 source : sources) { results.add(read(source)); } return results; } public static Stack<MetaAndViewOfOnDiffBean2View> read(Stack<MetaAndViewOfOnDiffBean2> sources) { if (sources == null) { return null; } Stack<MetaAndViewOfOnDiffBean2View> results = new Stack<>(); for (MetaAndViewOfOnDiffBean2 source : sources) { results.add(read(source)); } return results; } public static <K> Map<K, MetaAndViewOfOnDiffBean2View> read(Map<K, MetaAndViewOfOnDiffBean2> sources) { if (sources == null) { return null; } Map<K, MetaAndViewOfOnDiffBean2View> results = new HashMap<>(); for (Map.Entry<K, MetaAndViewOfOnDiffBean2> source : sources.entrySet()) { results.put(source.getKey(), read(source.getValue())); } return results; } public String getPa() { return this.pa; } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/otherbean/MetaOfFieldBean.java<|end_filename|> package io.github.vipcxj.beanknife.cases.otherbean; import io.github.vipcxj.beanknife.cases.beans.ChangePackageAndNameMetaConfig; import io.github.vipcxj.beanknife.cases.beans.FieldBean; import io.github.vipcxj.beanknife.cases.beans.FieldBeanViewConfig; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedMeta; @GeneratedMeta( targetClass = FieldBean.class, configClass = ChangePackageAndNameMetaConfig.class, proxies = { FieldBeanViewConfig.class } ) public class MetaOfFieldBean { public static final String b = "b"; public static final String c = "c"; public static final String d = "d"; public static class Views { public static final String io_github_vipcxj_beanknife_cases_beans_FieldBeanView = "io.github.vipcxj.beanknife.cases.beans.FieldBeanView"; } } <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/beans/InheritedAnnotationBeanViewConfigure.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.cases.annotations.*; import io.github.vipcxj.beanknife.runtime.annotations.UseAnnotation; @UseAnnotation(TypeAnnotation.class) @UseAnnotation(DocumentedTypeAnnotation.class) @UseAnnotation(InheritableTypeAnnotation.class) @UseAnnotation({ FieldAnnotation1.class, FieldAnnotation2.class }) @UseAnnotation(MethodAnnotation1.class) @UseAnnotation(PropertyAnnotation1.class) public class InheritedAnnotationBeanViewConfigure { } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/ViewOfInNestBean$Bean1Meta.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedMeta; @GeneratedMeta( targetClass = ViewOfInNestBean.Bean1.class, configClass = ViewOfInNestBean.Bean1.class, proxies = { ViewOfInNestBean.Bean1.class } ) public class ViewOfInNestBean$Bean1Meta { public static final String a = "a"; public static final String b = "b"; public static class Views { public static final String io_github_vipcxj_beanknife_cases_beans_ViewOfInNestBean$Bean1View = "io.github.vipcxj.beanknife.cases.beans.ViewOfInNestBean$Bean1View"; } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/IllegalPropertyWithConflictPropertyBeanMeta.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedMeta; @GeneratedMeta(targetClass = IllegalPropertyWithConflictPropertyBean.class, configClass = IllegalPropertyWithConflictPropertyBean.class) public class IllegalPropertyWithConflictPropertyBeanMeta { public static final String if_ = "if_"; public static final String if__ = "if"; public static final String if___ = "if__"; public static final String while_ = "while"; } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/FieldBean.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.ViewMeta; import java.util.Date; @ViewMeta public class FieldBean { private String a; long b; protected Date c; public Number[] d; } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/ViewOfInNestBean$Bean1View.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedView; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; @GeneratedView(targetClass = ViewOfInNestBean.Bean1.class, configClass = ViewOfInNestBean.Bean1.class) public class ViewOfInNestBean$Bean1View { public ViewOfInNestBean$Bean1View() { } public ViewOfInNestBean$Bean1View(ViewOfInNestBean$Bean1View source) { } public ViewOfInNestBean$Bean1View(ViewOfInNestBean.Bean1 source) { if (source == null) { throw new NullPointerException("The input source argument of the read constructor of class io.github.vipcxj.beanknife.cases.beans.ViewOfInNestBean$Bean1View should not be null."); } } public static ViewOfInNestBean$Bean1View read(ViewOfInNestBean.Bean1 source) { if (source == null) { return null; } return new ViewOfInNestBean$Bean1View(source); } public static ViewOfInNestBean$Bean1View[] read(ViewOfInNestBean.Bean1[] sources) { if (sources == null) { return null; } ViewOfInNestBean$Bean1View[] results = new ViewOfInNestBean$Bean1View[sources.length]; for (int i = 0; i < sources.length; ++i) { results[i] = read(sources[i]); } return results; } public static List<ViewOfInNestBean$Bean1View> read(List<ViewOfInNestBean.Bean1> sources) { if (sources == null) { return null; } List<ViewOfInNestBean$Bean1View> results = new ArrayList<>(); for (ViewOfInNestBean.Bean1 source : sources) { results.add(read(source)); } return results; } public static Set<ViewOfInNestBean$Bean1View> read(Set<ViewOfInNestBean.Bean1> sources) { if (sources == null) { return null; } Set<ViewOfInNestBean$Bean1View> results = new HashSet<>(); for (ViewOfInNestBean.Bean1 source : sources) { results.add(read(source)); } return results; } public static Stack<ViewOfInNestBean$Bean1View> read(Stack<ViewOfInNestBean.Bean1> sources) { if (sources == null) { return null; } Stack<ViewOfInNestBean$Bean1View> results = new Stack<>(); for (ViewOfInNestBean.Bean1 source : sources) { results.add(read(source)); } return results; } public static <K> Map<K, ViewOfInNestBean$Bean1View> read(Map<K, ViewOfInNestBean.Bean1> sources) { if (sources == null) { return null; } Map<K, ViewOfInNestBean$Bean1View> results = new HashMap<>(); for (Map.Entry<K, ViewOfInNestBean.Bean1> source : sources.entrySet()) { results.put(source.getKey(), read(source.getValue())); } return results; } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/BeanBMeta.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedMeta; @GeneratedMeta( targetClass = BeanB.class, configClass = BeanB.class, proxies = { ConfigBeanB.class, InheritedConfigBeanBViewConfig.class } ) public class BeanBMeta { public static final String a = "a"; public static final String beanA = "beanA"; public static final String shouldBeRemoved = "shouldBeRemoved"; public static class Views { public static final String io_github_vipcxj_beanknife_cases_beans_BeanBView = "io.github.vipcxj.beanknife.cases.beans.BeanBView"; public static final String io_github_vipcxj_beanknife_cases_beans_BeanBViewWithInheritedConfig = "io.github.vipcxj.beanknife.cases.beans.BeanBViewWithInheritedConfig"; } } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/annotations/ViewOfs.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.TYPE) @Retention(RetentionPolicy.SOURCE) public @interface ViewOfs { ViewOf[] value() default {}; } <|start_filename|>beanknife-core-base/src/main/java/io/github/vipcxj/beanknife/core/utils/TreeUtils.java<|end_filename|> package io.github.vipcxj.beanknife.core.utils; import com.sun.source.tree.*; import com.sun.source.util.TreePath; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import io.github.vipcxj.beanknife.core.models.Context; import javax.lang.model.element.Element; import javax.lang.model.type.TypeMirror; public class TreeUtils { public static String parseMemberSelect(MemberSelectTree tree) { ExpressionTree expression = tree.getExpression(); if (expression.getKind() == Tree.Kind.MEMBER_SELECT) { return parseMemberSelect((MemberSelectTree) expression) + "." + tree.getIdentifier().toString(); } else if (expression.getKind() == Tree.Kind.IDENTIFIER) { IdentifierTree identifierTree = (IdentifierTree) expression; return identifierTree.getName().toString() + "." + tree.getIdentifier().toString(); } else { throw new UnsupportedOperationException("Unsupported tree kind: " + tree.getKind() + "."); } } public static String parseImport(ImportTree importTree) { Tree qualifiedIdentifier = importTree.getQualifiedIdentifier(); if (qualifiedIdentifier.getKind() == Tree.Kind.MEMBER_SELECT) { return parseMemberSelect((MemberSelectTree) qualifiedIdentifier); } else { throw new UnsupportedOperationException("Unsupported tree kind: " + qualifiedIdentifier.getKind() + "."); } } public static String parsePackageName(CompilationUnitTree unit) { ExpressionTree packageName = unit.getPackageName(); if (packageName == null) { return ""; } if (packageName.getKind() == Tree.Kind.IDENTIFIER) { IdentifierTree identifierTree = (IdentifierTree) packageName; return identifierTree.getName().toString(); } else if (packageName.getKind() == Tree.Kind.MEMBER_SELECT) { return parseMemberSelect((MemberSelectTree) packageName); } else { throw new IllegalArgumentException("This is impossible!"); } } @CheckForNull public static CompilationUnitTree getCompilationUnit(@NonNull Context context, @NonNull Element element) { TreePath path = context.getTrees().getPath(element); return path != null ? path.getCompilationUnit() : null; } public static TypeMirror tryGetTypeMirror(@NonNull Context context, @NonNull Element element, @NonNull Tree tree) { TreePath path = context.getTrees().getPath(element); CompilationUnitTree unit = path.getCompilationUnit(); TreePath treePath = context.getTrees().getPath(unit, tree); return context.getTrees().getTypeMirror(treePath); } } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/converters/NullDoubleAsZeroConverter.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.converters; import io.github.vipcxj.beanknife.runtime.PropertyConverter; public class NullDoubleAsZeroConverter implements PropertyConverter<Double, Double> { @Override public Double convert(Double value) { return value != null ? value : 0.0; } @Override public Double convertBack(Double value) { return value; } } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/annotations/internal/GeneratedView.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.annotations.internal; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface GeneratedView { Class<?> targetClass(); Class<?> configClass(); } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/ConverterBean.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; public class ConverterBean { private Long a; private Integer b; public Long getA() { return a; } public Integer getB() { return b; } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/SimpleBean.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; @ViewOf(includePattern=".*") // (1) public class SimpleBean { private String a; private Integer b; private long c; public SimpleBean(String a, Integer b, long c) { this.a = a; this.b = b; this.c = c; } public String getA() { return a; } public Integer getB() { return b; } public long getC() { return c; } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/ChangeNameMetaConfig.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.ViewMeta; @ViewMeta(value = "MetaOfMixedAllBean", of = MixedAllBean.class) public class ChangeNameMetaConfig { } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/MixedAllBean.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.cases.models.AObject; import io.github.vipcxj.beanknife.runtime.annotations.ViewMeta; import java.util.Date; @ViewMeta public class MixedAllBean { protected int a; int b; private long c; private short d; private AObject f; private String _if; private Date _while; boolean isIsProperty; Boolean isObjectIsProperty; public String hideProperty; private int TV; String ABC; private long iI; Date aBC; private boolean _boolean; short _Short; public short getD() { return d; } public AObject getF() { return f; } protected boolean isMe() { return true; } public String getIf() { return _if; } public Date getWhile() { return _while; } public boolean isIsProperty() { return isIsProperty; } public boolean isObjectIsProperty() { return isObjectIsProperty; } private String getHideProperty() { return hideProperty; } public int getTV() { return TV; } public long getiI() { return iI; } public boolean is_boolean() { return _boolean; } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/MethodBean.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.ViewMeta; import java.util.Date; @ViewMeta public class MethodBean { protected Date getNow() { return new Date(); } } <|start_filename|>beanknife-jpa-examples/src/main/java/io/github/vipcxj/beanknfie/jpa/examples/dto/EmployeeInfoConfiguration.java<|end_filename|> package io.github.vipcxj.beanknfie.jpa.examples.dto; import io.github.vipcxj.beanknfie.jpa.examples.models.Employee; import io.github.vipcxj.beanknfie.jpa.examples.models.EmployeeMeta; import io.github.vipcxj.beanknife.runtime.annotations.RemoveViewProperty; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; @ViewOf(Employee.class) @RemoveViewProperty({EmployeeMeta.company, EmployeeMeta.department}) public class EmployeeInfoConfiguration extends BaseDtoConfiguration { } <|start_filename|>beanknife-spring/src/test/java/io/github/vipcxj/beanknife/spring/test/beans/SpringBean.java<|end_filename|> package io.github.vipcxj.beanknife.spring.test.beans; import java.util.Date; public class SpringBean { public Date now() { return new Date(); } } <|start_filename|>beanknife-jpa-examples/src/main/java/io/github/vipcxj/beanknfie/jpa/examples/models/Address.java<|end_filename|> package io.github.vipcxj.beanknfie.jpa.examples.models; import lombok.*; import javax.persistence.Embeddable; @Embeddable @Getter @Setter @NoArgsConstructor @AllArgsConstructor @ToString public class Address { private String city; private String road; private String number; } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/Leaf21BeanMeta.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedMeta; @GeneratedMeta( targetClass = Leaf21Bean.class, configClass = Leaf21Bean.class, proxies = { Leaf21BeanViewConfigure.class } ) public class Leaf21BeanMeta { public static final String a = "a"; public static final String b = "b"; public static final String c = "c"; public static final String d = "d"; public static final String e = "e"; public static class Views { public static final String io_github_vipcxj_beanknife_cases_beans_Leaf21BeanDto = "io.github.vipcxj.beanknife.cases.beans.Leaf21BeanDto"; } } <|start_filename|>beanknife-jpa/src/main/java/module-info.java<|end_filename|> import io.github.vipcxj.beanknife.core.spi.ViewCodeGenerator; import io.github.vipcxj.beanknife.jpa.JpaViewCodeGenerator; module beanknife.jpa { requires beanknife.core; requires beanknife.runtime; requires beanknife.jpa.runtime; requires org.apache.commons.text; requires java.compiler; provides ViewCodeGenerator with JpaViewCodeGenerator; } <|start_filename|>beanknife-core-base/src/test/java/io/github/vipcxj/beanknife/tests/ViewOfProcessorTest.java<|end_filename|> package io.github.vipcxj.beanknife.tests; import io.github.vipcxj.beanknife.core.GeneratedMetaProcessor; import io.github.vipcxj.beanknife.core.ViewMetaProcessor; import io.github.vipcxj.beanknife.core.ViewOfProcessor; import org.junit.Test; import java.util.Arrays; import java.util.Collections; import java.util.List; public class ViewOfProcessorTest { private void testViewCase(List<String> qualifiedClassNames, List<String> targetQualifiedClassNames) { Utils.testViewCase( Arrays.asList(new ViewOfProcessor(), new ViewMetaProcessor(), new GeneratedMetaProcessor()), qualifiedClassNames, targetQualifiedClassNames ); } private void testViewCase(String qualifiedClassName, List<String> targetQualifiedClassNames) { testViewCase( Collections.singletonList(qualifiedClassName), targetQualifiedClassNames ); } private void testViewCase(String qualifiedClassName, String targetQualifiedClassNames) { testViewCase( Collections.singletonList(qualifiedClassName), Collections.singletonList(targetQualifiedClassNames) ); } @Test public void testBeanWithOnlyFields() { testViewCase( "io.github.vipcxj.beanknife.cases.beans.FieldBeanViewConfig", "io.github.vipcxj.beanknife.cases.beans.FieldBeanView" ); } @Test public void testNestGenericBean() { testViewCase( "io.github.vipcxj.beanknife.cases.beans.NestedGenericBean", Arrays.asList( "io.github.vipcxj.beanknife.cases.beans.NestedGenericBeanView", "io.github.vipcxj.beanknife.cases.beans.NestedGenericBean$StaticChildBeanMeta", "io.github.vipcxj.beanknife.cases.beans.NestedGenericBean$StaticChildBeanView", "io.github.vipcxj.beanknife.cases.beans.NestedGenericBean$DynamicChildBeanMeta", "io.github.vipcxj.beanknife.cases.beans.NestedGenericBean$DynamicChildBeanView" ) ); } @Test public void testInheritedViewConfig() { testViewCase( Arrays.asList( "io.github.vipcxj.beanknife.cases.beans.InheritedConfigBeanAViewConfig", "io.github.vipcxj.beanknife.cases.beans.InheritedConfigBeanBViewConfig" ), Arrays.asList( "io.github.vipcxj.beanknife.cases.beans.BeanAViewWithInheritedConfig", "io.github.vipcxj.beanknife.cases.beans.BeanBViewWithInheritedConfig" ) ); } @Test public void testStaticPropertyMethod() { testViewCase( "io.github.vipcxj.beanknife.cases.beans.StaticMethodPropertyBeanViewConfig", "io.github.vipcxj.beanknife.cases.beans.StaticMethodPropertyBeanView" ); } @Test public void testDynamicPropertyMethod() { testViewCase( "io.github.vipcxj.beanknife.cases.beans.DynamicMethodPropertyBeanViewConfig", "io.github.vipcxj.beanknife.cases.beans.DynamicMethodPropertyBeanView" ); } @Test public void testUseAnnotation() { testViewCase( "io.github.vipcxj.beanknife.cases.beans.AnnotationBeanViewConfigure", "io.github.vipcxj.beanknife.cases.beans.AnnotationBeanView" ); } @Test public void testWriteableBean() { testViewCase( "io.github.vipcxj.beanknife.cases.beans.WriteableBeanViewConfigure", "io.github.vipcxj.beanknife.cases.beans.WriteableBeanView" ); } @Test public void testConfigurationInheritance() { testViewCase( "io.github.vipcxj.beanknife.cases.beans.Leaf11BeanViewConfigure", "io.github.vipcxj.beanknife.cases.beans.ViewOfLeaf11Bean" ); } @Test public void testViewPropertyContainerBean() { testViewCase( Arrays.asList( "io.github.vipcxj.beanknife.cases.beans.ViewPropertyBeanViewConfig", "io.github.vipcxj.beanknife.cases.beans.ViewPropertyContainerBeanViewConfig" ), Arrays.asList( "io.github.vipcxj.beanknife.cases.beans.ViewPropertyBeanWithoutParent", "io.github.vipcxj.beanknife.cases.beans.ViewPropertyContainerBeanView" ) ); } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/ViewOfDirectOnBeanMeta.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedMeta; @GeneratedMeta( targetClass = ViewOfDirectOnBean.class, configClass = ViewOfDirectOnBean.class, proxies = { ViewOfDirectOnBean.class } ) public class ViewOfDirectOnBeanMeta { public static final String a = "a"; public static final String b = "b"; public static class Views { public static final String io_github_vipcxj_beanknife_cases_beans_ViewOfDirectOnBeanView = "io.github.vipcxj.beanknife.cases.beans.ViewOfDirectOnBeanView"; } } <|start_filename|>beanknife-jpa/src/main/java/io/github/vipcxj/beanknife/jpa/Helper.java<|end_filename|> package io.github.vipcxj.beanknife.jpa; import io.github.vipcxj.beanknife.core.models.Property; import java.util.List; public class Helper { public static int findViewPropertyData(List<PropertyData> viewPropertyData, Property property, int startPos) { for (int i = startPos; i < viewPropertyData.size(); ++i) { PropertyData propertyData = viewPropertyData.get(i); if (propertyData.getTarget() == property) { return i; } } for (int i = 0; i < startPos; ++i) { PropertyData propertyData = viewPropertyData.get(i); if (propertyData.getTarget() == property) { return i; } } return -1; } } <|start_filename|>beanknife-spring/src/test/java/io/github/vipcxj/beanknife/spring/test/Tester.java<|end_filename|> package io.github.vipcxj.beanknife.spring.test; import io.github.vipcxj.beanknife.spring.test.beans.SimpleBean; import io.github.vipcxj.beanknife.spring.test.beans.SimpleBeanView; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import java.util.Date; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @SpringBootTest(classes = TestApplication.class) public class Tester { @Test public void test() { SimpleBean simpleBean = new SimpleBean(); simpleBean.setA(1); simpleBean.setB("a"); simpleBean.setC(true); Date time1 = new Date(); SimpleBeanView view = SimpleBeanView.read(simpleBean); Date now = view.getSpringBean().now(); Date time2 = new Date(); assertEquals(simpleBean.getA(), view.getA()); assertEquals(simpleBean.getB(), view.getB()); assertEquals(simpleBean.isC(), view.isC()); assertEquals(simpleBean.getA() + simpleBean.getB(), view.getAb()); assertTrue(time1.getTime() <= now.getTime()); assertTrue(now.getTime() <= time2.getTime()); } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/WriteableBeanView.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.BeanProviders; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedView; import io.github.vipcxj.beanknife.runtime.utils.BeanUsage; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; @GeneratedView(targetClass = WriteableBean.class, configClass = WriteableBeanViewConfigure.class) public class WriteableBeanView<T> { private String a; private boolean b; private List<? extends Set<? extends T>> c; private List<SimpleBean> d; private Integer e; private long f; public WriteableBeanView() { } public WriteableBeanView( String a, boolean b, List<? extends Set<? extends T>> c, List<SimpleBean> d, Integer e, long f ) { this.a = a; this.b = b; this.c = c; this.d = d; this.e = e; this.f = f; } public WriteableBeanView(WriteableBeanView<T> source) { this.a = source.a; this.b = source.b; this.c = source.c; this.d = source.d; this.e = source.e; this.f = source.f; } public WriteableBeanView(WriteableBean<T> source) { if (source == null) { throw new NullPointerException("The input source argument of the read constructor of class io.github.vipcxj.beanknife.cases.beans.WriteableBeanView should not be null."); } this.a = source.getA(); this.b = source.isB(); this.c = source.getC(); this.d = source.getD(); this.e = source.e; this.f = source.getF(); } public static <T> WriteableBeanView<T> read(WriteableBean<T> source) { if (source == null) { return null; } return new WriteableBeanView<>(source); } public static <T> WriteableBeanView<T>[] read(WriteableBean<T>[] sources) { if (sources == null) { return null; } WriteableBeanView<T>[] results = new WriteableBeanView[sources.length]; for (int i = 0; i < sources.length; ++i) { results[i] = read(sources[i]); } return results; } public static <T> List<WriteableBeanView<T>> read(List<WriteableBean<T>> sources) { if (sources == null) { return null; } List<WriteableBeanView<T>> results = new ArrayList<>(); for (WriteableBean<T> source : sources) { results.add(read(source)); } return results; } public static <T> Set<WriteableBeanView<T>> read(Set<WriteableBean<T>> sources) { if (sources == null) { return null; } Set<WriteableBeanView<T>> results = new HashSet<>(); for (WriteableBean<T> source : sources) { results.add(read(source)); } return results; } public static <T> Stack<WriteableBeanView<T>> read(Stack<WriteableBean<T>> sources) { if (sources == null) { return null; } Stack<WriteableBeanView<T>> results = new Stack<>(); for (WriteableBean<T> source : sources) { results.add(read(source)); } return results; } public static <K, T> Map<K, WriteableBeanView<T>> read(Map<K, WriteableBean<T>> sources) { if (sources == null) { return null; } Map<K, WriteableBeanView<T>> results = new HashMap<>(); for (Map.Entry<K, WriteableBean<T>> source : sources.entrySet()) { results.put(source.getKey(), read(source.getValue())); } return results; } public void writeBack(WriteableBean<T> target) { target.setA(this.a); target.setB(this.b); target.setC(this.c); target.setD(this.d); target.e = this.e; } protected WriteableBean<T> createAndWriteBack() { WriteableBean<T> target = BeanProviders.INSTANCE.get(WriteableBean.class, BeanUsage.CONVERT_BACK, this, false, false); target.setA(this.a); target.setB(this.b); target.setC(this.c); target.setD(this.d); target.e = this.e; return target; } public String getA() { return this.a; } public boolean isB() { return this.b; } public List<? extends Set<? extends T>> getC() { return this.c; } public List<SimpleBean> getD() { return this.d; } public Integer getE() { return this.e; } public long getF() { return this.f; } } <|start_filename|>beanknife-jpa/src/main/java/io/github/vipcxj/beanknife/jpa/JpaViewCodeGenerator.java<|end_filename|> package io.github.vipcxj.beanknife.jpa; import io.github.vipcxj.beanknife.core.models.ViewContext; import io.github.vipcxj.beanknife.core.spi.ViewCodeGenerator; import java.io.PrintWriter; public class JpaViewCodeGenerator implements ViewCodeGenerator { @Override public void ready(ViewContext context) { context.setContext(JpaContext.class.getName(), new JpaContext(context)); } @Override public void print(PrintWriter writer, ViewContext context, String indent, int indentNum) { JpaContext jpaContext = context.getContext(JpaContext.class.getName()); if (jpaContext.isEnabled()) { jpaContext.printConstructor(writer, indent, indentNum); jpaContext.printSelectionMethod(writer, indent, indentNum); } } /* private void printParameterPrefix(PrintWriter writer, boolean breakLine, String indent, int indentNum) { printParameterPrefix(writer, breakLine, false, indent, indentNum); } private void printParameterPrefix(PrintWriter writer, boolean breakLine, boolean start, String indent, int indentNum) { if (!start) { writer.print(","); } if (breakLine) { writer.println(); Utils.printIndent(writer, indent, indentNum); } else if (!start) { writer.print(" "); } } private void printParameter( PrintWriter writer, Context context, Object key, VarMapper varMapper, boolean breakLine, boolean start, Type type, String name, String indent, int indentNum ) { printParameterPrefix(writer, breakLine, start, indent, indentNum); String varName = varMapper != null ? varMapper.getVar(key, name) : name; type.printType(writer, context, true, false); writer.print(" "); writer.print(varName); } private void printValueString(PrintWriter writer, JpaContext jpaContext, Context context, VarMapper varMapper, Property property) { if (jpaContext.isProvideSource()) { writer.print(property.getValueString("source")); } else { writer.print(varMapper.getVar(property, property.getName())); } } */ // private void printToSelection(PrintWriter writer, ViewContext context, JpaContext jpaContext, String indent, int indentNum) { // VarMapper varMapper = new VarMapper("cb", "from"); // List<Property> extraProperties = context.getExtraProperties(); // Map<String, ParamInfo> extraParams = context.getExtraParams(); // boolean breakLine = extraProperties.size() + extraParams.size() > 3; // Utils.printIndent(writer, indent, indentNum); // writer.print("public static <T> "); // printSelectionType(writer, context, context.getGenType()); // writer.print(" toJpaSelection("); // if (breakLine) { // writer.println(); // Utils.printIndent(writer, indent, indentNum + 1); // } // if (context.hasImport(JpaContext.TYPE_CRITERIA_BUILDER)) { // writer.print(JpaContext.SIMPLE_TYPE_CRITERIA_BUILDER); // } else { // writer.print(JpaContext.TYPE_CRITERIA_BUILDER); // } // writer.print(" cb"); // if (breakLine) { // writer.println(","); // Utils.printIndent(writer, indent, indentNum + 1); // } else { // writer.print(", "); // } // if (context.hasImport(JpaContext.TYPE_FROM)) { // writer.print(JpaContext.SIMPLE_TYPE_FROM); // } else { // writer.print(JpaContext.TYPE_FROM); // } // writer.print("<T, "); // context.getTargetType().printType(writer, context, true, false); // writer.print("> from"); // for (Property property : jpaContext.getProperties()) { // if ((property.getConverter() == null && property.isView()) || !property.isBase()) { // String var = varMapper.getVar(property, property.getName()); // printParameterPrefix(writer, breakLine, indent, indentNum + 1); // printSelectionType(writer, context, property.getType()); // writer.print(" "); // writer.print(var); // } // } // for (ParamInfo paramInfo : jpaContext.getParamInfos()) { // String var = varMapper.getVar(paramInfo, paramInfo.getExtraParamName()); // printParameterPrefix(writer, breakLine, indent, indentNum + 1); // Type type = Type.extract(context, paramInfo.getVar()); // printSelectionType(writer, context, type); // writer.print(" "); // writer.print(var); // } // if (breakLine) { // writer.println(); // Utils.printIndent(writer, indent, indentNum); // } // writer.println(") {"); // // Utils.printIndent(writer, indent, indentNum + 1); // writer.println("return cb.construct("); // // Utils.printIndent(writer, indent, indentNum + 2); // context.getGenType().printType(writer, context, false, false); // writer.print(".class"); // if (jpaContext.isProvideSource()) { // writer.println(","); // Utils.printIndent(writer, indent, indentNum + 2); // writer.print("from"); // } // for (Property property : jpaContext.getProperties()) { // writer.println(","); // Utils.printIndent(writer, indent, indentNum + 2); // if (property.isBase()) { // writer.print("from.get(\""); // writer.print(StringEscapeUtils.escapeJava(property.getName())); // writer.print("\")"); // } else { // writer.print(varMapper.getVar(property, property.getName())); // } // } // for (ParamInfo paramInfo : jpaContext.getParamInfos()) { // writer.println(","); // Utils.printIndent(writer, indent, indentNum + 2); // writer.print(varMapper.getVar(paramInfo, paramInfo.getExtraParamName())); // } // if (jpaContext.isFixConstructor()) { // writer.println(","); // Utils.printIndent(writer, indent, indentNum + 2); // writer.print("cb.literal(0)"); // } // // Utils.printIndent(writer, indent, indentNum + 1); // writer.println(");"); // // Utils.printIndent(writer, indent, indentNum); // writer.println("}"); // writer.println(); // } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/MapPropertiesView.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedView; import io.github.vipcxj.beanknife.runtime.converters.NullIntegerAsZeroConverter; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; @GeneratedView(targetClass = SimpleBean.class, configClass = MapPropertiesViewConfigure.class) public class MapPropertiesView { private String aMap; private int bMapWithConverter; private Date cMapUseMethod; public MapPropertiesView() { } public MapPropertiesView( String aMap, int bMapWithConverter, Date cMapUseMethod ) { this.aMap = aMap; this.bMapWithConverter = bMapWithConverter; this.cMapUseMethod = cMapUseMethod; } public MapPropertiesView(MapPropertiesView source) { this.aMap = source.aMap; this.bMapWithConverter = source.bMapWithConverter; this.cMapUseMethod = source.cMapUseMethod; } public MapPropertiesView(SimpleBean source) { if (source == null) { throw new NullPointerException("The input source argument of the read constructor of class io.github.vipcxj.beanknife.cases.beans.MapPropertiesView should not be null."); } this.aMap = source.getA(); this.bMapWithConverter = new NullIntegerAsZeroConverter().convert(source.getB()); this.cMapUseMethod = MapPropertiesViewConfigure.cMapUseMethod(source); } public static MapPropertiesView read(SimpleBean source) { if (source == null) { return null; } return new MapPropertiesView(source); } public static MapPropertiesView[] read(SimpleBean[] sources) { if (sources == null) { return null; } MapPropertiesView[] results = new MapPropertiesView[sources.length]; for (int i = 0; i < sources.length; ++i) { results[i] = read(sources[i]); } return results; } public static List<MapPropertiesView> read(List<SimpleBean> sources) { if (sources == null) { return null; } List<MapPropertiesView> results = new ArrayList<>(); for (SimpleBean source : sources) { results.add(read(source)); } return results; } public static Set<MapPropertiesView> read(Set<SimpleBean> sources) { if (sources == null) { return null; } Set<MapPropertiesView> results = new HashSet<>(); for (SimpleBean source : sources) { results.add(read(source)); } return results; } public static Stack<MapPropertiesView> read(Stack<SimpleBean> sources) { if (sources == null) { return null; } Stack<MapPropertiesView> results = new Stack<>(); for (SimpleBean source : sources) { results.add(read(source)); } return results; } public static <K> Map<K, MapPropertiesView> read(Map<K, SimpleBean> sources) { if (sources == null) { return null; } Map<K, MapPropertiesView> results = new HashMap<>(); for (Map.Entry<K, SimpleBean> source : sources.entrySet()) { results.put(source.getKey(), read(source.getValue())); } return results; } public String getA() { return this.aMap; } public int getB() { return this.bMapWithConverter; } public Date getC() { return this.cMapUseMethod; } } <|start_filename|>beanknife-core-base/src/main/java/io/github/vipcxj/beanknife/core/models/MetaContext.java<|end_filename|> package io.github.vipcxj.beanknife.core.models; import com.sun.source.util.Trees; import edu.umd.cs.findbugs.annotations.NonNull; import io.github.vipcxj.beanknife.core.utils.LombokUtils; import io.github.vipcxj.beanknife.core.utils.Utils; import io.github.vipcxj.beanknife.runtime.annotations.Access; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedMeta; import org.apache.commons.text.StringEscapeUtils; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.*; import javax.lang.model.util.Elements; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class MetaContext extends Context { private final ViewMetaData viewMeta; private final List<ViewOfData> viewOfDataList; private final Type genType; private final Type generatedType; public MetaContext(@NonNull Trees trees, @NonNull ProcessingEnvironment processingEnv, @NonNull ViewMetaData viewMeta, @NonNull List<ViewOfData> viewOfDataList) { super(trees, processingEnv, null); this.viewMeta = viewMeta; this.viewOfDataList = viewOfDataList; TypeElement targetElement = viewMeta.getOf(); this.genType = Utils.extractGenType( Type.extract(this, targetElement), viewMeta.getValue(), viewMeta.getPackageName(), "Meta" ).withoutParameters(); this.packageName = this.genType.getPackageName(); this.containers.push(Type.fromPackage(this, this.packageName)); this.generatedType = Type.extract(this, GeneratedMeta.class); } public ViewMetaData getViewMeta() { return viewMeta; } public Type getGenType() { return genType; } public void collectData() { TypeElement element = viewMeta.getOf(); Elements elementUtils = getProcessingEnv().getElementUtils(); List<? extends Element> members = elementUtils.getAllMembers(element); Access typeGetterAccess = LombokUtils.getGetterAccess(element, null); Access typeSetterAccess = LombokUtils.getSetterAccess(element, null); for (Element member : members) { if (member.getModifiers().contains(Modifier.STATIC)) { continue; } Property property = null; if (member.getKind() == ElementKind.FIELD) { property = Utils.createPropertyFromBase(this, null, (VariableElement) member, typeGetterAccess, typeSetterAccess); } else if (member.getKind() == ElementKind.METHOD) { property = Utils.createPropertyFromBase(this, null, (ExecutableElement) member); } if (property != null) { addProperty(property, false); } } getProperties().removeIf(property -> Utils.canNotSeeFromOtherClass(property, true)); importAll(); } private void importAll() { importVariable(generatedType); importVariable(Type.extract(this, viewMeta.getOf())); importVariable(Type.extract(this, viewMeta.getConfig())); if (!viewOfDataList.isEmpty()) { for (ViewOfData viewOfData : viewOfDataList) { importVariable(Type.extract(this, viewOfData.getConfigElement())); } } } @Override public boolean print(@NonNull PrintWriter writer) { if (super.print(writer)) { writer.println(); } writer.print("@"); generatedType.printType(writer, this, false, false); int viewOfNum = viewOfDataList.size(); if (viewOfNum > 0) { writer.println("("); Utils.printIndent(writer, INDENT, 1); writer.print("targetClass = "); Type.extract(this, viewMeta.getOf()).printType(writer, this, false, false); writer.println(".class,"); Utils.printIndent(writer, INDENT, 1); writer.print("configClass = "); Type.extract(this, viewMeta.getConfig()).printType(writer, this, false, false); writer.println(".class,"); Utils.printIndent(writer, INDENT, 1); writer.println("proxies = {"); Set<String> configTypeNames = new HashSet<>(); List<Type> configTypes = new ArrayList<>(); for (ViewOfData viewOfData : viewOfDataList) { Type configType = Type.extract(this, viewOfData.getConfigElement()); String configTypeName = configType.getQualifiedName(); if (!configTypeNames.contains(configTypeName)) { configTypeNames.add(configTypeName); configTypes.add(configType); } } int i = 0; int configNum = configTypes.size(); for (Type configType : configTypes) { Utils.printIndent(writer, INDENT, 2); configType.printType(writer, this, false, false); writer.print(".class"); if (i++ != configNum - 1) { writer.println(","); } else { writer.println(); } } Utils.printIndent(writer, INDENT, 1); writer.println("}"); } else { writer.print("(targetClass = "); Type.extract(this, viewMeta.getOf()).printType(writer, this, false, false); writer.print(".class, "); writer.print("configClass = "); Type.extract(this, viewMeta.getConfig()).printType(writer, this, false, false); writer.print(".class"); } writer.println(")"); genType.openClass(writer, Modifier.PUBLIC, this, INDENT, 0); Set<String> names = new HashSet<>(); for (Property property : getProperties()) { String variableName = Utils.createValidFieldName(property.getName(), names); names.add(variableName); Utils.printIndent(writer, INDENT, 1); writer.print("public static final String "); writer.print(variableName); writer.print(" = \""); writer.print(StringEscapeUtils.escapeJava(property.getName())); writer.print("\";"); writer.println(); } if (viewOfNum > 0) { writer.println(); Utils.printIndent(writer, INDENT, 1); writer.println("public static class Views {"); names.clear(); viewOfDataList.stream() .map(viewOfData -> Utils.extractGenType( Type.extract(this, viewOfData.getTargetElement()), viewOfData.getGenName(), viewOfData.getGenPackage(), "View" ).getQualifiedName()) .forEach(viewName -> { String variableName = Utils.createValidFieldName(viewName, names); names.add(variableName); Utils.printIndent(writer, INDENT, 2); writer.print("public static final String "); writer.print(variableName); writer.print(" = \""); writer.print(StringEscapeUtils.escapeJava(viewName)); writer.print("\";"); writer.println(); }); Utils.printIndent(writer, INDENT, 1); writer.println("}"); } genType.closeClass(writer, INDENT, 0); return true; } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/ConverterBeanView.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedView; import io.github.vipcxj.beanknife.runtime.converters.NullIntegerAsZeroConverter; import io.github.vipcxj.beanknife.runtime.converters.NullLongAsZeroConverter; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; @GeneratedView(targetClass = ConverterBean.class, configClass = ConverterBeanConfig.class) public class ConverterBeanView { private long a; private Number b; public ConverterBeanView() { } public ConverterBeanView( long a, Number b ) { this.a = a; this.b = b; } public ConverterBeanView(ConverterBeanView source) { this.a = source.a; this.b = source.b; } public ConverterBeanView(ConverterBean source) { if (source == null) { throw new NullPointerException("The input source argument of the read constructor of class io.github.vipcxj.beanknife.cases.beans.ConverterBeanView should not be null."); } this.a = new NullLongAsZeroConverter().convert(source.getA()); this.b = new NullIntegerAsZeroConverter().convert(source.getB()); } public static ConverterBeanView read(ConverterBean source) { if (source == null) { return null; } return new ConverterBeanView(source); } public static ConverterBeanView[] read(ConverterBean[] sources) { if (sources == null) { return null; } ConverterBeanView[] results = new ConverterBeanView[sources.length]; for (int i = 0; i < sources.length; ++i) { results[i] = read(sources[i]); } return results; } public static List<ConverterBeanView> read(List<ConverterBean> sources) { if (sources == null) { return null; } List<ConverterBeanView> results = new ArrayList<>(); for (ConverterBean source : sources) { results.add(read(source)); } return results; } public static Set<ConverterBeanView> read(Set<ConverterBean> sources) { if (sources == null) { return null; } Set<ConverterBeanView> results = new HashSet<>(); for (ConverterBean source : sources) { results.add(read(source)); } return results; } public static Stack<ConverterBeanView> read(Stack<ConverterBean> sources) { if (sources == null) { return null; } Stack<ConverterBeanView> results = new Stack<>(); for (ConverterBean source : sources) { results.add(read(source)); } return results; } public static <K> Map<K, ConverterBeanView> read(Map<K, ConverterBean> sources) { if (sources == null) { return null; } Map<K, ConverterBeanView> results = new HashMap<>(); for (Map.Entry<K, ConverterBean> source : sources.entrySet()) { results.put(source.getKey(), read(source.getValue())); } return results; } public long getA() { return this.a; } public Number getB() { return this.b; } } <|start_filename|>beanknife-core-base/src/main/java/io/github/vipcxj/beanknife/core/utils/ParamInfo.java<|end_filename|> package io.github.vipcxj.beanknife.core.utils; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.Nullable; import io.github.vipcxj.beanknife.core.models.Property; import javax.lang.model.element.VariableElement; public class ParamInfo { private final VariableElement var; private final boolean source; private final boolean extraParam; private final boolean propertyParam; private final String extraParamName; private final Property injectedProperty; public ParamInfo(@NonNull VariableElement var, boolean source, boolean extraParam, boolean propertyParam, @NonNull String extraParamName, @Nullable Property injectedProperty) { this.var = var; this.source = source; this.extraParam = extraParam; this.propertyParam = propertyParam; this.extraParamName = extraParamName; this.injectedProperty = injectedProperty; } public static ParamInfo sourceParam(@NonNull VariableElement var) { return new ParamInfo(var, true, false, false, "", null); } public static ParamInfo extraParam(@NonNull VariableElement var, @NonNull String name) { return new ParamInfo(var, false, true, false, name, null); } public static ParamInfo propertyParam(@NonNull VariableElement var, @NonNull Property property) { return new ParamInfo(var, false, false, true, "", property); } public static ParamInfo unknown(@NonNull VariableElement var) { return new ParamInfo(var, false, false, false, "", null); } public VariableElement getVar() { return var; } public boolean isSource() { return source; } public boolean isExtraParam() { return extraParam; } public boolean isPropertyParam() { return propertyParam; } @NonNull public String getExtraParamName() { return extraParamName; } public Property getInjectedProperty() { return injectedProperty; } @NonNull public String getParameterName() { return var.getSimpleName().toString(); } public boolean isUnknown() { return !source && !extraParam && !propertyParam; } public String getMethodName() { return var.getEnclosingElement().getSimpleName().toString(); } } <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/beans/ViewOfInNestBean.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; public class ViewOfInNestBean { private int a; private String b; public int getA() { return a; } public String getB() { return b; } public void setB(String b) { this.b = b; } @ViewOf static class Bean1 { private int a; private String b; public int getA() { return a; } public String getB() { return b; } public void setB(String b) { this.b = b; } public static class Bean2 { private int a; private String b; public int getA() { return a; } public String getB() { return b; } public void setB(String b) { this.b = b; } @ViewOf protected static class Bean3 { private int a; private String b; public int getA() { return a; } public String getB() { return b; } public void setB(String b) { this.b = b; } } } } static class Bean2 { int a; @ViewOf class Bean1 { long b; @ViewOf class Bean3 { String c; } } } } <|start_filename|>beanknife-core-base/debug-test.cmd<|end_filename|> mvn -Dtest=%1 -Dmaven.surefire.debug test <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/beans/MetaAndViewOfOnDiffBean3MetaConfig.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.ViewMeta; @ViewMeta(of = MetaAndViewOfOnDiffBean3.class) public class MetaAndViewOfOnDiffBean3MetaConfig { } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/annotations/UseAnnotations.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.annotations; import java.lang.annotation.*; @Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD}) @Retention(RetentionPolicy.SOURCE) @Inherited public @interface UseAnnotations { UseAnnotation[] value() default {}; } <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/beans/Leaf11Bean.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import java.lang.annotation.Annotation; import java.util.List; public class Leaf11Bean { private int a; private Class<? extends Annotation> b; private List<? extends String> c; private long d; private String e; public int getA() { return a; } public void setA(int a) { this.a = a; } public Class<? extends Annotation> getB() { return b; } public void setB(Class<? extends Annotation> b) { this.b = b; } public List<? extends String> getC() { return c; } public void setC(List<? extends String> c) { this.c = c; } public long getD() { return d; } public void setD(long d) { this.d = d; } public String getE() { return e; } public void setE(String e) { this.e = e; } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/NestedGenericBean$StaticChildBeanView.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedView; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; @GeneratedView(targetClass = NestedGenericBean.StaticChildBean.class, configClass = NestedGenericBean.StaticChildBean.class) public class NestedGenericBean$StaticChildBeanView<T1 extends String> { private T1 a; public NestedGenericBean$StaticChildBeanView() { } public NestedGenericBean$StaticChildBeanView( T1 a ) { this.a = a; } public NestedGenericBean$StaticChildBeanView(NestedGenericBean$StaticChildBeanView<T1> source) { this.a = source.a; } public NestedGenericBean$StaticChildBeanView(NestedGenericBean.StaticChildBean<T1> source) { if (source == null) { throw new NullPointerException("The input source argument of the read constructor of class io.github.vipcxj.beanknife.cases.beans.NestedGenericBean$StaticChildBeanView should not be null."); } this.a = source.getA(); } public static <T1 extends String> NestedGenericBean$StaticChildBeanView<T1> read(NestedGenericBean.StaticChildBean<T1> source) { if (source == null) { return null; } return new NestedGenericBean$StaticChildBeanView<>(source); } public static <T1 extends String> NestedGenericBean$StaticChildBeanView<T1>[] read(NestedGenericBean.StaticChildBean<T1>[] sources) { if (sources == null) { return null; } NestedGenericBean$StaticChildBeanView<T1>[] results = new NestedGenericBean$StaticChildBeanView[sources.length]; for (int i = 0; i < sources.length; ++i) { results[i] = read(sources[i]); } return results; } public static <T1 extends String> List<NestedGenericBean$StaticChildBeanView<T1>> read(List<NestedGenericBean.StaticChildBean<T1>> sources) { if (sources == null) { return null; } List<NestedGenericBean$StaticChildBeanView<T1>> results = new ArrayList<>(); for (NestedGenericBean.StaticChildBean<T1> source : sources) { results.add(read(source)); } return results; } public static <T1 extends String> Set<NestedGenericBean$StaticChildBeanView<T1>> read(Set<NestedGenericBean.StaticChildBean<T1>> sources) { if (sources == null) { return null; } Set<NestedGenericBean$StaticChildBeanView<T1>> results = new HashSet<>(); for (NestedGenericBean.StaticChildBean<T1> source : sources) { results.add(read(source)); } return results; } public static <T1 extends String> Stack<NestedGenericBean$StaticChildBeanView<T1>> read(Stack<NestedGenericBean.StaticChildBean<T1>> sources) { if (sources == null) { return null; } Stack<NestedGenericBean$StaticChildBeanView<T1>> results = new Stack<>(); for (NestedGenericBean.StaticChildBean<T1> source : sources) { results.add(read(source)); } return results; } public static <K, T1 extends String> Map<K, NestedGenericBean$StaticChildBeanView<T1>> read(Map<K, NestedGenericBean.StaticChildBean<T1>> sources) { if (sources == null) { return null; } Map<K, NestedGenericBean$StaticChildBeanView<T1>> results = new HashMap<>(); for (Map.Entry<K, NestedGenericBean.StaticChildBean<T1>> source : sources.entrySet()) { results.put(source.getKey(), read(source.getValue())); } return results; } public T1 getA() { return this.a; } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/StaticMethodPropertyBeanViewConfig.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.*; @ViewOf(value = SimpleBean.class, genName = "StaticMethodPropertyBeanView", includes = {SimpleBeanMeta.a, SimpleBeanMeta.b}) public class StaticMethodPropertyBeanViewConfig { @NewViewProperty("one") public static int getOne(){ return 1; } @OverrideViewProperty(SimpleBeanMeta.b) public static Object getB() { return null; } @NewViewProperty("c") public static Integer getC(SimpleBean bean) { return bean.getB(); } @NewViewProperty("d") public static Integer getD(SimpleBean bean) { return bean.getB(); } /** * test non static method as a static method property. * Though the source can be compiled, * this will cause a exception in the runtime. Because {@link ViewOf#useDefaultBeanProvider()} is false here. * So no bean provider is used. Then the configure class {@link StaticMethodPropertyBeanViewConfig} can not be initialized. * @param source the original instance. * @return the property value */ @NewViewProperty("e") public String getABC(SimpleBean source) { return source.getA() + source.getB() + source.getC(); } } <|start_filename|>beanknife-core-base/src/main/java/io/github/vipcxj/beanknife/core/models/Type.java<|end_filename|> package io.github.vipcxj.beanknife.core.models; import com.sun.source.tree.*; import com.sun.source.util.TreePath; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import edu.umd.cs.findbugs.annotations.Nullable; import io.github.vipcxj.beanknife.core.utils.ObjectsCompatible; import io.github.vipcxj.beanknife.core.utils.TreeUtils; import io.github.vipcxj.beanknife.core.utils.Utils; import javax.lang.model.element.*; import javax.lang.model.type.*; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import java.io.PrintWriter; import java.io.StringWriter; import java.util.*; import java.util.stream.Collectors; public class Type { private static final Set<Modifier> DEFAULT_MODIFIERS = new TreeSet<>(Collections.singletonList(Modifier.PUBLIC)); private final Context context; private final Set<Modifier> modifiers; private String packageName; private String simpleName; private int array; private final boolean annotation; private final boolean typeVar; private final boolean wildcard; private List<Type> parameters; private Type container; private final List<Type> upperBounds; private final List<Type> lowerBounds; private CompilationUnitTree cu; private Tree tree; /** * 构造函数 * @param packageName 包名 * @param simpleName 类名,不包括包名,特别的,对于嵌套类,有如下形式Parent.Nest1.Nest2 * @param array 数组维数,若不是数组,则为0 * @param parameters 泛型参数列表 * @param upperBounds 类型上界,可为空,此时默认为 {@link Object} * @param container 包裹类,可为空 * @param lowerBounds 类型下界,可为空 */ public Type( @NonNull Context context, @NonNull Set<Modifier> modifiers, @NonNull String packageName, @NonNull String simpleName, int array, boolean annotation, boolean typeVar, boolean wildcard, @NonNull List<Type> parameters, @CheckForNull Type container, @NonNull List<Type> upperBounds, @NonNull List<Type> lowerBounds, @CheckForNull CompilationUnitTree cu, @CheckForNull Tree tree ) { this.context = context; this.modifiers = modifiers; this.packageName = packageName; this.simpleName = simpleName; this.array = array; this.annotation = annotation; this.typeVar = typeVar; this.wildcard = wildcard; this.parameters = parameters; this.container = container; this.upperBounds = upperBounds; this.lowerBounds = lowerBounds; this.cu = cu; this.tree = tree; } private Type(@NonNull Type other) { this.context = other.context; this.modifiers = other.modifiers; this.packageName = other.packageName; this.simpleName = other.simpleName; this.array = other.array; this.annotation = other.annotation; this.typeVar = other.typeVar; this.wildcard = other.wildcard; this.parameters = other.parameters; this.container = other.container; this.upperBounds = other.upperBounds; this.lowerBounds = other.lowerBounds; this.cu = other.cu; this.tree = other.tree; } @NonNull public Type toArrayType() { if (wildcard) { throw new UnsupportedOperationException(); } Type type = new Type(this); ++type.array; return type; } @NonNull public Type changeSimpleName(@NonNull String simpleName, boolean removeParents) { if (wildcard) { throw new UnsupportedOperationException(); } if (simpleName.equals(this.simpleName) && (!removeParents || this.container == null)) { return this; } Type type = new Type(this); type.simpleName = simpleName; type.container = removeParents ? null : container; type.cu = null; type.tree = null; return type; } @NonNull public Type changePackage(@NonNull String packageName) { if (wildcard || typeVar) { throw new UnsupportedOperationException(); } if (packageName.equals(this.packageName)) { return this; } Type type = new Type(this); type.packageName = packageName; type.cu = null; type.tree = null; return type; } @NonNull public Type appendName(@NonNull String postfix) { if (wildcard) { throw new UnsupportedOperationException(); } if (postfix.isEmpty()) { return this; } Type type = new Type(this); type.simpleName += postfix; type.cu = null; type.tree = null; return type; } public boolean isStatic() { if (container == null) { return true; } if (!container.isStatic()) { return false; } return modifiers.contains(Modifier.STATIC); } @NonNull public Type flatten() { if (container == null) { return this; } Type type = new Type(this); type.simpleName = getEnclosedFlatSimpleName(); if (!isStatic()) { type.parameters = new ArrayList<>(type.parameters); Type parent = container; while (parent != null) { type.parameters.addAll(0, parent.getParameters()); parent = parent.container; } } type.container = null; type.cu = null; type.tree = null; return type; } @NonNull public Type withoutParameters() { if (parameters.isEmpty()) { return this; } Type type = new Type(this); type.parameters = Collections.emptyList(); type.cu = null; type.tree = null; return type; } @NonNull public Type withParameters(@NonNull List<Type> parameters) { Type type = new Type(this); type.parameters = parameters; type.cu = null; type.tree = null; return type; } @NonNull public Type withoutArray() { if (!isArray()) { return this; } Type type = new Type(this); type.array = 0; type.cu = null; type.tree = null; return type; } @CheckForNull public Type getComponentType() { Type type = new Type(this); int newArray = type.array - 1; if (newArray >= 0) { type.array = newArray; type.cu = null; type.tree = null; return type; } else { return null; } } public String relativeName(Type type, boolean imported) { String packageName = type.getPackageName(); String qualifiedName = type.getQualifiedName(); String packageNameOfMe = getPackageName(); String qualifiedNameOfMe = getQualifiedName(); if (packageName.equals(packageNameOfMe) && !isPackage() && type.isNested()) { if (qualifiedName.equals(qualifiedNameOfMe)) { return type.getSimpleName(); } if (qualifiedName.startsWith(qualifiedNameOfMe) && qualifiedName.charAt(qualifiedNameOfMe.length()) == '.') { return type.getSimpleName(); } if (qualifiedNameOfMe.startsWith(qualifiedName) && qualifiedNameOfMe.charAt(qualifiedName.length()) == '.') { return type.getSimpleName(); } } return (imported || type.isLangType()) ? type.getEnclosedSimpleName() : type.getQualifiedName(); } public static Type create(Context context, String packageName, String typeName, int array, boolean annotation) { return new Type( context, DEFAULT_MODIFIERS, packageName, typeName, array, annotation, false, false, Collections.emptyList(), null, Collections.emptyList(), Collections.emptyList(), null, null ); } public static Type extract(Context context, Class<?> clazz) { return extract(context, context.getProcessingEnv().getElementUtils().getTypeElement(clazz.getCanonicalName()), null); } @NonNull public static Type createWildcard(Context context, @NonNull List<Type> extendsBounds, @NonNull List<Type> supperBounds) { return new Type( context, Collections.emptySet(), "", "?", 0, false, false, true, Collections.emptyList(), null, extendsBounds, supperBounds, null, null ); } @NonNull public static Type createUnboundedWildcard(Context context) { return createWildcard(context, Collections.emptyList(), Collections.emptyList()); } @NonNull public static Type createExtendsWildcard(Context context, @NonNull List<Type> upperBounds) { return createWildcard(context, upperBounds, Collections.emptyList()); } @NonNull public static Type createSuperWildcard(Context context, @NonNull List<Type> lowerBounds) { return createWildcard(context, Collections.emptyList(), lowerBounds); } public static Type createTypeParameter(Context context, @NonNull String name, @NonNull List<Type> bounds, @CheckForNull CompilationUnitTree cu, @CheckForNull Tree tree) { return new Type( context, Collections.emptySet(), "", name, 0, false, true, false, Collections.emptyList(), null, bounds, Collections.emptyList(), cu, tree ); } public static Type extract(@NonNull Context context, @NonNull Element element) { return extract(context, element, null); } private static Tree parseTree(@NonNull Context context, @NonNull Element element) { Tree tree = context.trees.getTree(element); if (tree != null) { return tree; } if (element.getKind() == ElementKind.PARAMETER) { VariableElement variableElement = (VariableElement) element; ExecutableElement method = (ExecutableElement) variableElement.getEnclosingElement(); MethodTree methodTree = context.trees.getTree(method); if (methodTree == null) { return null; } for (VariableTree parameter : methodTree.getParameters()) { if (parameter.getName().toString().equals(element.getSimpleName().toString())) { return parameter; } } } // todo support other element type. return null; } public static Type extract(@NonNull Context context, @NonNull Element element, @Nullable List<Type> parameterTypes) { CompilationUnitTree cu = TreeUtils.getCompilationUnit(context, element); Tree tree = parseTree(context, element); if (element.getKind().isClass() || element.getKind().isInterface()) { TypeElement typeElement = (TypeElement) element; List<? extends TypeParameterElement> typeParameters = typeElement.getTypeParameters(); List<Type> parameters; parameters = ObjectsCompatible.requireNonNullElseGet(parameterTypes, () -> typeParameters.stream().map(e -> extract(context, e, null)).collect(Collectors.toList())); boolean annotation = element.getKind() == ElementKind.ANNOTATION_TYPE; Element enclosingElement = element.getEnclosingElement(); Type parentType = null; String packageName; if (enclosingElement.getKind() == ElementKind.PACKAGE) { PackageElement packageElement = (PackageElement) enclosingElement; packageName = packageElement.getQualifiedName().toString(); } else { parentType = extract(context, enclosingElement, null); if (parentType == null) { return null; } packageName = parentType.packageName; } return new Type( context, typeElement.getModifiers(), packageName, element.getSimpleName().toString(), 0, annotation, false, false, parameters, parentType, Collections.emptyList(), Collections.emptyList(), cu, tree ); } else if ( element.getKind() == ElementKind.FIELD || element.getKind() == ElementKind.PARAMETER ) { if (tree == null || tree instanceof VariableTree) { VariableTree variableTree = (VariableTree) tree; tree = variableTree != null ? variableTree.getType() : null; return extract(context, element.asType(), cu, tree); } else { throw new IllegalArgumentException("This is impossible!"); } } else if (element.getKind() == ElementKind.METHOD) { ExecutableElement executableElement = (ExecutableElement) element; if (tree == null || tree instanceof MethodTree) { MethodTree methodTree = (MethodTree) tree; tree = methodTree != null ? (methodTree).getReturnType() : null; return extract(context, executableElement.getReturnType(), cu, tree); } else { throw new IllegalArgumentException("This is impossible!"); } } else if (element.getKind() == ElementKind.PACKAGE) { PackageElement packageElement = (PackageElement) element; return fromPackage(context, packageElement.isUnnamed() ? "" : packageElement.getQualifiedName().toString()); } else if (element.getKind() == ElementKind.TYPE_PARAMETER) { TypeParameterElement typeParameterElement = (TypeParameterElement) element; if (tree instanceof TypeParameterTree) { TypeParameterTree typeParameterTree = (TypeParameterTree) tree; List<Type> bounds = typeParameterTree.getBounds().stream() .map(bound -> { TypeMirror typeMirror = TreeUtils.tryGetTypeMirror(context, element, bound); return extract(context, typeMirror, cu, bound); }) .filter(type -> type == null || type.isNotObjectType()) .collect(Collectors.toList()); if (bounds.stream().anyMatch(Objects::isNull)) { return null; } return createTypeParameter(context, typeParameterElement.getSimpleName().toString(), bounds, cu, tree); } else if (tree == null) { List<Type> bounds = typeParameterElement.getBounds().stream() .map(bound -> extract(context, bound, null, null)) .filter(type -> type == null || type.isNotObjectType()) .collect(Collectors.toList()); if (bounds.stream().anyMatch(Objects::isNull)) { return null; } return createTypeParameter(context, typeParameterElement.getSimpleName().toString(), bounds, cu, null); } else { throw new IllegalArgumentException("This is impossible!"); } } throw new UnsupportedOperationException("Unsupported element kind: " + element.getKind() + "."); } @NonNull private static List<Type> parseBounds(@NonNull Context context, @Nullable TypeMirror typeMirror, @CheckForNull CompilationUnitTree cu, @NonNull List<Tree> tree) { if (typeMirror == null) { return Collections.emptyList(); } else if (typeMirror.getKind() == TypeKind.INTERSECTION) { IntersectionType intersectionType = (IntersectionType) typeMirror; List<? extends TypeMirror> bounds = intersectionType.getBounds(); List<Type> types = new ArrayList<>(); for (int i = 0; i < bounds.size(); ++i) { TypeMirror bound = bounds.get(i); Tree boundTree = i < tree.size() ? tree.get(i) : null; types.add(extract(context, bound, cu, boundTree)); } return types; } else { return Collections.singletonList(extract(context, typeMirror, cu, tree.isEmpty() ? null : tree.get(0))); } } @CheckForNull public static Type extract(@NonNull Context context, @Nullable TypeMirror type, @CheckForNull CompilationUnitTree cu, @CheckForNull Tree tree) { if (type == null || type.getKind() == TypeKind.ERROR) { return cu != null && tree != null ? context.fixType(cu, tree) : null; } else if (type.getKind().isPrimitive()) { return new Type( context, Collections.emptySet(), "", type.toString(), 0, false, false, false, Collections.emptyList(), null, Collections.emptyList(), Collections.emptyList(), cu, tree ); } else if (type.getKind() == TypeKind.ARRAY) { ArrayType arrayType = (ArrayType) type; ArrayTypeTree arrayTypeTree = (ArrayTypeTree) tree; Type componentType = extract(context, arrayType.getComponentType(), cu, arrayTypeTree != null ? arrayTypeTree.getType() : null); return componentType != null ? componentType.toArrayType() : null; } else if (type.getKind() == TypeKind.DECLARED) { DeclaredType declaredType = (DeclaredType) type; List<? extends Tree> typeParameterTrees = null; if (tree != null && tree.getKind() == Tree.Kind.PARAMETERIZED_TYPE) { ParameterizedTypeTree parameterizedTypeTree = (ParameterizedTypeTree) tree; typeParameterTrees = parameterizedTypeTree.getTypeArguments(); } List<? extends TypeMirror> typeArguments = declaredType.getTypeArguments(); List<Type> parameterTypes = new ArrayList<>(); for (int i = 0; i < typeArguments.size(); ++i) { TypeMirror typeArgument = typeArguments.get(i); Tree typeParameterTree = typeParameterTrees != null ? typeParameterTrees.get(Math.max(i, typeParameterTrees.size() - 1)) : null; Type parameterType = extract(context, typeArgument, cu, cu != null ? typeParameterTree : null); if (parameterType == null) { return null; } parameterTypes.add(parameterType); } TypeElement typeElement = Utils.toElement(declaredType); return extract(context, typeElement, parameterTypes); } else if (type.getKind() == TypeKind.TYPEVAR) { TypeVariable typeVariable = (TypeVariable) type; TypeParameterTree typeParameterTree = tree instanceof TypeParameterTree ? (TypeParameterTree) tree : null; List<? extends Tree> boundTrees = typeParameterTree != null ? typeParameterTree.getBounds() : null; List<Type> upperBounds = new ArrayList<>(); TypeMirror upperBound = typeVariable.getUpperBound(); if (upperBound.getKind() == TypeKind.INTERSECTION) { IntersectionType intersectionType = (IntersectionType) upperBound; if (boundTrees != null && boundTrees.size() != intersectionType.getBounds().size()) { throw new IllegalArgumentException("This is impossible!"); } for (int i = 0; i < intersectionType.getBounds().size(); ++i) { TypeMirror boundTypeMirror = intersectionType.getBounds().get(i); Tree boundTree = boundTrees != null ? boundTrees.get(i) : null; Type boundType = extract(context, boundTypeMirror, cu, cu != null ? boundTree : null); if (boundType == null) { return null; } upperBounds.add(boundType); } } else if (!Utils.isThisType(upperBound, Object.class)){ if (boundTrees != null && boundTrees.size() != 1) { throw new IllegalArgumentException("This is impossible!"); } Tree boundTree = boundTrees != null ? boundTrees.get(0) : null; Type boundType = extract(context, upperBound, cu, cu != null ? boundTree : null); upperBounds.add(boundType); } return Type.createTypeParameter(context, typeVariable.asElement().getSimpleName().toString(), upperBounds, cu, tree); } else if (type.getKind() == TypeKind.WILDCARD) { WildcardType wildcardType = (WildcardType) type; TypeMirror extendsBound = wildcardType.getExtendsBound(); TypeMirror superBound = wildcardType.getSuperBound(); List<Tree> extendsBoundTrees = Collections.emptyList(); List<Tree> superBoundTrees = Collections.emptyList(); if (tree != null) { WildcardTree wildcardTree = (WildcardTree) tree; Tree bound = wildcardTree.getBound(); List<Tree> bounds = new ArrayList<>(); if (bound != null) { if (bound.getKind() == Tree.Kind.INTERSECTION_TYPE) { IntersectionTypeTree intersectionTypeTree = (IntersectionTypeTree) bound; bounds.addAll(intersectionTypeTree.getBounds()); } else { bounds.add(bound); } } if (tree.getKind() == Tree.Kind.EXTENDS_WILDCARD) { extendsBoundTrees = bounds; } else if (tree.getKind() == Tree.Kind.SUPER_WILDCARD) { superBoundTrees = bounds; } } List<Type> extendsBoundTypes = extendsBound != null ? parseBounds(context, extendsBound, cu, extendsBoundTrees) : Collections.emptyList(); List<Type> superBoundTypes = superBound != null ? parseBounds(context, superBound, cu, superBoundTrees) : Collections.emptyList(); return new Type( context, Collections.emptySet(), "", "?", 0, false, false, true, Collections.emptyList(), null, extendsBoundTypes, superBoundTypes, cu, tree ); } else if (type.getKind() == TypeKind.VOID) { return null; } else { throw new UnsupportedOperationException("Type " + type + " is not supported."); } } public TypeMirror getTypeMirror() { if (cu != null && tree != null) { TreePath path = context.trees.getPath(cu, tree); return context.trees.getTypeMirror(path); } else if (isPrimate()) { Types typeUtils = context.getProcessingEnv().getTypeUtils(); TypeMirror typeMirror; if (isBoolean()) { typeMirror = typeUtils.getPrimitiveType(TypeKind.BOOLEAN); } else if (isChar()) { typeMirror = typeUtils.getPrimitiveType(TypeKind.CHAR); } else if (isByte()) { typeMirror = typeUtils.getPrimitiveType(TypeKind.BYTE); } else if (isShort()) { typeMirror = typeUtils.getPrimitiveType(TypeKind.SHORT); } else if (isInt()) { typeMirror = typeUtils.getPrimitiveType(TypeKind.INT); } else if (isLong()) { typeMirror = typeUtils.getPrimitiveType(TypeKind.LONG); } else if (isFloat()) { typeMirror = typeUtils.getPrimitiveType(TypeKind.FLOAT); } else if (isDouble()) { typeMirror = typeUtils.getPrimitiveType(TypeKind.DOUBLE); } else { throw new IllegalArgumentException("This is impossible."); } for (int i = 0; i < array; ++i) { typeMirror = typeUtils.getArrayType(typeMirror); } return typeMirror; } else if (!isTypeVar() && !isWildcard()) { Types typeUtils = context.getProcessingEnv().getTypeUtils(); Elements elementUtils = context.getProcessingEnv().getElementUtils(); TypeElement typeElement = elementUtils.getTypeElement(getQualifiedName()); if (typeElement == null) { return null; } List<TypeMirror> typeParameters = parameters.stream().map(Type::getTypeMirror).collect(Collectors.toList()); if (typeParameters.stream().anyMatch(Objects::isNull)) { return null; } TypeMirror containerTypeMirror = null; if (container != null) { containerTypeMirror = container.getTypeMirror(); if (containerTypeMirror == null || containerTypeMirror.getKind() != TypeKind.DECLARED) { return null; } } TypeMirror typeMirror = typeUtils.getDeclaredType((DeclaredType) containerTypeMirror, typeElement, typeParameters.toArray(new TypeMirror[0])); for (int i = 0; i < array; ++i) { typeMirror = typeUtils.getArrayType(typeMirror); } return typeMirror; } else { return null; } } public boolean canAssignTo(TypeMirror target) { TypeMirror typeMirror = getTypeMirror(); if (typeMirror != null) { Types typeUtils = context.getProcessingEnv().getTypeUtils(); return typeUtils.isAssignable(typeMirror, target); } else { return Utils.isThisType(target, Object.class); } } public boolean canAssignTo(Type targetType) { TypeMirror typeMirror = getTypeMirror(); TypeMirror targetTypeMirror = targetType.getTypeMirror(); if (typeMirror != null && targetTypeMirror != null) { Types typeUtils = context.getProcessingEnv().getTypeUtils(); return typeUtils.isAssignable(typeMirror, targetTypeMirror); } else { return sameType(targetType) || !targetType.isNotObjectType(); } } public boolean canBeAssignedBy(TypeMirror source) { TypeMirror typeMirror = getTypeMirror(); if (typeMirror != null) { Types typeUtils = context.getProcessingEnv().getTypeUtils(); return typeUtils.isAssignable(source, typeMirror); } else { return !isNotObjectType(); } } public static Type fromPackage(Context context, String packageName) { return new Type( context, Collections.emptySet(), packageName, "", 0, false, false, false, Collections.emptyList(), null, Collections.emptyList(), Collections.emptyList(), null, null ); } /** * 获取包名 * @return 包名 */ @NonNull public String getPackageName() { return packageName; } /** * 获取简单名,不包括包名,特别的,对于嵌套类,有如下形式Parent.Nest1.Nest2 * @return 类名 */ @NonNull public String getSimpleName() { return simpleName; } public String getEnclosedSimpleName() { if (container == null) { return getSimpleName(); } return combine( ".", container.getEnclosedSimpleName(), getSimpleName() ); } /** * 获取单独类名,若不是嵌套类,则为不包括包名和泛型参数的类名。对于嵌套类,列如 a.b.c.D.E, 返回 D$E * @return 单独类名 */ public String getEnclosedFlatSimpleName() { if (container == null) { return getSimpleName(); } return combine( "$", container.getEnclosedFlatSimpleName(), getSimpleName() ); } /** * 获取最外层类,如果不是嵌套类,则为其本身 * @return 最外层类 */ public Type getTopmostEnclosingType() { if (container == null) { return this; } return container.getTopmostEnclosingType(); } private static String combine(String connector, @NonNull String... parts) { StringBuilder sb = new StringBuilder(); for (String part : parts) { if (part != null && !part.isEmpty()) { if (sb.length() == 0) { sb.append(part); } else { sb.append(connector).append(part); } } } return sb.toString(); } /** * 获取全限定类名。特别的,对于嵌套类,例如 a.b.c.D.E 返回 a.b.c.D.E * @return 全限定类名 */ @NonNull public String getQualifiedName() { return combine( ".", container != null ? container.getQualifiedName() : packageName, getSimpleName() ); } public Context getContext() { return context; } public int getArray() { return array; } public boolean isArray() { return array > 0; } public boolean isAnnotation() { return annotation; } public boolean isTypeVar() { return typeVar; } public boolean isWildcard() { return wildcard; } public List<Type> getLowerBounds() { return lowerBounds; } public List<Type> getUpperBounds() { return upperBounds; } public List<Type> getParameters() { return parameters; } public boolean isSamePackage(Type other) { return getPackageName().equals(other.getPackageName()); } public boolean isNotObjectType() { return !"java.lang".equals(packageName) || !"Object".equals(simpleName); } public boolean isLangType() { return "java.lang".equals(packageName); } public boolean isBoolean() { return packageName.isEmpty() && "boolean".equals(simpleName); } public boolean isChar() { return packageName.isEmpty() && "char".equals(simpleName); } public boolean isByte() { return packageName.isEmpty() && "byte".equals(simpleName); } public boolean isShort() { return packageName.isEmpty() && "short".equals(simpleName); } public boolean isInt() { return packageName.isEmpty() && "int".equals(simpleName); } public boolean isLong() { return packageName.isEmpty() && "long".equals(simpleName); } public boolean isFloat() { return packageName.isEmpty() && "float".equals(simpleName); } public boolean isDouble() { return packageName.isEmpty() && "double".equals(simpleName); } public boolean isNested() { return container != null; } public boolean isPackage() { return simpleName.isEmpty(); } public boolean isObject() { return !isPackage() && !isArray() && !isPrimate() && !isWildcard() && !isTypeVar(); } public boolean isPrimate() { return packageName.isEmpty() && !typeVar && !wildcard && parameters.isEmpty() && container == null && upperBounds.isEmpty() && lowerBounds.isEmpty() && (simpleName.equals("boolean") || simpleName.equals("char") || simpleName.equals("byte") || simpleName.equals("short") || simpleName.equals("int") || simpleName.equals("long") || simpleName.equals("float") || simpleName.equals("double")); } public boolean isType(Class<?> type) { int array = 0; while (type.isArray()) { type = type.getComponentType(); ++array; } return this.array == array && getQualifiedName().equals(type.getCanonicalName()); } public boolean isView() { return context.isViewType(this); } public boolean sameType(@NonNull Type type) { return sameType(type, false); } public boolean sameType(@NonNull Type type, boolean erasure) { if (array != type.array) { return false; } if (!packageName.equals(type.packageName)) { return false; } if (!simpleName.equals(type.simpleName)) { return false; } if (annotation != type.annotation) { return false; } if (typeVar != type.typeVar) { return false; } if (wildcard != type.wildcard) { return false; } if (container == null && type.container != null) { return false; } else if (container != null && type.container == null) { return false; } else if (container != null && !container.sameType(type.container, erasure)){ return false; } if (!erasure) { if (parameters.size() != type.parameters.size()) { return false; } for (int i = 0; i < parameters.size(); ++i) { Type parameter = parameters.get(i); Type otherParameter = type.parameters.get(i); if (!parameter.sameType(otherParameter)) { return false; } } if (upperBounds.size() != type.upperBounds.size()) { return false; } for (int i = 0; i < upperBounds.size(); ++i) { Type bound = upperBounds.get(i); Type otherParameter = type.upperBounds.get(i); if (!bound.sameType(otherParameter)) { return false; } } if (lowerBounds.size() != type.lowerBounds.size()) { return false; } for (int i = 0; i < lowerBounds.size(); ++i) { Type bound = lowerBounds.get(i); Type otherParameter = type.lowerBounds.get(i); if (!bound.sameType(otherParameter)) { return false; } } } return true; } public void openClass(@NonNull PrintWriter writer, @NonNull Modifier modifier, @NonNull Context context, String indent, int indentNum) { openClass(writer, modifier, context, null, Collections.emptyList(), indent, indentNum); } public void openClass(@NonNull PrintWriter writer, @NonNull Modifier modifier, @NonNull Context context, @CheckForNull Type extendsType, @NonNull List<Type> implTypes, String indent, int indentNum) { Utils.printIndent(writer, indent, indentNum); writer.print(modifier); writer.print(" "); writer.print("class "); writer.print(getSimpleName()); printGenericParameters(writer, context, true); if (extendsType != null) { writer.print(" extends "); extendsType.printType(writer, context, true, false); } if (!implTypes.isEmpty()) { writer.print(" implements "); int i = 0; for (Type implType : implTypes) { implType.printType(writer, context, true, false); if (i++ != implTypes.size() - 1) { writer.print(", "); } } } writer.println(" {"); } public void closeClass(@NonNull PrintWriter writer, String indent, int indentNum) { Utils.printIndent(writer, indent, indentNum); writer.println("}"); } private void openConstructor(@NonNull PrintWriter writer, @NonNull Modifier modifier, String indent, int indentNum) { Utils.printIndent(writer, indent, indentNum); Utils.printModifier(writer, modifier); writer.print(getSimpleName()); writer.print("("); } public void emptyConstructor(@NonNull PrintWriter writer, @NonNull Modifier modifier, String indent, int indentNum) { openConstructor(writer, modifier, indent, indentNum); writer.println(") { }"); } public void fieldsConstructor(@NonNull PrintWriter writer, @NonNull Context context, @NonNull Modifier modifier, @NonNull List<Property> properties, String indent, int indentNum) { if (properties.isEmpty()) { return; } openConstructor(writer, modifier, indent, indentNum); writer.println(); properties = properties.stream().filter(property -> !property.isDynamic()).collect(Collectors.toList()); int size = properties.size(); int i = 0; for (Property property : properties) { Utils.printIndent(writer, indent, indentNum + 1); property.printType(writer, context, true, false); writer.print(" "); writer.print(context.getMappedFieldName(property)); if (i != size - 1) { writer.println(","); } else { writer.println(); } ++i; } Utils.printIndent(writer, indent, indentNum); writer.println(") {"); for (Property property : properties) { Utils.printIndent(writer, indent, indentNum + 1); writer.print("this."); writer.print(context.getMappedFieldName(property)); writer.print(" = "); writer.print(context.getMappedFieldName(property)); writer.println(";"); } Utils.printIndent(writer, indent, indentNum); writer.println("}"); } public void copyConstructor(@NonNull PrintWriter writer, @NonNull Context context, @NonNull Modifier modifier, @NonNull List<Property> properties, String indent, int indentNum) { openConstructor(writer, modifier, indent, indentNum); writer.print(getSimpleName()); printGenericParameters(writer, context, false); writer.print(" "); writer.println("source) {"); for (Property property : properties) { if (!property.isDynamic()) { Utils.printIndent(writer, indent, indentNum + 1); writer.print("this."); writer.print(context.getMappedFieldName(property)); writer.print(" = source."); writer.print(context.getMappedFieldName(property)); writer.println(";"); } } Utils.printIndent(writer, indent, indentNum); writer.println("}"); } public void printType(@NonNull PrintWriter writer, @CheckForNull Context context, boolean generic, boolean full) { if (isStatic() || !generic) { writer.print(context != null ? context.relativeName(this) : getQualifiedName()); if (generic) { printGenericParameters(writer, context, full); } } else { if (container == null) { throw new IllegalStateException("This is impossible!"); } container.printType(writer, context, true, full); writer.print("."); writer.print(simpleName); printGenericParameters(writer, context, full); } for (int i = 0; i < array; ++i) { writer.print("[]"); } } public void startInvokeNew(@NonNull PrintWriter writer, @CheckForNull Context context) { writer.print("new "); printType(writer, context, false, false); if (!getParameters().isEmpty()) { writer.print("<>"); } writer.print("("); } public void endInvokeNew(@NonNull PrintWriter writer) { writer.print(")"); } public void printGenericParameters(@NonNull PrintWriter writer, @CheckForNull Context context, boolean full) { printGenericParameters(writer, context, full, true); } public void printGenericParameters(@NonNull PrintWriter writer, @CheckForNull Context context, boolean full, boolean withAngleBrackets) { if (parameters.isEmpty()) { return; } if (withAngleBrackets) { writer.print("<"); } boolean start = true; for (Type parameter : parameters) { if (!start) { writer.print(", "); } parameter.printType(writer, context, true, full); if (full || !parameter.isTypeVar()) { List<Type> upperBounds = parameter.upperBounds; List<Type> lowerBounds = parameter.lowerBounds; if (!upperBounds.isEmpty()) { writer.print(" extends "); for (int i = 0; i < upperBounds.size(); ++i) { upperBounds.get(i).printType(writer, context, true, true); if (i != upperBounds.size() - 1) { writer.print(" & "); } } } if (!lowerBounds.isEmpty()) { writer.print(" super "); for (int i = 0; i < lowerBounds.size(); ++i) { lowerBounds.get(i).printType(writer, context, true, true); if (i != lowerBounds.size() - 1) { writer.print(" & "); } } } } start = false; } if (withAngleBrackets) { writer.print(">"); } } @Override public int hashCode() { return Objects.hash(context, packageName, simpleName, array, annotation, typeVar, wildcard, parameters, container, upperBounds, lowerBounds, cu, tree); } @Override public String toString() { StringWriter stringWriter = new StringWriter(); PrintWriter writer = new PrintWriter(stringWriter); printType(writer, null, true, true); return stringWriter.toString(); } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/Leaf12BeanMeta.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedMeta; @GeneratedMeta( targetClass = Leaf12Bean.class, configClass = Leaf12Bean.class, proxies = { Leaf12BeanViewConfigure.class } ) public class Leaf12BeanMeta { public static final String a = "a"; public static final String b = "b"; public static final String c = "c"; public static final String d = "d"; public static final String e = "e"; public static class Views { public static final String io_github_vipcxj_beanknife_cases_beans_ViewOfLeaf12Bean = "io.github.vipcxj.beanknife.cases.beans.ViewOfLeaf12Bean"; } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/LombokBeanView.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.cases.annotations.MethodAnnotation1; import io.github.vipcxj.beanknife.cases.annotations.PropertyAnnotation1; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedView; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; import lombok.Data; @GeneratedView(targetClass = LombokBean.class, configClass = LombokBeanViewConfigure.class) public class LombokBeanView { private String a; private int b; private List<? extends Class<? extends Data>> c; public LombokBeanView() { } public LombokBeanView( String a, int b, List<? extends Class<? extends Data>> c ) { this.a = a; this.b = b; this.c = c; } public LombokBeanView(LombokBeanView source) { this.a = source.a; this.b = source.b; this.c = source.c; } public LombokBeanView(LombokBean source) { if (source == null) { throw new NullPointerException("The input source argument of the read constructor of class io.github.vipcxj.beanknife.cases.beans.LombokBeanView should not be null."); } this.a = source.getA(); this.b = source.getB(); this.c = source.getC(); } public static LombokBeanView read(LombokBean source) { if (source == null) { return null; } return new LombokBeanView(source); } public static LombokBeanView[] read(LombokBean[] sources) { if (sources == null) { return null; } LombokBeanView[] results = new LombokBeanView[sources.length]; for (int i = 0; i < sources.length; ++i) { results[i] = read(sources[i]); } return results; } public static List<LombokBeanView> read(List<LombokBean> sources) { if (sources == null) { return null; } List<LombokBeanView> results = new ArrayList<>(); for (LombokBean source : sources) { results.add(read(source)); } return results; } public static Set<LombokBeanView> read(Set<LombokBean> sources) { if (sources == null) { return null; } Set<LombokBeanView> results = new HashSet<>(); for (LombokBean source : sources) { results.add(read(source)); } return results; } public static Stack<LombokBeanView> read(Stack<LombokBean> sources) { if (sources == null) { return null; } Stack<LombokBeanView> results = new Stack<>(); for (LombokBean source : sources) { results.add(read(source)); } return results; } public static <K> Map<K, LombokBeanView> read(Map<K, LombokBean> sources) { if (sources == null) { return null; } Map<K, LombokBeanView> results = new HashMap<>(); for (Map.Entry<K, LombokBean> source : sources.entrySet()) { results.put(source.getKey(), read(source.getValue())); } return results; } @PropertyAnnotation1 public String getA() { return this.a; } @MethodAnnotation1 public int getB() { return this.b; } @PropertyAnnotation1 public List<? extends Class<? extends Data>> getC() { return this.c; } } <|start_filename|>beanknife-jpa/src/test/java/io/github/vipcxj/beanknife/jpa/models/Address.java<|end_filename|> package io.github.vipcxj.beanknife.jpa.models; import lombok.Getter; import lombok.Setter; import javax.persistence.Embeddable; @Embeddable @Getter @Setter public class Address { private String city; private String road; private String number; } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/utils/AnnotationSource.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.utils; public enum AnnotationSource { CONFIG, TARGET_TYPE, TARGET_GETTER, TARGET_FIELD } <|start_filename|>beanknife-examples/src/main/java/module-info.java<|end_filename|> module beanknife.examples { requires beanknife.runtime; requires static lombok; } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/ViewOfInNestBean$Bean2$Bean1Meta.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedMeta; @GeneratedMeta( targetClass = ViewOfInNestBean.Bean2.Bean1.class, configClass = ViewOfInNestBean.Bean2.Bean1.class, proxies = { ViewOfInNestBean.Bean2.Bean1.class } ) public class ViewOfInNestBean$Bean2$Bean1Meta { public static final String b = "b"; public static class Views { public static final String io_github_vipcxj_beanknife_cases_beans_ViewOfInNestBean$Bean2$Bean1View = "io.github.vipcxj.beanknife.cases.beans.ViewOfInNestBean$Bean2$Bean1View"; } } <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/beans/GrandparentViewConfigure.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.*; @ViewSerializable(true) @ViewReadConstructor(Access.NONE) @ViewSetters(Access.PROTECTED) @ViewGenNameMapper("${name}Dto") @ViewPropertiesExclude("a") public class GrandparentViewConfigure { } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/MetaAndViewOfOnDiffBean1Meta.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedMeta; @GeneratedMeta( targetClass = MetaAndViewOfOnDiffBean1.class, configClass = MetaAndViewOfOnDiffBean1MetaConfig.class, proxies = { MetaAndViewOfOnDiffBean1ViewConfig.class } ) public class MetaAndViewOfOnDiffBean1Meta { public static final String pa = "pa"; public static final String pb = "pb"; public static class Views { public static final String io_github_vipcxj_beanknife_cases_beans_MetaAndViewOfOnDiffBean1View = "io.github.vipcxj.beanknife.cases.beans.MetaAndViewOfOnDiffBean1View"; } } <|start_filename|>beanknife-jpa/src/test/java/io/github/vipcxj/beanknife/jpa/dao/EmployeeRepository.java<|end_filename|> package io.github.vipcxj.beanknife.jpa.dao; import io.github.vipcxj.beanknife.jpa.models.Employee; import org.springframework.data.jpa.repository.JpaRepository; public interface EmployeeRepository extends JpaRepository<Employee, String> { } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/Parent2ViewConfigure.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.Access; import io.github.vipcxj.beanknife.runtime.annotations.ViewPropertiesExclude; import io.github.vipcxj.beanknife.runtime.annotations.ViewPropertiesInclude; import io.github.vipcxj.beanknife.runtime.annotations.ViewSetters; @ViewSetters(Access.NONE) // Not work, because "a" is excluded by parent configuration. @ViewPropertiesInclude("a") @ViewPropertiesExclude("b") public class Parent2ViewConfigure extends GrandparentViewConfigure { } <|start_filename|>beanknife-jpa/src/test/java/io/github/vipcxj/beanknife/jpa/dto/EmployeeInfoConfiguration.java<|end_filename|> package io.github.vipcxj.beanknife.jpa.dto; import io.github.vipcxj.beanknife.jpa.models.CompanyInfo; import io.github.vipcxj.beanknife.jpa.models.DepartmentInfo; import io.github.vipcxj.beanknife.jpa.models.Employee; import io.github.vipcxj.beanknife.jpa.runtime.annotations.AddJpaSupport; import io.github.vipcxj.beanknife.runtime.annotations.MapViewProperty; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; @ViewOf(Employee.class) @AddJpaSupport public class EmployeeInfoConfiguration extends BaseDtoConfiguration { @MapViewProperty(name = "departmentInfo", map = "department") private DepartmentInfo departmentInfo; @MapViewProperty(name = "companyInfo", map = "company") private CompanyInfo companyInfo; } <|start_filename|>beanknife-jpa/src/test/java/io/github/vipcxj/beanknife/jpa/dto/DepartmentInfoConfiguration.java<|end_filename|> package io.github.vipcxj.beanknife.jpa.dto; import io.github.vipcxj.beanknife.jpa.models.*; import io.github.vipcxj.beanknife.runtime.annotations.MapViewProperty; import io.github.vipcxj.beanknife.runtime.annotations.OverrideViewProperty; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; import java.util.List; @ViewOf(Department.class) public class DepartmentInfoConfiguration extends BaseDtoConfiguration { @MapViewProperty(name = "companyInfo", map = DepartmentMeta.company) private CompanyInfo companyInfo; @OverrideViewProperty(DepartmentMeta.employees) private List<EmployeeInfo> employees; } <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/beans/InvalidPatternViewConfig.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; @ViewOf(value = SimpleBean.class, genName = "SimpleBeanWithInvalidIncludePattern", includePattern = "\\") public class InvalidPatternViewConfig { } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/MetaAndViewOfOnDiffBean1MetaConfig.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.ViewMeta; @ViewMeta(of = MetaAndViewOfOnDiffBean1.class) public class MetaAndViewOfOnDiffBean1MetaConfig { } <|start_filename|>beanknife-jpa-examples/src/main/java/io/github/vipcxj/beanknfie/jpa/examples/models/Department.java<|end_filename|> package io.github.vipcxj.beanknfie.jpa.examples.models; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import java.util.List; @Entity @Getter @Setter @NoArgsConstructor @AllArgsConstructor public class Department { @Id private String number; @ManyToOne private Company company; @OneToMany(mappedBy = "department") private List<Employee> employees; } <|start_filename|>beanknife-spring/src/test/java/io/github/vipcxj/beanknife/spring/test/configures/ViewConfigure.java<|end_filename|> package io.github.vipcxj.beanknife.spring.test.configures; import io.github.vipcxj.beanknife.runtime.annotations.Dynamic; import io.github.vipcxj.beanknife.runtime.annotations.InjectProperty; import io.github.vipcxj.beanknife.runtime.annotations.NewViewProperty; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; import io.github.vipcxj.beanknife.spring.test.beans.SimpleBean; import io.github.vipcxj.beanknife.spring.test.beans.SimpleBeanMeta; import io.github.vipcxj.beanknife.spring.test.beans.SpringBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @ViewOf(value = SimpleBean.class, includePattern = ".*") @Component public class ViewConfigure { private SpringBean springBean; @Autowired public void setSpringBean(SpringBean springBean) { this.springBean = springBean; } @NewViewProperty("ab") @Dynamic public String getAb(@InjectProperty(SimpleBeanMeta.a) int a, @InjectProperty(SimpleBeanMeta.b) String b) { return a + b; } @NewViewProperty("springBean") public SpringBean getSpringBean() { return springBean; } } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/annotations/ViewPropertiesInclude.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.annotations; import java.lang.annotation.*; @Target(ElementType.TYPE) @Retention(RetentionPolicy.SOURCE) @Repeatable(ViewPropertiesIncludes.class) @Inherited public @interface ViewPropertiesInclude { String[] value(); } <|start_filename|>beanknife-jpa/src/main/java/io/github/vipcxj/beanknife/jpa/PropertyType.java<|end_filename|> package io.github.vipcxj.beanknife.jpa; public enum PropertyType { BASEABLE, EXTRACTOR, VIEW, EXTRA } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/annotations/ViewReadConstructor.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.annotations; import java.lang.annotation.*; @Target(ElementType.TYPE) @Retention(RetentionPolicy.SOURCE) @Inherited public @interface ViewReadConstructor { Access value(); } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/WriteableBeanMeta.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedMeta; @GeneratedMeta( targetClass = WriteableBean.class, configClass = WriteableBean.class, proxies = { WriteableBeanViewConfigure.class } ) public class WriteableBeanMeta { public static final String a = "a"; public static final String b = "b"; public static final String c = "c"; public static final String d = "d"; public static final String e = "e"; public static final String f = "f"; public static class Views { public static final String io_github_vipcxj_beanknife_cases_beans_WriteableBeanView = "io.github.vipcxj.beanknife.cases.beans.WriteableBeanView"; } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/GenericBeanView.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedView; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; @GeneratedView(targetClass = GenericBean.class, configClass = GenericBean.class) public class GenericBeanView<T1 extends CharSequence & Set<? extends Character>, T2 extends List<? extends Set<? super String>>> { private T1 a; private T2 b; private List<T1> c; private T2[] d; private List<Map<String, Map<T1, T2>>[]>[] e; public GenericBeanView() { } public GenericBeanView( T1 a, T2 b, List<T1> c, T2[] d, List<Map<String, Map<T1, T2>>[]>[] e ) { this.a = a; this.b = b; this.c = c; this.d = d; this.e = e; } public GenericBeanView(GenericBeanView<T1, T2> source) { this.a = source.a; this.b = source.b; this.c = source.c; this.d = source.d; this.e = source.e; } public GenericBeanView(GenericBean<T1, T2> source) { if (source == null) { throw new NullPointerException("The input source argument of the read constructor of class io.github.vipcxj.beanknife.cases.beans.GenericBeanView should not be null."); } this.a = source.getA(); this.b = source.getB(); this.c = source.getC(); this.d = source.getD(); this.e = source.getE(); } public static <T1 extends CharSequence & Set<? extends Character>, T2 extends List<? extends Set<? super String>>> GenericBeanView<T1, T2> read(GenericBean<T1, T2> source) { if (source == null) { return null; } return new GenericBeanView<>(source); } public static <T1 extends CharSequence & Set<? extends Character>, T2 extends List<? extends Set<? super String>>> GenericBeanView<T1, T2>[] read(GenericBean<T1, T2>[] sources) { if (sources == null) { return null; } GenericBeanView<T1, T2>[] results = new GenericBeanView[sources.length]; for (int i = 0; i < sources.length; ++i) { results[i] = read(sources[i]); } return results; } public static <T1 extends CharSequence & Set<? extends Character>, T2 extends List<? extends Set<? super String>>> List<GenericBeanView<T1, T2>> read(List<GenericBean<T1, T2>> sources) { if (sources == null) { return null; } List<GenericBeanView<T1, T2>> results = new ArrayList<>(); for (GenericBean<T1, T2> source : sources) { results.add(read(source)); } return results; } public static <T1 extends CharSequence & Set<? extends Character>, T2 extends List<? extends Set<? super String>>> Set<GenericBeanView<T1, T2>> read(Set<GenericBean<T1, T2>> sources) { if (sources == null) { return null; } Set<GenericBeanView<T1, T2>> results = new HashSet<>(); for (GenericBean<T1, T2> source : sources) { results.add(read(source)); } return results; } public static <T1 extends CharSequence & Set<? extends Character>, T2 extends List<? extends Set<? super String>>> Stack<GenericBeanView<T1, T2>> read(Stack<GenericBean<T1, T2>> sources) { if (sources == null) { return null; } Stack<GenericBeanView<T1, T2>> results = new Stack<>(); for (GenericBean<T1, T2> source : sources) { results.add(read(source)); } return results; } public static <K, T1 extends CharSequence & Set<? extends Character>, T2 extends List<? extends Set<? super String>>> Map<K, GenericBeanView<T1, T2>> read(Map<K, GenericBean<T1, T2>> sources) { if (sources == null) { return null; } Map<K, GenericBeanView<T1, T2>> results = new HashMap<>(); for (Map.Entry<K, GenericBean<T1, T2>> source : sources.entrySet()) { results.put(source.getKey(), read(source.getValue())); } return results; } public T1 getA() { return this.a; } public T2 getB() { return this.b; } public List<T1> getC() { return this.c; } public T2[] getD() { return this.d; } public List<Map<String, Map<T1, T2>>[]>[] getE() { return this.e; } } <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/beans/LombokBeanViewConfigure.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.cases.annotations.MethodAnnotation1; import io.github.vipcxj.beanknife.cases.annotations.PropertyAnnotation1; import io.github.vipcxj.beanknife.runtime.annotations.*; @ViewOf(LombokBean.class) @ViewOf(LombokBean2.class) @ViewWriteBackMethod(Access.PUBLIC) @UseAnnotation(PropertyAnnotation1.class) @UseAnnotation(MethodAnnotation1.class) public class LombokBeanViewConfigure extends IncludeAllBaseConfigure { } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/converters/NullStringAsEmptyConverter.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.converters; import io.github.vipcxj.beanknife.runtime.PropertyConverter; public class NullStringAsEmptyConverter implements PropertyConverter<String, String> { @Override public String convert(String value) { return value != null ? value : ""; } @Override public String convertBack(String value) { return value; } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/SerializableBeanMeta.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedMeta; @GeneratedMeta( targetClass = SerializableBean.class, configClass = SerializableBean.class, proxies = { SerializableBean.class } ) public class SerializableBeanMeta { public static final String a = "a"; public static final String b = "b"; public static class Views { public static final String io_github_vipcxj_beanknife_cases_beans_SerializableBeanView = "io.github.vipcxj.beanknife.cases.beans.SerializableBeanView"; } } <|start_filename|>beanknife-core-base/src/main/java/io/github/vipcxj/beanknife/core/models/AnnotationUsage.java<|end_filename|> package io.github.vipcxj.beanknife.core.models; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import io.github.vipcxj.beanknife.core.utils.Utils; import io.github.vipcxj.beanknife.runtime.annotations.UnUseAnnotation; import io.github.vipcxj.beanknife.runtime.annotations.UnUseAnnotations; import io.github.vipcxj.beanknife.runtime.annotations.UseAnnotation; import io.github.vipcxj.beanknife.runtime.annotations.UseAnnotations; import io.github.vipcxj.beanknife.runtime.utils.AnnotationDest; import io.github.vipcxj.beanknife.runtime.utils.AnnotationSource; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.util.Elements; import java.util.*; public class AnnotationUsage { private Set<AnnotationSource> from; private Set<AnnotationDest> dest; public static AnnotationUsage from(@NonNull Elements elements, @NonNull AnnotationMirror useAnnotation) { Map<? extends ExecutableElement, ? extends AnnotationValue> values = elements.getElementValuesWithDefaults(useAnnotation); AnnotationUsage usage = new AnnotationUsage(); usage.from = new HashSet<>(Arrays.asList(Utils.getEnumArrayAnnotationValue(useAnnotation, values, "from", AnnotationSource.class))); usage.dest = new HashSet<>(Arrays.asList(Utils.getEnumArrayAnnotationValue(useAnnotation, values, "dest", AnnotationDest.class))); return usage; } @NonNull public static Map<String, AnnotationUsage> collectAnnotationUsages(@NonNull Elements elements, @NonNull Element element, @CheckForNull Map<String, AnnotationUsage> baseUsages) { Map<String, AnnotationUsage> results = baseUsages != null ? new HashMap<>(baseUsages) : new HashMap<>(); List<AnnotationMirror> useAnnotations = Utils.getAnnotationsOn(elements, element, UseAnnotation.class, UseAnnotations.class); List<AnnotationMirror> unUseAnnotations = Utils.getAnnotationsOn(elements, element, UnUseAnnotation.class, UnUseAnnotations.class); for (AnnotationMirror useAnnotation : useAnnotations) { AnnotationUsage annotationUsage = AnnotationUsage.from(elements, useAnnotation); Map<? extends ExecutableElement, ? extends AnnotationValue> values = elements.getElementValuesWithDefaults(useAnnotation); DeclaredType[] types = Utils.getTypeArrayAnnotationValue(useAnnotation, values, "value"); for (DeclaredType type : types) { String key = Utils.toElement(type).getQualifiedName().toString(); results.put(key, annotationUsage); } } for (AnnotationMirror unUseAnnotation : unUseAnnotations) { Map<? extends ExecutableElement, ? extends AnnotationValue> values = elements.getElementValuesWithDefaults(unUseAnnotation); DeclaredType[] types = Utils.getTypeArrayAnnotationValue(unUseAnnotation, values, "value"); for (DeclaredType type : types) { String key = Utils.toElement(type).getQualifiedName().toString(); results.remove(key); } } return results; } @CheckForNull public static Set<AnnotationDest> getAnnotationDest(@NonNull Map<String, AnnotationUsage> useAnnotations, @NonNull AnnotationMirror annotation, AnnotationSource source) { String name = Utils.getAnnotationName(annotation); AnnotationUsage annotationUsage = useAnnotations.get(name); if (annotationUsage == null) { return null; } if (annotationUsage.getFrom().contains(source)) { return annotationUsage.getDest(); } else { return null; } } public Set<AnnotationSource> getFrom() { return from; } public Set<AnnotationDest> getDest() { return dest; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AnnotationUsage that = (AnnotationUsage) o; return Objects.equals(from, that.from) && Objects.equals(dest, that.dest); } @Override public int hashCode() { return Objects.hash(from, dest); } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/ViewPropertyBeanWithoutParent.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedView; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; @GeneratedView(targetClass = ViewPropertyBean.class, configClass = ViewPropertyBeanViewConfig.class) public class ViewPropertyBeanWithoutParent { private int a; private String b; public ViewPropertyBeanWithoutParent() { } public ViewPropertyBeanWithoutParent( int a, String b ) { this.a = a; this.b = b; } public ViewPropertyBeanWithoutParent(ViewPropertyBeanWithoutParent source) { this.a = source.a; this.b = source.b; } public ViewPropertyBeanWithoutParent(ViewPropertyBean source) { if (source == null) { throw new NullPointerException("The input source argument of the read constructor of class io.github.vipcxj.beanknife.cases.beans.ViewPropertyBeanWithoutParent should not be null."); } this.a = source.getA(); this.b = source.getB(); } public static ViewPropertyBeanWithoutParent read(ViewPropertyBean source) { if (source == null) { return null; } return new ViewPropertyBeanWithoutParent(source); } public static ViewPropertyBeanWithoutParent[] read(ViewPropertyBean[] sources) { if (sources == null) { return null; } ViewPropertyBeanWithoutParent[] results = new ViewPropertyBeanWithoutParent[sources.length]; for (int i = 0; i < sources.length; ++i) { results[i] = read(sources[i]); } return results; } public static List<ViewPropertyBeanWithoutParent> read(List<ViewPropertyBean> sources) { if (sources == null) { return null; } List<ViewPropertyBeanWithoutParent> results = new ArrayList<>(); for (ViewPropertyBean source : sources) { results.add(read(source)); } return results; } public static Set<ViewPropertyBeanWithoutParent> read(Set<ViewPropertyBean> sources) { if (sources == null) { return null; } Set<ViewPropertyBeanWithoutParent> results = new HashSet<>(); for (ViewPropertyBean source : sources) { results.add(read(source)); } return results; } public static Stack<ViewPropertyBeanWithoutParent> read(Stack<ViewPropertyBean> sources) { if (sources == null) { return null; } Stack<ViewPropertyBeanWithoutParent> results = new Stack<>(); for (ViewPropertyBean source : sources) { results.add(read(source)); } return results; } public static <K> Map<K, ViewPropertyBeanWithoutParent> read(Map<K, ViewPropertyBean> sources) { if (sources == null) { return null; } Map<K, ViewPropertyBeanWithoutParent> results = new HashMap<>(); for (Map.Entry<K, ViewPropertyBean> source : sources.entrySet()) { results.put(source.getKey(), read(source.getValue())); } return results; } public int getA() { return this.a; } public String getB() { return this.b; } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/MethodHideFieldBean.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.ViewMeta; @ViewMeta public class MethodHideFieldBean { public String test; private String getTest() { return test; } } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/providers/DefaultBeanProvider.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.providers; import io.github.vipcxj.beanknife.runtime.spi.BeanProvider; import io.github.vipcxj.beanknife.runtime.utils.BeanUsage; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; public class DefaultBeanProvider implements BeanProvider { @Override public int getPriority() { return Integer.MIN_VALUE + 1; } @Override public boolean support(Class<?> type, BeanUsage usage) { return true; } @Override public <T> T get(Class<T> type, BeanUsage usage, Object requester) { try { Constructor<T> constructor = type.getConstructor(); return constructor.newInstance(); } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) { return null; } } } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/annotations/NewViewProperty.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Used to add the new property to the generate class. * It should be put on the method. * If {@link Dynamic} is also found on this method, it means this method is the dynamic property method. * If there is no {@link Dynamic} found on this method, it means this method is the static property method.<br/> * The static property method should look like this:<br/> * <pre> * public static PropertyType methodName(SourceType source) * </pre> * The dynamic property method should look like this:<br/> * <pre> * public static PropertyType methodName(@InjectProperty TypeOfPropertyA a, @InjectProperty TypeOfPropertyB b, ...) * </pre> * The static property is initialized in the constructor or read method, and has a related field in the generated class. * However the dynamic property is calculated in the getter method, and has not a related field in the generated class. * */ @Target({ ElementType.FIELD, ElementType.METHOD }) @Retention(RetentionPolicy.SOURCE) public @interface NewViewProperty { /** * The property name. * @return the property name. */ String value(); /** * The access type of the getter methods. By default, inherited from the {@link ViewOf} annotation. * @return the access type of the getter methods */ Access getter() default Access.UNKNOWN; /** * The access type of the setter methods. By default, inherited from the {@link ViewOf} annotation. * @return the access type of the setter methods */ Access setter() default Access.UNKNOWN; } <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/beans/StrangeNamePropertyBean.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.ViewMeta; import java.util.Date; @ViewMeta public class StrangeNamePropertyBean { private int TV; String ABC; private long iI; Date aBC; private boolean _boolean; short _Short; public int getTV() { return TV; } public long getiI() { return iI; } public boolean is_boolean() { return _boolean; } } <|start_filename|>beanknife-core-base/src/main/java/io/github/vipcxj/beanknife/core/ViewOfProcessor.java<|end_filename|> package io.github.vipcxj.beanknife.core; import com.sun.source.util.Trees; import io.github.vipcxj.beanknife.core.models.MetaContext; import io.github.vipcxj.beanknife.core.models.ViewMetaData; import io.github.vipcxj.beanknife.core.models.ViewOfData; import io.github.vipcxj.beanknife.core.utils.JetbrainUtils; import io.github.vipcxj.beanknife.core.utils.Utils; import io.github.vipcxj.beanknife.runtime.annotations.ViewMeta; import io.github.vipcxj.beanknife.runtime.annotations.ViewMetas; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; import io.github.vipcxj.beanknife.runtime.annotations.ViewOfs; import javax.annotation.processing.*; import javax.lang.model.SourceVersion; import javax.lang.model.element.*; import javax.tools.Diagnostic; import javax.tools.JavaFileObject; import java.io.IOException; import java.io.PrintWriter; import java.util.*; @SupportedAnnotationTypes({"io.github.vipcxj.beanknife.runtime.annotations.ViewOf", "io.github.vipcxj.beanknife.runtime.annotations.ViewOfs"}) @SupportedSourceVersion(SourceVersion.RELEASE_8) public class ViewOfProcessor extends AbstractProcessor { private Trees trees; @Override public synchronized void init(ProcessingEnvironment processingEnv) { System.out.println("ViewOfProcessor Init"); super.init(processingEnv); ProcessingEnvironment unwrappedProcessingEnv = JetbrainUtils.jbUnwrap(ProcessingEnvironment.class, this.processingEnv); this.trees = Trees.instance(unwrappedProcessingEnv); } @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { try { for (TypeElement annotation : annotations) { Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(annotation); for (Element element : elements) { if (element.getKind() == ElementKind.CLASS) { List<AnnotationMirror> annotationMirrors = Utils.getAnnotationsOn(processingEnv.getElementUtils(), element, ViewOf.class, ViewOfs.class, false, false); TypeElement typeElement = (TypeElement) element; Set<String> metaClassNames = new HashSet<>(); for (AnnotationMirror annotationMirror : annotationMirrors) { ViewOfData viewOf = ViewOfData.read(processingEnv, annotationMirror, typeElement); if (hasMeta(roundEnv, viewOf.getTargetElement())) { continue; } List<ViewOfData> viewOfDataList = Utils.collectViewOfs(processingEnv, roundEnv, viewOf.getTargetElement()); TypeElement mostImportantViewConfigElement = getMostImportantViewConfigElement(viewOfDataList); if (Objects.equals(typeElement, mostImportantViewConfigElement)) { ViewMetaData viewMetaData = new ViewMetaData("", "", viewOf.getTargetElement(), viewOf.getTargetElement()); MetaContext metaContext = new MetaContext(trees, processingEnv, viewMetaData, viewOfDataList); String metaClassName = metaContext.getGenType().getQualifiedName(); if (!metaClassNames.contains(metaClassName)) { metaClassNames.add(metaClassName); try { List<TypeElement> dependencies = Utils.calcDependencies(viewOf.getTargetElement()); dependencies.add(typeElement); JavaFileObject sourceFile = processingEnv.getFiler().createSourceFile(metaClassName, dependencies.toArray(new Element[0])); try (PrintWriter writer = new PrintWriter(sourceFile.openWriter())) { metaContext.collectData(); metaContext.print(writer); } } catch (IOException e) { processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, e.getMessage()); } } } } } else { processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, ""); } } } } catch (Throwable t) { Utils.logError(processingEnv, t); } return false; } private boolean hasMeta(RoundEnvironment roundEnv, TypeElement targetElement) { Set<? extends Element> candidates = roundEnv.getElementsAnnotatedWith(ViewMeta.class); for (Element candidate : candidates) { if (Utils.shouldIgnoredElement(candidate)) { continue; } List<? extends AnnotationMirror> annotationMirrors = processingEnv.getElementUtils().getAllAnnotationMirrors(candidate); for (AnnotationMirror annotationMirror : annotationMirrors) { if (Utils.isThisAnnotation(annotationMirror, ViewMeta.class)) { if (Utils.isViewMetaTargetTo(processingEnv, annotationMirror, (TypeElement) candidate, targetElement)) { return true; } } } } candidates = roundEnv.getElementsAnnotatedWith(ViewMetas.class); for (Element candidate : candidates) { if (Utils.shouldIgnoredElement(candidate)) { continue; } List<? extends AnnotationMirror> annotationMirrors = processingEnv.getElementUtils().getAllAnnotationMirrors(candidate); for (AnnotationMirror annotationMirror : annotationMirrors) { if (Utils.isThisAnnotation(annotationMirror, ViewMetas.class)) { Map<? extends ExecutableElement, ? extends AnnotationValue> elementValuesWithDefaults = processingEnv.getElementUtils().getElementValuesWithDefaults(annotationMirror); List<AnnotationMirror> viewMetas = Utils.getAnnotationElement(annotationMirror, elementValuesWithDefaults); for (AnnotationMirror viewMeta : viewMetas) { if (Utils.isViewMetaTargetTo(processingEnv, viewMeta, (TypeElement) candidate, targetElement)) { return true; } } } } } return false; } private TypeElement getMostImportantViewConfigElement(List<ViewOfData> viewOfDataList) { return viewOfDataList.stream().map(ViewOfData::getConfigElement).max(Comparator.comparing(e -> e.getQualifiedName().toString())).orElse(null); } } <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/beans/AnnotationBeanViewConfigure.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.cases.annotations.FieldAnnotation1; import io.github.vipcxj.beanknife.cases.annotations.FieldAnnotation2; import io.github.vipcxj.beanknife.cases.annotations.PropertyAnnotation1; import io.github.vipcxj.beanknife.cases.annotations.PropertyAnnotation2; import io.github.vipcxj.beanknife.runtime.annotations.OverrideViewProperty; import io.github.vipcxj.beanknife.runtime.annotations.UnUseAnnotation; import io.github.vipcxj.beanknife.runtime.annotations.UseAnnotation; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; import io.github.vipcxj.beanknife.runtime.utils.AnnotationDest; import io.github.vipcxj.beanknife.runtime.utils.AnnotationSource; import java.util.Date; @ViewOf(value = AnnotationBean.class, includePattern = ".*") @UnUseAnnotation(FieldAnnotation2.class) @UseAnnotation(value = PropertyAnnotation2.class, from = { AnnotationSource.CONFIG, AnnotationSource.TARGET_FIELD }) public class AnnotationBeanViewConfigure extends InheritedAnnotationBeanViewConfigure { @UseAnnotation(FieldAnnotation2.class) @OverrideViewProperty(AnnotationBeanMeta.c) private String[] c; // FieldAnnotation1 can not be put on a method, so this annotation is ignored. @UseAnnotation(value = FieldAnnotation1.class, dest = AnnotationDest.GETTER) // PropertyAnnotation1 is put on the field in the original class, // but will be put on getter method in the generated class. @UseAnnotation(value = PropertyAnnotation1.class, dest = AnnotationDest.GETTER) @OverrideViewProperty(AnnotationBeanMeta.d) private int d; @PropertyAnnotation2(stringValue = "config_e") @OverrideViewProperty(AnnotationBeanMeta.e) private Date e; } <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/annotations/ValueAnnotation2.java<|end_filename|> package io.github.vipcxj.beanknife.cases.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Target; @Target({ ElementType.TYPE, ElementType.METHOD, ElementType.FIELD }) public @interface ValueAnnotation2 { String value() default ""; } <|start_filename|>beanknife-core/src/main/java/module-info.java<|end_filename|> import io.github.vipcxj.beanknife.core.GeneratedMetaProcessor; import io.github.vipcxj.beanknife.core.ViewMetaProcessor; import io.github.vipcxj.beanknife.core.ViewOfProcessor; import javax.annotation.processing.Processor; module beanknife.core { uses io.github.vipcxj.beanknife.core.spi.ViewCodeGenerator; exports io.github.vipcxj.beanknife.core; exports io.github.vipcxj.beanknife.core.models; exports io.github.vipcxj.beanknife.core.spi; exports io.github.vipcxj.beanknife.core.utils; requires jdk.compiler; requires static com.github.spotbugs.annotations; requires beanknife.runtime; requires org.apache.commons.text; provides Processor with ViewMetaProcessor, ViewOfProcessor, GeneratedMetaProcessor; } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/converters/NullFloatAsZeroConverter.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.converters; import io.github.vipcxj.beanknife.runtime.PropertyConverter; public class NullFloatAsZeroConverter implements PropertyConverter<Float, Float> { @Override public Float convert(Float value) { return value != null ? value : 0.0f; } @Override public Float convertBack(Float value) { return value; } } <|start_filename|>beanknife-jpa-examples/src/test/java/io/github/vipcxj/beanknfie/jpa/examples/Tester.java<|end_filename|> package io.github.vipcxj.beanknfie.jpa.examples; import io.github.vipcxj.beanknfie.jpa.examples.models.*; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.context.support.AnnotationConfigContextLoader; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import javax.persistence.criteria.Selection; import java.time.Instant; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Random; @ExtendWith(SpringExtension.class) @ContextConfiguration(classes = JpaConfig.class, loader = AnnotationConfigContextLoader.class) public class Tester { @Autowired private EntityManager em; private Random random = new Random(); private long random() { long unit = 3000 * 24 * 3600; return (long) (random.nextDouble() * unit) - unit / 2; } private Date randomDate(Instant instant) { return Date.from(instant.plusSeconds(random())); } @Test @Transactional public void test() { Random random = new Random(); CriteriaBuilder cb = em.getCriteriaBuilder(); Company company = new Company("001", "google", 10000.0, new Address("Shanhai", "SanQuan Road", "888"), new ArrayList<>(), new ArrayList<>()); em.persist(company); Department department = new Department("001001", company, new ArrayList<>()); company.getDepartments().add(department); em.persist(department); Instant baseBirthDay = Instant.parse("1988-03-24T00:00:00.00Z"); Instant baseEnrollmentDay = Instant.parse("1999-01-03T00:00:00.00Z"); Employee employee = new Employee("001001001", "a", "male", "", randomDate(baseBirthDay), randomDate(baseEnrollmentDay), department, company); department.getEmployees().add(employee); company.getEmployees().add(employee); em.persist(employee); employee = new Employee("001001002", "b", "male", "", randomDate(baseBirthDay), randomDate(baseEnrollmentDay), department, company); department.getEmployees().add(employee); company.getEmployees().add(employee); em.persist(employee); employee = new Employee("001001003", "c", "male", "", randomDate(baseBirthDay), randomDate(baseEnrollmentDay), department, company); department.getEmployees().add(employee); company.getEmployees().add(employee); em.persist(employee); department = new Department("001002", company, new ArrayList<>()); company.getDepartments().add(department); em.persist(department); employee = new Employee("001002001", "d", "male", "", randomDate(baseBirthDay), randomDate(baseEnrollmentDay), department, company); department.getEmployees().add(employee); company.getEmployees().add(employee); em.persist(employee); employee = new Employee("001002002", "e", "male", "", randomDate(baseBirthDay), randomDate(baseEnrollmentDay), department, company); department.getEmployees().add(employee); company.getEmployees().add(employee); em.persist(employee); employee = new Employee("001002003", "f", "male", "", randomDate(baseBirthDay), randomDate(baseEnrollmentDay), department, company); department.getEmployees().add(employee); company.getEmployees().add(employee); em.persist(employee); CriteriaQuery<EmployeeDetail> query = cb.createQuery(EmployeeDetail.class); Root<Employee> employees = query.from(Employee.class); Selection<EmployeeDetail> employeeInfoSelection = EmployeeDetail.toJpaSelection(cb, employees); List<EmployeeDetail> resultList = em.createQuery(query.select(employeeInfoSelection)).getResultList(); for (EmployeeDetail detail : resultList) { System.out.print("{"); System.out.print("number: "); System.out.print(detail.getNumber()); System.out.print(", name: "); System.out.print(detail.getName()); System.out.print(", sex: "); System.out.print(detail.getSex()); System.out.print(", nation: "); System.out.print(detail.getNation()); System.out.print(", companyCode:");; System.out.print(detail.getCompany().getCode()); System.out.print(", companyName:");; System.out.print(detail.getCompany().getName()); System.out.print(", companyMoney:");; System.out.print(detail.getCompany().getMoney()); System.out.print(", companyAddress:"); System.out.print(detail.getCompany().getAddress().toString()); System.out.println("}"); } } } <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/beans/ViewPropertyBean.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.ViewMeta; @ViewMeta public class ViewPropertyBean { private int a; private String b; private ViewPropertyContainerBean parent; public int getA() { return a; } public String getB() { return b; } public ViewPropertyContainerBean getParent() { return parent; } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/NestedGenericBean$StaticChildBeanMeta.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedMeta; @GeneratedMeta( targetClass = NestedGenericBean.StaticChildBean.class, configClass = NestedGenericBean.StaticChildBean.class, proxies = { NestedGenericBean.StaticChildBean.class } ) public class NestedGenericBean$StaticChildBeanMeta { public static final String a = "a"; public static class Views { public static final String io_github_vipcxj_beanknife_cases_beans_NestedGenericBean$StaticChildBeanView = "io.github.vipcxj.beanknife.cases.beans.NestedGenericBean$StaticChildBeanView"; } } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/annotations/ViewProperty.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.annotations; /** * The same as {@link OverrideViewProperty}, * But it is only used in the original class, so no value attribute to specialize the property name. * @see OverrideViewProperty */ public @interface ViewProperty { /** * The access type of the getter methods. By default, public is used. * It can be override by the {@link ViewProperty}, {@link OverrideViewProperty} and {@link NewViewProperty}. * @return the access type of the getter methods */ Access getter() default Access.PUBLIC; /** * The access type of the setter methods. By default, none is used, which means there are no setter method. * It can be override by the {@link ViewProperty}, {@link OverrideViewProperty} and {@link NewViewProperty}. * @return the access type of the setter methods */ Access setter() default Access.NONE; } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/annotations/ViewErrors.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.annotations; import java.lang.annotation.*; @Target(ElementType.TYPE) @Retention(RetentionPolicy.SOURCE) @Inherited public @interface ViewErrors { boolean errorMethods() default true; } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/annotations/ValueAnnotation.java<|end_filename|> package io.github.vipcxj.beanknife.cases.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Target; @Target(ElementType.TYPE_USE) public @interface ValueAnnotation { Class<?>[] type() default ValueAnnotation.class; } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/annotations/ViewGenNameMapper.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.annotations; import java.lang.annotation.*; /** * The mapper of original class name to generated class name.<br/> * For example:<br/> * <code>@ViewGenNameMapper("${name}Dto")</code><br/> * means the class Bean will generate class BeanDto, the class Apple will generate class AppleDto. */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.SOURCE) @Inherited public @interface ViewGenNameMapper { String value(); } <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/beans/MetaAndViewOfOnDiffBean3.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; @ViewOf(includes = {MetaAndViewOfOnDiffBean3Meta.pa, MetaAndViewOfOnDiffBean3Meta.pb}) public class MetaAndViewOfOnDiffBean3 { private String pa; private int pb; public String getPa() { return pa; } public int getPb() { return pb; } } <|start_filename|>beanknife-jpa-examples/src/main/java/io/github/vipcxj/beanknfie/jpa/examples/dto/EmployeeDetailConfiguration.java<|end_filename|> package io.github.vipcxj.beanknfie.jpa.examples.dto; import io.github.vipcxj.beanknfie.jpa.examples.models.CompanyInfo; import io.github.vipcxj.beanknfie.jpa.examples.models.DepartmentInfo; import io.github.vipcxj.beanknfie.jpa.examples.models.Employee; import io.github.vipcxj.beanknife.runtime.annotations.MapViewProperty; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; @ViewOf(value = Employee.class, genName = "EmployeeDetail") public class EmployeeDetailConfiguration extends BaseDtoConfiguration { @MapViewProperty(name = "departmentInfo", map = "department") private DepartmentInfo departmentInfo; @MapViewProperty(name = "companyInfo", map = "company") private CompanyInfo companyInfo; } <|start_filename|>beanknife-spring/src/test/java/io/github/vipcxj/beanknife/spring/test/beans/SimpleBean.java<|end_filename|> package io.github.vipcxj.beanknife.spring.test.beans; public class SimpleBean { private int a; private String b; private boolean c; public int getA() { return a; } public void setA(int a) { this.a = a; } public String getB() { return b; } public void setB(String b) { this.b = b; } public boolean isC() { return c; } public void setC(boolean c) { this.c = c; } } <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/beans/LombokBean.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.cases.annotations.MethodAnnotation1; import io.github.vipcxj.beanknife.cases.annotations.PropertyAnnotation1; import lombok.Data; import lombok.Getter; import lombok.Setter; import java.util.List; @Setter @Getter(onMethod_ = {@PropertyAnnotation1}) public class LombokBean { private String a; @Getter(onMethod_ = {@MethodAnnotation1}) private int b; private List<? extends Class<? extends Data>> c; } <|start_filename|>beanknife-jpa-examples/src/main/java/module-info.java<|end_filename|> open module beanknife.jpa.examples { requires spring.data.jpa; requires beanknife.runtime; requires beanknife.jpa.runtime; requires java.persistence; requires lombok; } <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/beans/WriteableBean.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import java.util.List; import java.util.Set; public class WriteableBean<T> { private String a; private boolean b; private List<? extends Set<? extends T>> c; List<SimpleBean> d; Integer e; private long f; public String getA() { return a; } public void setA(String a) { this.a = a; } public boolean isB() { return b; } public void setB(boolean b) { this.b = b; } public List<? extends Set<? extends T>> getC() { return c; } public void setC(List<? extends Set<? extends T>> c) { this.c = c; } public List<SimpleBean> getD() { return d; } public void setD(List<SimpleBean> d) { this.d = d; } public long getF() { return f; } public void setF(long f) { this.f = f; } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/LombokBeanMeta.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedMeta; @GeneratedMeta( targetClass = LombokBean.class, configClass = LombokBean.class, proxies = { LombokBeanViewConfigure.class } ) public class LombokBeanMeta { public static final String a = "a"; public static final String b = "b"; public static final String c = "c"; public static class Views { public static final String io_github_vipcxj_beanknife_cases_beans_LombokBeanView = "io.github.vipcxj.beanknife.cases.beans.LombokBeanView"; } } <|start_filename|>beanknife-spring/src/main/java/io/github/vipcxj/beanknife/spring/BeanUtils.java<|end_filename|> package io.github.vipcxj.beanknife.spring; import edu.umd.cs.findbugs.annotations.NonNull; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; public class BeanUtils implements ApplicationContextAware { private static ApplicationContext context; @Override public void setApplicationContext(@NonNull ApplicationContext applicationContext) { BeanUtils.context = applicationContext; } public static <T> T getBean(Class<T> type) { if (context == null) { throw new IllegalStateException("The application context is not initialized yet."); } return context.getBean(type); } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/ViewOfInNestBean$Bean1$Bean2$Bean3Meta.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedMeta; @GeneratedMeta( targetClass = ViewOfInNestBean.Bean1.Bean2.Bean3.class, configClass = ViewOfInNestBean.Bean1.Bean2.Bean3.class, proxies = { ViewOfInNestBean.Bean1.Bean2.Bean3.class } ) public class ViewOfInNestBean$Bean1$Bean2$Bean3Meta { public static final String a = "a"; public static final String b = "b"; public static class Views { public static final String io_github_vipcxj_beanknife_cases_beans_ViewOfInNestBean$Bean1$Bean2$Bean3View = "io.github.vipcxj.beanknife.cases.beans.ViewOfInNestBean$Bean1$Bean2$Bean3View"; } } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/converters/NullBigDecimalAsZeroConverter.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.converters; import io.github.vipcxj.beanknife.runtime.PropertyConverter; import java.math.BigDecimal; public class NullBigDecimalAsZeroConverter implements PropertyConverter<BigDecimal, BigDecimal> { @Override public BigDecimal convert(BigDecimal value) { return value != null ? value : BigDecimal.ZERO; } @Override public BigDecimal convertBack(BigDecimal value) { return value; } } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/annotations/MapViewProperty.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * ready to use in next release. */ @Target({ElementType.FIELD, ElementType.METHOD}) @Retention(RetentionPolicy.SOURCE) public @interface MapViewProperty { /** * The property name. Should be unique in the generated class. * @return the property name */ String name(); /** * The property name being mapped. It should be one of the original's properties. * @return The property name being mapped */ String map(); /** * The access type of the getter methods. By default, inherited from the {@link ViewOf} annotation. * @return the access type of the getter methods */ Access getter() default Access.UNKNOWN; /** * The access type of the setter methods. By default, inherited from the {@link ViewOf} annotation. * @return the access type of the setter methods */ Access setter() default Access.UNKNOWN; } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/annotations/ViewPropertiesExclude.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.annotations; import java.lang.annotation.*; @Target(ElementType.TYPE) @Retention(RetentionPolicy.SOURCE) @Repeatable(ViewPropertiesExcludes.class) @Inherited public @interface ViewPropertiesExclude { String[] value(); } <|start_filename|>beanknife-core-base/src/main/java/io/github/vipcxj/beanknife/core/models/Extractor.java<|end_filename|> package io.github.vipcxj.beanknife.core.models; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import io.github.vipcxj.beanknife.core.utils.VarMapper; import io.github.vipcxj.beanknife.runtime.utils.CacheType; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import java.io.PrintWriter; public interface Extractor { boolean check(); @NonNull ViewContext getContext(); @NonNull Type getReturnType(); @CheckForNull Type getContainer(); @NonNull ExecutableElement getExecutableElement(); boolean isDynamic(); default boolean useBeanProvider() { return !getExecutableElement().getModifiers().contains(Modifier.STATIC); } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/MetaAndViewOfOnDiffBean1ViewConfig.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; @ViewOf(value = MetaAndViewOfOnDiffBean1.class, includePattern = ".*", excludes = {MetaAndViewOfOnDiffBean1Meta.pa}) public class MetaAndViewOfOnDiffBean1ViewConfig { } <|start_filename|>beanknife-core-base/src/main/java/io/github/vipcxj/beanknife/core/utils/JetbrainUtils.java<|end_filename|> package io.github.vipcxj.beanknife.core.utils; import java.lang.reflect.Method; public class JetbrainUtils { public static <T> T jbUnwrap(Class<? extends T> iface, T wrapper) { T unwrapped = null; try { final Class<?> apiWrappers = wrapper.getClass().getClassLoader().loadClass("org.jetbrains.jps.javac.APIWrappers"); final Method unwrapMethod = apiWrappers.getDeclaredMethod("unwrap", Class.class, Object.class); unwrapped = iface.cast(unwrapMethod.invoke(null, iface, wrapper)); } catch (Throwable ignored) {} return unwrapped != null? unwrapped : wrapper; } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/Leaf11BeanMeta.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedMeta; @GeneratedMeta( targetClass = Leaf11Bean.class, configClass = Leaf11Bean.class, proxies = { Leaf11BeanViewConfigure.class } ) public class Leaf11BeanMeta { public static final String a = "a"; public static final String b = "b"; public static final String c = "c"; public static final String d = "d"; public static final String e = "e"; public static class Views { public static final String io_github_vipcxj_beanknife_cases_beans_ViewOfLeaf11Bean = "io.github.vipcxj.beanknife.cases.beans.ViewOfLeaf11Bean"; } } <|start_filename|>beanknife-core-base/src/main/java/io/github/vipcxj/beanknife/core/models/StaticMethodExtractor.java<|end_filename|> package io.github.vipcxj.beanknife.core.models; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import io.github.vipcxj.beanknife.core.utils.CollectionUtils; import io.github.vipcxj.beanknife.core.utils.ParamInfo; import io.github.vipcxj.beanknife.core.utils.Utils; import io.github.vipcxj.beanknife.core.utils.VarMapper; import io.github.vipcxj.beanknife.runtime.annotations.ExtraParam; import io.github.vipcxj.beanknife.runtime.annotations.InjectProperty; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.Name; import javax.lang.model.element.VariableElement; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; public class StaticMethodExtractor implements Extractor { @NonNull private final ViewContext context; @CheckForNull private final Type container; @NonNull private final ExecutableElement executableElement; @NonNull private final Type returnType; private final List<ParamInfo> paramInfoList; public StaticMethodExtractor(@NonNull ViewContext context, @NonNull ExecutableElement executableElement) { this.context = context; this.container = Type.extract(context, context.getViewOf().getConfigElement()); this.executableElement = executableElement; Type type = Type.extract(context, executableElement); if (type == null) { context.error("Failed to resolve the return type of property method" + executableElement.getSimpleName() + "."); this.returnType = Type.extract(context, Object.class); } else { this.returnType = type; } this.paramInfoList = collectParamInfoList(context, executableElement); } private static List<ParamInfo> collectParamInfoList(ViewContext context, @NonNull ExecutableElement executableElement) { List<ParamInfo> paramInfoList = new ArrayList<>(); for (VariableElement parameter : executableElement.getParameters()) { ExtraParam extraParam = parameter.getAnnotation(ExtraParam.class); InjectProperty injectProperty = parameter.getAnnotation(InjectProperty.class); if (extraParam != null && injectProperty != null) { context.error("@ExtraParam and @InjectProperty can not be put on the same parameter: " + executableElement.getSimpleName() + "#" + parameter.getSimpleName() + ". The @ExtraParam is ignored."); } if (injectProperty != null) { Property injectedProperty = context.getBaseProperties().stream().filter(property -> property.getName().equals(injectProperty.value())).findAny().orElse(null); if (injectedProperty == null) { context.error("Unable to inject the property " + injectProperty.value() + ", No property named " + injectProperty.value() + " in the original class " + context.getTargetType() + "." ); paramInfoList.add(ParamInfo.unknown(parameter)); } else { paramInfoList.add(ParamInfo.propertyParam(parameter, injectedProperty)); } } else if (extraParam != null) { paramInfoList.add(ParamInfo.extraParam(parameter, extraParam.value())); } else if (isSourceParam(context, parameter)) { paramInfoList.add(ParamInfo.sourceParam(parameter)); } else { paramInfoList.add(ParamInfo.unknown(parameter)); } } return paramInfoList; } private static boolean isSourceParam(@NonNull ViewContext context, @NonNull VariableElement parameter) { Type paramType = Type.extract(context, parameter); List<Type> testTypes = new ArrayList<>(); if (paramType.isTypeVar()) { testTypes.addAll(paramType.getUpperBounds()); if (testTypes.isEmpty()) { testTypes.add(Type.extract(context, Object.class)); } } else { testTypes.add(paramType); } return testTypes.stream().allMatch(testType -> context.getTargetType().canAssignTo(testType)); } @Override public boolean check() { if (container == null) { context.error("Unable to resolve the type config element: " + context.getViewOf().getConfigElement().getQualifiedName()); return false; } Name name = executableElement.getSimpleName(); if (paramInfoList.stream().filter(ParamInfo::isSource).count() > 1) { String params = paramInfoList.stream().filter(ParamInfo::isSource).map(ParamInfo::getParameterName).collect(Collectors.joining(", ")); context.error("There should be at most one source type parameter in the static property method \"" + name + "\". No there are many: " + params + "."); return false; } if (paramInfoList.stream().anyMatch(ParamInfo::isUnknown)) { String params = paramInfoList.stream().filter(ParamInfo::isUnknown).map(ParamInfo::getParameterName).collect(Collectors.joining(", ")); context.error("There are some unknown parameter in the static property method \"" + name + "\": " + params + "."); return false; } List<List<ParamInfo>> checkUnique = CollectionUtils.checkUnique(paramInfoList.stream().filter(ParamInfo::isExtraParam).collect(Collectors.toList()), Comparator.comparing(ParamInfo::getExtraParamName)); if (!checkUnique.isEmpty()) { for (List<ParamInfo> infos : checkUnique) { String params = infos.stream().map(ParamInfo::getParameterName).collect(Collectors.joining(", ")); context.error("" + "There are multi extra parameters with same name \"" + infos.get(0).getExtraParamName() + "\" in the static property method \"" + name + "\". " + "They are " + params + "."); } return false; } for (ParamInfo paramInfo : paramInfoList) { if (paramInfo.isPropertyParam()) { Property injectedProperty = paramInfo.getInjectedProperty(); Type type = Type.extract(context, paramInfo.getVar()); if (!injectedProperty.getType().canAssignTo(type)) { context.error("The type of the inject property parameter " + paramInfo.getParameterName() + " in the static property method " + name + " is illegal. The binding property " + injectedProperty.getName() + " can not be injected into it." ); return false; } } } return true; } @Override @NonNull public ViewContext getContext() { return context; } @Override @CheckForNull public Type getContainer() { return container; } @Override @NonNull public ExecutableElement getExecutableElement() { return executableElement; } @Override @NonNull public Type getReturnType() { return returnType; } @Override public boolean isDynamic() { return false; } public List<ParamInfo> getParamInfoList() { return paramInfoList; } private void printParameter(@NonNull PrintWriter writer, @NonNull ParamInfo paramInfo, @NonNull VarMapper varMapper, boolean useSource) { if (paramInfo.isSource()) { writer.print("source"); } else if (paramInfo.isExtraParam()) { Object key = Objects.requireNonNull(getParamInfoKey(paramInfo)); writer.print(varMapper.getVar(key, paramInfo.getExtraParamName())); } else if (paramInfo.isPropertyParam()) { Property injectedProperty = paramInfo.getInjectedProperty(); if (useSource) { writer.print(injectedProperty.getValueString("source")); } else { writer.print(varMapper.getVar(injectedProperty, injectedProperty.getName())); } } else { writer.print("null"); } } private Object getParamInfoKey(ParamInfo info) { if (info.isExtraParam()) { return context.getExtraParams().get(info.getExtraParamName()); } else { return null; } } private void printConfigBean(PrintWriter writer, @NonNull String requester) { if (getContainer() == null) { throw new IllegalStateException("This is impossible!"); } if (getExecutableElement().getModifiers().contains(Modifier.STATIC)) { getContainer().printType(writer, context, false, false); } else { getContext().printInitConfigureBean(writer, requester, true); } } public void print(PrintWriter writer, @CheckForNull VarMapper varMapper, boolean useSource, @NonNull String indent, int indentNum) { if (varMapper == null) { throw new NullPointerException("This is impossible!"); } printConfigBean(writer, useSource ? "source" : "this"); writer.print("."); writer.print(executableElement.getSimpleName()); if (paramInfoList.size() < 5) { writer.print("("); int i = 0; for (ParamInfo paramInfo : paramInfoList) { printParameter(writer, paramInfo, varMapper, useSource); if (i++ != paramInfoList.size() - 1) { writer.print(", "); } } writer.print(")"); } else { writer.print("("); int i = 0; for (ParamInfo paramInfo : paramInfoList) { writer.println(); Utils.printIndent(writer, indent, indentNum + 1); printParameter(writer, paramInfo, varMapper, useSource); if (i++ != paramInfoList.size() - 1) { writer.print(", "); } } writer.println(); Utils.printIndent(writer, indent, indentNum); writer.print(")"); } } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/ViewOfDirectOnBean.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; @ViewOf(includePattern = ".*") public class ViewOfDirectOnBean { private long a; private String b; public long getA() { return a; } public String getB() { return b; } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/StrangeNamePropertyBeanMeta.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedMeta; @GeneratedMeta(targetClass = StrangeNamePropertyBean.class, configClass = StrangeNamePropertyBean.class) public class StrangeNamePropertyBeanMeta { public static final String TV = "TV"; public static final String ABC = "ABC"; public static final String iI = "iI"; public static final String aBC = "aBC"; public static final String _boolean = "_boolean"; public static final String _Short = "_Short"; } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/SimpleBeanWithoutGetters.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedView; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; @GeneratedView(targetClass = SimpleBean.class, configClass = GetterAccessViewConfig.class) public class SimpleBeanWithoutGetters { private String a; private Integer b; private long c; public SimpleBeanWithoutGetters() { } public SimpleBeanWithoutGetters( String a, Integer b, long c ) { this.a = a; this.b = b; this.c = c; } public SimpleBeanWithoutGetters(SimpleBeanWithoutGetters source) { this.a = source.a; this.b = source.b; this.c = source.c; } public SimpleBeanWithoutGetters(SimpleBean source) { if (source == null) { throw new NullPointerException("The input source argument of the read constructor of class io.github.vipcxj.beanknife.cases.beans.SimpleBeanWithoutGetters should not be null."); } this.a = source.getA(); this.b = source.getB(); this.c = source.getC(); } public static SimpleBeanWithoutGetters read(SimpleBean source) { if (source == null) { return null; } return new SimpleBeanWithoutGetters(source); } public static SimpleBeanWithoutGetters[] read(SimpleBean[] sources) { if (sources == null) { return null; } SimpleBeanWithoutGetters[] results = new SimpleBeanWithoutGetters[sources.length]; for (int i = 0; i < sources.length; ++i) { results[i] = read(sources[i]); } return results; } public static List<SimpleBeanWithoutGetters> read(List<SimpleBean> sources) { if (sources == null) { return null; } List<SimpleBeanWithoutGetters> results = new ArrayList<>(); for (SimpleBean source : sources) { results.add(read(source)); } return results; } public static Set<SimpleBeanWithoutGetters> read(Set<SimpleBean> sources) { if (sources == null) { return null; } Set<SimpleBeanWithoutGetters> results = new HashSet<>(); for (SimpleBean source : sources) { results.add(read(source)); } return results; } public static Stack<SimpleBeanWithoutGetters> read(Stack<SimpleBean> sources) { if (sources == null) { return null; } Stack<SimpleBeanWithoutGetters> results = new Stack<>(); for (SimpleBean source : sources) { results.add(read(source)); } return results; } public static <K> Map<K, SimpleBeanWithoutGetters> read(Map<K, SimpleBean> sources) { if (sources == null) { return null; } Map<K, SimpleBeanWithoutGetters> results = new HashMap<>(); for (Map.Entry<K, SimpleBean> source : sources.entrySet()) { results.put(source.getKey(), read(source.getValue())); } return results; } } <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/beans/GetterAccessViewConfig.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.Access; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; @ViewOf(value = SimpleBean.class, genName = "SimpleBeanWithDefaultGetters", includePattern = ".*", getters = Access.DEFAULT) @ViewOf(value = SimpleBean.class, genName = "SimpleBeanWithPrivateGetters", includePattern = ".*", getters = Access.PRIVATE) @ViewOf(value = SimpleBean.class, genName = "SimpleBeanWithProtectedGetters", includePattern = ".*", getters = Access.PROTECTED) @ViewOf(value = SimpleBean.class, genName = "SimpleBeanWithUnknownGetters", includePattern = ".*", getters = Access.UNKNOWN) @ViewOf(value = SimpleBean.class, genName = "SimpleBeanWithoutGetters", includePattern = ".*", getters = Access.NONE) public class GetterAccessViewConfig { } <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/beans/AnnotationBean.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.cases.annotations.*; import io.github.vipcxj.beanknife.cases.models.AEnum; import java.util.Date; import java.util.List; @TypeAnnotation(Date.class) @DocumentedTypeAnnotation(enumValue = AEnum.B, enumValues = {AEnum.C, AEnum.B, AEnum.A}) public class AnnotationBean extends BaseAnnotationBean { @FieldAnnotation1(doubleArray = 1.0) private String a; @FieldAnnotation2(annotation = @ValueAnnotation1(type = Date.class)) private String b; @FieldAnnotation1(charValue = '0') @FieldAnnotation2(stringArray = "5") private String[] c; @FieldAnnotation1(annotations = { @ValueAnnotation1(), @ValueAnnotation1(type = AnnotationBean.class) }) @PropertyAnnotation1 private int d; @PropertyAnnotation2(stringValue = "field_e") private Date e; @PropertyAnnotation2(stringValue = "field_f") private List<String> f; @PropertyAnnotation1(stringValue = "field_g") private short g; public String getA() { return a; } public void setA(String a) { this.a = a; } public String getB() { return b; } public void setB(String b) { this.b = b; } public String[] getC() { return c; } public void setC(String[] c) { this.c = c; } @MethodAnnotation1( charValue = 'a', annotations = { @ValueAnnotation1, @ValueAnnotation1( annotations = @ValueAnnotation2 ) } ) public int getD() { return d; } public void setD(int d) { this.d = d; } @PropertyAnnotation2(stringValue = "getter_e") public Date getE() { return e; } @PropertyAnnotation2(stringValue = "getter_f") public List<String> getF() { return f; } @PropertyAnnotation1(stringValue = "getter_g") public short getG() { return g; } } <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/beans/FieldBeanViewConfig.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; @ViewOf(value = FieldBean.class, includePattern = ".*") public class FieldBeanViewConfig { } <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/beans/StaticMethodPropertyBeanViewConfig.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.*; import java.math.BigInteger; @ViewOf(value = SimpleBean.class, genName = "StaticMethodPropertyBeanView") public class StaticMethodPropertyBeanViewConfig extends IncludeAllBaseConfigure { @NewViewProperty("one") public static int getOne(){ return 1; } @OverrideViewProperty(SimpleBeanMeta.b) public static Object getB() { return null; } @NewViewProperty("d") public static Integer getD(SimpleBean bean) { return bean.getB(); } @NewViewProperty("e") public static Integer getE(SimpleBean bean) { return bean.getB(); } @MapViewProperty(name = "newA", map = SimpleBeanMeta.a) public static String newA(@InjectProperty(SimpleBeanMeta.a) String a) { return a != null ? a + "-new" : "new"; } @MapViewProperty(name = "newC", map = SimpleBeanMeta.c) public BigInteger newC(@InjectProperty(SimpleBeanMeta.b) Integer b, @InjectProperty(SimpleBeanMeta.c) long c) { return BigInteger.valueOf((b != null ? b : 0) + c); } /** * test non static method as a static method property. * Though the source can be compiled, * this will cause a exception in the runtime. Because {@link ViewOf#useDefaultBeanProvider()} is false here. * So no bean provider is used. Then the configure class {@link StaticMethodPropertyBeanViewConfig} can not be initialized. * @param source the original instance. * @return the property value */ @NewViewProperty("e") public String getABC(SimpleBean source) { return source.getA() + source.getB() + source.getC(); } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/annotations/DocumentedTypeAnnotation.java<|end_filename|> package io.github.vipcxj.beanknife.cases.annotations; import io.github.vipcxj.beanknife.cases.models.AEnum; import java.lang.annotation.*; @Documented @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface DocumentedTypeAnnotation { AEnum enumValue() default AEnum.A; AEnum[] enumValues() default {}; } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/utils/AnnotationDest.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.utils; import java.lang.annotation.ElementType; public enum AnnotationDest { SAME, TYPE, FIELD, GETTER, SETTER; public ElementType toElementType() { switch (this) { case TYPE: return ElementType.TYPE; case FIELD: return ElementType.FIELD; case GETTER: case SETTER: return ElementType.METHOD; default: throw new UnsupportedOperationException(); } } } <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/models/AEnum.java<|end_filename|> package io.github.vipcxj.beanknife.cases.models; public enum AEnum { A, B, C } <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/beans/ViewPropertyWithExtraBean.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import java.util.List; import java.util.Map; import java.util.Set; public class ViewPropertyWithExtraBean { private SimpleBean a; private Map<String, List<SimpleBean[]>> b; private Set<SimpleBean> c; public SimpleBean getA() { return a; } public Map<String, List<SimpleBean[]>> getB() { return b; } public Set<SimpleBean> getC() { return c; } } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/utils/Self.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.utils; /** * Refers to the class being annotated. */ public class Self { } <|start_filename|>beanknife-jpa-examples/src/main/java/io/github/vipcxj/beanknfie/jpa/examples/dto/DepartmentInfoConfiguration.java<|end_filename|> package io.github.vipcxj.beanknfie.jpa.examples.dto; import io.github.vipcxj.beanknfie.jpa.examples.models.Department; import io.github.vipcxj.beanknfie.jpa.examples.models.DepartmentMeta; import io.github.vipcxj.beanknfie.jpa.examples.models.EmployeeInfo; import io.github.vipcxj.beanknife.runtime.annotations.OverrideViewProperty; import io.github.vipcxj.beanknife.runtime.annotations.RemoveViewProperty; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; import java.util.List; @ViewOf(Department.class) @RemoveViewProperty(DepartmentMeta.company) public class DepartmentInfoConfiguration extends BaseDtoConfiguration { @OverrideViewProperty(DepartmentMeta.employees) private List<EmployeeInfo> employees; } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/SimpleBeanMeta.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedMeta; @GeneratedMeta( targetClass = SimpleBean.class, configClass = SimpleBean.class, proxies = { ExtraProperty1ViewConfigure.class, StaticMethodPropertyBeanViewConfig.class, ExtraProperty2ViewConfigure.class, ExtraParamsViewConfigure.class, DynamicMethodPropertyBeanViewConfig.class, MapPropertiesViewConfigure.class, InvalidPatternViewConfig.class, SimpleBean.class, SetterAccessViewConfig.class, GenClassShouldUniqueViewConfig.class, GetterAccessViewConfig.class } ) public class SimpleBeanMeta { public static final String a = "a"; public static final String b = "b"; public static final String c = "c"; public static class Views { public static final String io_github_vipcxj_beanknife_cases_beans_ExtraProperties1BeanView = "io.github.vipcxj.beanknife.cases.beans.ExtraProperties1BeanView"; public static final String io_github_vipcxj_beanknife_cases_beans_StaticMethodPropertyBeanView = "io.github.vipcxj.beanknife.cases.beans.StaticMethodPropertyBeanView"; public static final String io_github_vipcxj_beanknife_cases_beans_ExtraProperties2BeanView = "io.github.vipcxj.beanknife.cases.beans.ExtraProperties2BeanView"; public static final String io_github_vipcxj_beanknife_cases_beans_ExtraParamsBeanView = "io.github.vipcxj.beanknife.cases.beans.ExtraParamsBeanView"; public static final String io_github_vipcxj_beanknife_cases_beans_DynamicMethodPropertyBeanView = "io.github.vipcxj.beanknife.cases.beans.DynamicMethodPropertyBeanView"; public static final String io_github_vipcxj_beanknife_cases_beans_MapPropertiesView = "io.github.vipcxj.beanknife.cases.beans.MapPropertiesView"; public static final String io_github_vipcxj_beanknife_cases_beans_SimpleBeanWithInvalidIncludePattern = "io.github.vipcxj.beanknife.cases.beans.SimpleBeanWithInvalidIncludePattern"; public static final String io_github_vipcxj_beanknife_cases_beans_SimpleBeanView = "io.github.vipcxj.beanknife.cases.beans.SimpleBeanView"; public static final String io_github_vipcxj_beanknife_cases_beans_SimpleBeanWithDefaultSetters = "io.github.vipcxj.beanknife.cases.beans.SimpleBeanWithDefaultSetters"; public static final String io_github_vipcxj_beanknife_cases_beans_SimpleBeanWithPrivateSetters = "io.github.vipcxj.beanknife.cases.beans.SimpleBeanWithPrivateSetters"; public static final String io_github_vipcxj_beanknife_cases_beans_SimpleBeanWithProtectedSetters = "io.github.vipcxj.beanknife.cases.beans.SimpleBeanWithProtectedSetters"; public static final String io_github_vipcxj_beanknife_cases_beans_SimpleBeanWithDefaultSetters_ = "io.github.vipcxj.beanknife.cases.beans.SimpleBeanWithDefaultSetters"; public static final String io_github_vipcxj_beanknife_cases_beans_SimpleBeanWithUnknownSetters = "io.github.vipcxj.beanknife.cases.beans.SimpleBeanWithUnknownSetters"; public static final String io_github_vipcxj_beanknife_cases_beans_SimpleBeanViewNotUnique = "io.github.vipcxj.beanknife.cases.beans.SimpleBeanViewNotUnique"; public static final String io_github_vipcxj_beanknife_cases_beans_SimpleBeanViewNotUnique_ = "io.github.vipcxj.beanknife.cases.beans.SimpleBeanViewNotUnique"; public static final String io_github_vipcxj_beanknife_cases_beans_SimpleBeanWithDefaultGetters = "io.github.vipcxj.beanknife.cases.beans.SimpleBeanWithDefaultGetters"; public static final String io_github_vipcxj_beanknife_cases_beans_SimpleBeanWithPrivateGetters = "io.github.vipcxj.beanknife.cases.beans.SimpleBeanWithPrivateGetters"; public static final String io_github_vipcxj_beanknife_cases_beans_SimpleBeanWithProtectedGetters = "io.github.vipcxj.beanknife.cases.beans.SimpleBeanWithProtectedGetters"; public static final String io_github_vipcxj_beanknife_cases_beans_SimpleBeanWithUnknownGetters = "io.github.vipcxj.beanknife.cases.beans.SimpleBeanWithUnknownGetters"; public static final String io_github_vipcxj_beanknife_cases_beans_SimpleBeanWithoutGetters = "io.github.vipcxj.beanknife.cases.beans.SimpleBeanWithoutGetters"; } } <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/beans/BaseAnnotationBean.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.cases.annotations.FieldAnnotation1; import io.github.vipcxj.beanknife.cases.annotations.InheritableTypeAnnotation; import io.github.vipcxj.beanknife.cases.annotations.ValueAnnotation1; import io.github.vipcxj.beanknife.cases.models.AEnum; @InheritableTypeAnnotation( annotation = @ValueAnnotation1(type = int.class), annotations = { @ValueAnnotation1(type = void.class), @ValueAnnotation1(type = String.class), @ValueAnnotation1(type = int[][][].class), @ValueAnnotation1(type = Void.class), @ValueAnnotation1(type = Void[].class) } ) public class BaseAnnotationBean { @FieldAnnotation1(enumClassArray = {AEnum.class, AEnum.class}) public Class<?> type; } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/ViewPropertyBeanMeta.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedMeta; @GeneratedMeta( targetClass = ViewPropertyBean.class, configClass = ViewPropertyBean.class, proxies = { ViewPropertyBeanViewConfig.class } ) public class ViewPropertyBeanMeta { public static final String a = "a"; public static final String b = "b"; public static final String parent = "parent"; public static class Views { public static final String io_github_vipcxj_beanknife_cases_beans_ViewPropertyBeanWithoutParent = "io.github.vipcxj.beanknife.cases.beans.ViewPropertyBeanWithoutParent"; } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/SetterAccessViewConfig.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.Access; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; @ViewOf(value = SimpleBean.class, genName = "SimpleBeanWithDefaultSetters", includePattern = ".*", setters = Access.DEFAULT) @ViewOf(value = SimpleBean.class, genName = "SimpleBeanWithPrivateSetters", includePattern = ".*", setters = Access.PRIVATE) @ViewOf(value = SimpleBean.class, genName = "SimpleBeanWithProtectedSetters", includePattern = ".*", setters = Access.PROTECTED) @ViewOf(value = SimpleBean.class, genName = "SimpleBeanWithDefaultSetters", includePattern = ".*", setters = Access.PUBLIC) @ViewOf(value = SimpleBean.class, genName = "SimpleBeanWithUnknownSetters", includePattern = ".*", setters = Access.UNKNOWN) public class SetterAccessViewConfig { } <|start_filename|>beanknife-core-base/src/main/java/io/github/vipcxj/beanknife/core/utils/ObjectsCompatible.java<|end_filename|> package io.github.vipcxj.beanknife.core.utils; import java.util.function.Supplier; public class ObjectsCompatible { /** * Returns the first argument if it is non-{@code null} and otherwise * returns the non-{@code null} value of {@code supplier.get()}. * * @param obj an object * @param supplier of a non-{@code null} object to return if the first argument * is {@code null} * @param <T> the type of the first argument and return type * @return the first argument if it is non-{@code null} and otherwise * the value from {@code supplier.get()} if it is non-{@code null} * @throws NullPointerException if both {@code obj} is null and * either the {@code supplier} is {@code null} or * the {@code supplier.get()} value is {@code null} * @since 9 */ public static <T> T requireNonNullElseGet(T obj, Supplier<? extends T> supplier) { return (obj != null) ? obj : java.util.Objects.requireNonNull(java.util.Objects.requireNonNull(supplier, "supplier").get(), "supplier.get()"); } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/NestedGenericBeanView.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedView; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; @GeneratedView(targetClass = NestedGenericBean.class, configClass = NestedGenericBean.class) public class NestedGenericBeanView<T1 extends CharSequence & Set<? extends Character>, T2 extends List<? extends Set<? super String>>> { private T1 a; private T2 b; public NestedGenericBeanView() { } public NestedGenericBeanView( T1 a, T2 b ) { this.a = a; this.b = b; } public NestedGenericBeanView(NestedGenericBeanView<T1, T2> source) { this.a = source.a; this.b = source.b; } public NestedGenericBeanView(NestedGenericBean<T1, T2> source) { if (source == null) { throw new NullPointerException("The input source argument of the read constructor of class io.github.vipcxj.beanknife.cases.beans.NestedGenericBeanView should not be null."); } this.a = source.getA(); this.b = source.getB(); } public static <T1 extends CharSequence & Set<? extends Character>, T2 extends List<? extends Set<? super String>>> NestedGenericBeanView<T1, T2> read(NestedGenericBean<T1, T2> source) { if (source == null) { return null; } return new NestedGenericBeanView<>(source); } public static <T1 extends CharSequence & Set<? extends Character>, T2 extends List<? extends Set<? super String>>> NestedGenericBeanView<T1, T2>[] read(NestedGenericBean<T1, T2>[] sources) { if (sources == null) { return null; } NestedGenericBeanView<T1, T2>[] results = new NestedGenericBeanView[sources.length]; for (int i = 0; i < sources.length; ++i) { results[i] = read(sources[i]); } return results; } public static <T1 extends CharSequence & Set<? extends Character>, T2 extends List<? extends Set<? super String>>> List<NestedGenericBeanView<T1, T2>> read(List<NestedGenericBean<T1, T2>> sources) { if (sources == null) { return null; } List<NestedGenericBeanView<T1, T2>> results = new ArrayList<>(); for (NestedGenericBean<T1, T2> source : sources) { results.add(read(source)); } return results; } public static <T1 extends CharSequence & Set<? extends Character>, T2 extends List<? extends Set<? super String>>> Set<NestedGenericBeanView<T1, T2>> read(Set<NestedGenericBean<T1, T2>> sources) { if (sources == null) { return null; } Set<NestedGenericBeanView<T1, T2>> results = new HashSet<>(); for (NestedGenericBean<T1, T2> source : sources) { results.add(read(source)); } return results; } public static <T1 extends CharSequence & Set<? extends Character>, T2 extends List<? extends Set<? super String>>> Stack<NestedGenericBeanView<T1, T2>> read(Stack<NestedGenericBean<T1, T2>> sources) { if (sources == null) { return null; } Stack<NestedGenericBeanView<T1, T2>> results = new Stack<>(); for (NestedGenericBean<T1, T2> source : sources) { results.add(read(source)); } return results; } public static <K, T1 extends CharSequence & Set<? extends Character>, T2 extends List<? extends Set<? super String>>> Map<K, NestedGenericBeanView<T1, T2>> read(Map<K, NestedGenericBean<T1, T2>> sources) { if (sources == null) { return null; } Map<K, NestedGenericBeanView<T1, T2>> results = new HashMap<>(); for (Map.Entry<K, NestedGenericBean<T1, T2>> source : sources.entrySet()) { results.put(source.getKey(), read(source.getValue())); } return results; } public T1 getA() { return this.a; } public T2 getB() { return this.b; } } <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/beans/LombokBean2.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.cases.annotations.MethodAnnotation1; import io.github.vipcxj.beanknife.cases.annotations.PropertyAnnotation1; import lombok.AccessLevel; import lombok.Data; import lombok.Getter; import lombok.Setter; import java.util.List; @Data public class LombokBean2 { private String a; @Getter(value = AccessLevel.PROTECTED, onMethod_ = {@MethodAnnotation1}) private int b; private List<? extends Class<? extends Data>> c; final private long d; } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/BeanB.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; public class BeanB { // (6) private String a; private BeanA beanA; private String shouldBeRemoved; public String getA() { return a; } public BeanA getBeanA() { return beanA; } public String getShouldBeRemoved() { return shouldBeRemoved; } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/MetaAndViewOfOnDiffBean4.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; public class MetaAndViewOfOnDiffBean4 { private String pa; private int pb; public String getPa() { return pa; } public int getPb() { return pb; } @ViewOf(includePattern = ".*", excludes = {MetaAndViewOfOnDiffBean4$NestedBeanMeta.paOfParent}) class NestedBean { private final String paOfParent; private final String pa; private int pb; public NestedBean(String pa, int pb) { this.pa = pa; this.pb = pb; this.paOfParent = MetaAndViewOfOnDiffBean4.this.pa; } public String getPaOfParent() { return paOfParent; } public String getPa() { return pa; } public int getPb() { return pb; } } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/ConverterBeanMeta.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedMeta; @GeneratedMeta( targetClass = ConverterBean.class, configClass = ConverterBeanConfig.class, proxies = { ConverterBeanConfig.class } ) public class ConverterBeanMeta { public static final String a = "a"; public static final String b = "b"; public static class Views { public static final String io_github_vipcxj_beanknife_cases_beans_ConverterBeanView = "io.github.vipcxj.beanknife.cases.beans.ConverterBeanView"; } } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/annotations/UsePropertyConverter.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.annotations; import io.github.vipcxj.beanknife.runtime.PropertyConverter; import java.lang.annotation.*; /** * Used to specialize the converter. Multi converters are supported. The annotation process will select a suitable one from them. */ @Target({ ElementType.FIELD, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) @Repeatable(UsePropertyConverters.class) public @interface UsePropertyConverter { /** * The converter type. * @return the converter type. */ Class<? extends PropertyConverter<?, ?>> value(); } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/MetaAndViewOfBothOnBeanView.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedView; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; @GeneratedView(targetClass = MetaAndViewOfBothOnBean.class, configClass = MetaAndViewOfBothOnBean.class) public class MetaAndViewOfBothOnBeanView { private int a; private String c; private Date e; public MetaAndViewOfBothOnBeanView() { } public MetaAndViewOfBothOnBeanView( int a, String c, Date e ) { this.a = a; this.c = c; this.e = e; } public MetaAndViewOfBothOnBeanView(MetaAndViewOfBothOnBeanView source) { this.a = source.a; this.c = source.c; this.e = source.e; } public MetaAndViewOfBothOnBeanView(MetaAndViewOfBothOnBean source) { if (source == null) { throw new NullPointerException("The input source argument of the read constructor of class io.github.vipcxj.beanknife.cases.beans.MetaAndViewOfBothOnBeanView should not be null."); } this.a = source.getA(); this.c = source.getC(); this.e = source.getE(); } public static MetaAndViewOfBothOnBeanView read(MetaAndViewOfBothOnBean source) { if (source == null) { return null; } return new MetaAndViewOfBothOnBeanView(source); } public static MetaAndViewOfBothOnBeanView[] read(MetaAndViewOfBothOnBean[] sources) { if (sources == null) { return null; } MetaAndViewOfBothOnBeanView[] results = new MetaAndViewOfBothOnBeanView[sources.length]; for (int i = 0; i < sources.length; ++i) { results[i] = read(sources[i]); } return results; } public static List<MetaAndViewOfBothOnBeanView> read(List<MetaAndViewOfBothOnBean> sources) { if (sources == null) { return null; } List<MetaAndViewOfBothOnBeanView> results = new ArrayList<>(); for (MetaAndViewOfBothOnBean source : sources) { results.add(read(source)); } return results; } public static Set<MetaAndViewOfBothOnBeanView> read(Set<MetaAndViewOfBothOnBean> sources) { if (sources == null) { return null; } Set<MetaAndViewOfBothOnBeanView> results = new HashSet<>(); for (MetaAndViewOfBothOnBean source : sources) { results.add(read(source)); } return results; } public static Stack<MetaAndViewOfBothOnBeanView> read(Stack<MetaAndViewOfBothOnBean> sources) { if (sources == null) { return null; } Stack<MetaAndViewOfBothOnBeanView> results = new Stack<>(); for (MetaAndViewOfBothOnBean source : sources) { results.add(read(source)); } return results; } public static <K> Map<K, MetaAndViewOfBothOnBeanView> read(Map<K, MetaAndViewOfBothOnBean> sources) { if (sources == null) { return null; } Map<K, MetaAndViewOfBothOnBeanView> results = new HashMap<>(); for (Map.Entry<K, MetaAndViewOfBothOnBean> source : sources.entrySet()) { results.put(source.getKey(), read(source.getValue())); } return results; } public int getA() { return this.a; } public String getC() { return this.c; } public Date getE() { return this.e; } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/ExtraProperties1BeanView.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedView; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; @GeneratedView(targetClass = SimpleBean.class, configClass = ExtraProperty1ViewConfigure.class) public class ExtraProperties1BeanView { private String a; private Integer b; private long c; private List<Date> x; public ExtraProperties1BeanView() { } public ExtraProperties1BeanView( String a, Integer b, long c, List<Date> x ) { this.a = a; this.b = b; this.c = c; this.x = x; } public ExtraProperties1BeanView(ExtraProperties1BeanView source) { this.a = source.a; this.b = source.b; this.c = source.c; this.x = source.x; } public ExtraProperties1BeanView(SimpleBean source, List<Date> x) { if (source == null) { throw new NullPointerException("The input source argument of the read constructor of class io.github.vipcxj.beanknife.cases.beans.ExtraProperties1BeanView should not be null."); } this.a = source.getA(); this.b = source.getB(); this.c = source.getC(); this.x = x; } public static ExtraProperties1BeanView read(SimpleBean source, List<Date> x) { if (source == null) { return null; } return new ExtraProperties1BeanView(source, x); } public String getA() { return this.a; } public Integer getB() { return this.b; } public long getC() { return this.c; } public List<Date> getX() { return this.x; } } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/annotations/ViewConfigureBeanCacheType.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.annotations; import io.github.vipcxj.beanknife.runtime.utils.CacheType; import java.lang.annotation.*; @Target(ElementType.TYPE) @Retention(RetentionPolicy.SOURCE) @Inherited public @interface ViewConfigureBeanCacheType { CacheType value(); } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/MetaAndViewOfOnDiffBean4$NestedBeanView.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedView; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; @GeneratedView(targetClass = MetaAndViewOfOnDiffBean4.NestedBean.class, configClass = MetaAndViewOfOnDiffBean4.NestedBean.class) public class MetaAndViewOfOnDiffBean4$NestedBeanView { private String pa; private int pb; public MetaAndViewOfOnDiffBean4$NestedBeanView() { } public MetaAndViewOfOnDiffBean4$NestedBeanView( String pa, int pb ) { this.pa = pa; this.pb = pb; } public MetaAndViewOfOnDiffBean4$NestedBeanView(MetaAndViewOfOnDiffBean4$NestedBeanView source) { this.pa = source.pa; this.pb = source.pb; } public MetaAndViewOfOnDiffBean4$NestedBeanView(MetaAndViewOfOnDiffBean4.NestedBean source) { if (source == null) { throw new NullPointerException("The input source argument of the read constructor of class io.github.vipcxj.beanknife.cases.beans.MetaAndViewOfOnDiffBean4$NestedBeanView should not be null."); } this.pa = source.getPa(); this.pb = source.getPb(); } public static MetaAndViewOfOnDiffBean4$NestedBeanView read(MetaAndViewOfOnDiffBean4.NestedBean source) { if (source == null) { return null; } return new MetaAndViewOfOnDiffBean4$NestedBeanView(source); } public static MetaAndViewOfOnDiffBean4$NestedBeanView[] read(MetaAndViewOfOnDiffBean4.NestedBean[] sources) { if (sources == null) { return null; } MetaAndViewOfOnDiffBean4$NestedBeanView[] results = new MetaAndViewOfOnDiffBean4$NestedBeanView[sources.length]; for (int i = 0; i < sources.length; ++i) { results[i] = read(sources[i]); } return results; } public static List<MetaAndViewOfOnDiffBean4$NestedBeanView> read(List<MetaAndViewOfOnDiffBean4.NestedBean> sources) { if (sources == null) { return null; } List<MetaAndViewOfOnDiffBean4$NestedBeanView> results = new ArrayList<>(); for (MetaAndViewOfOnDiffBean4.NestedBean source : sources) { results.add(read(source)); } return results; } public static Set<MetaAndViewOfOnDiffBean4$NestedBeanView> read(Set<MetaAndViewOfOnDiffBean4.NestedBean> sources) { if (sources == null) { return null; } Set<MetaAndViewOfOnDiffBean4$NestedBeanView> results = new HashSet<>(); for (MetaAndViewOfOnDiffBean4.NestedBean source : sources) { results.add(read(source)); } return results; } public static Stack<MetaAndViewOfOnDiffBean4$NestedBeanView> read(Stack<MetaAndViewOfOnDiffBean4.NestedBean> sources) { if (sources == null) { return null; } Stack<MetaAndViewOfOnDiffBean4$NestedBeanView> results = new Stack<>(); for (MetaAndViewOfOnDiffBean4.NestedBean source : sources) { results.add(read(source)); } return results; } public static <K> Map<K, MetaAndViewOfOnDiffBean4$NestedBeanView> read(Map<K, MetaAndViewOfOnDiffBean4.NestedBean> sources) { if (sources == null) { return null; } Map<K, MetaAndViewOfOnDiffBean4$NestedBeanView> results = new HashMap<>(); for (Map.Entry<K, MetaAndViewOfOnDiffBean4.NestedBean> source : sources.entrySet()) { results.put(source.getKey(), read(source.getValue())); } return results; } public String getPa() { return this.pa; } public int getPb() { return this.pb; } } <|start_filename|>release.cmd<|end_filename|> mvn release:perform -Pdeploy <|start_filename|>beanknife-jpa/src/test/java/io/github/vipcxj/beanknife/jpa/dto/CompanyInfoConfiguration.java<|end_filename|> package io.github.vipcxj.beanknife.jpa.dto; import io.github.vipcxj.beanknife.jpa.models.Company; import io.github.vipcxj.beanknife.jpa.models.CompanyMeta; import io.github.vipcxj.beanknife.runtime.annotations.RemoveViewProperty; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; @ViewOf(Company.class) @RemoveViewProperty({CompanyMeta.departments, CompanyMeta.employees}) public class CompanyInfoConfiguration extends BaseDtoConfiguration { } <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/beans/GenClassShouldUniqueViewConfig.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; @ViewOf(value = SimpleBean.class, genName = "SimpleBeanViewNotUnique", includePattern = ".*") @ViewOf(value = SimpleBean.class, genName = "SimpleBeanViewNotUnique", includePattern = ".*") public class GenClassShouldUniqueViewConfig { } <|start_filename|>beanknife-examples/src/test/java/io/github/vipcxj/beanknife/cases/test/Tester.java<|end_filename|> package io.github.vipcxj.beanknife.cases.test; import io.github.vipcxj.beanknife.cases.beans.*; import io.github.vipcxj.beanknife.runtime.utils.Utils; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; public class Tester { private static void checkView(Class<?> type) { checkView(type, Collections.emptyList()); } private static void checkView(Class<?> type, List<String> errorMessages) { List<String> newErrorMessages = new ArrayList<>(errorMessages); System.out.println("Checking generated view type: " + type); Assertions.assertTrue(Utils.isGeneratedView(type), "The type " + type.getName() + " is not a generated view class."); for (Method method : type.getDeclaredMethods()) { boolean isError = method.getName().matches("error\\d+") && Modifier.isStatic(method.getModifiers()); if (errorMessages.isEmpty()) { if (isError) { try { String error = (String) method.invoke(null); Assertions.fail("The generated class " + type.getName() + " has some error: " + error); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } } } else { if (isError) { try { String error = (String) method.invoke(null); if (errorMessages.stream().anyMatch(error::matches)) { newErrorMessages.removeIf(error::matches); } else { Assertions.fail("The generated class " + type.getName() + " has some error: " + error); } } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } } } } String messages = newErrorMessages.stream().map(m -> "\"" + m + "\"").collect(Collectors.joining(", ")); Assertions.assertTrue(newErrorMessages.isEmpty(), "The generated class " + type.getName() + " should has some errors which match " + messages + "."); } @Test public void checkView() { checkView(AnnotationBeanView.class); checkView(BeanAView.class); checkView(BeanAViewWithInheritedConfig.class); checkView(BeanBView.class); checkView(BeanBViewWithInheritedConfig.class); checkView(CommentBeanView.class); checkView(ConverterBeanView.class); checkView(DynamicMethodPropertyBeanView.class); checkView(FieldBeanView.class); checkView(GenericBeanView.class); checkView(MetaAndViewOfBothOnBeanView.class); checkView(MetaAndViewOfOnDiffBean1View.class); checkView(MetaAndViewOfOnDiffBean2View.class); checkView(MetaAndViewOfOnDiffBean3View.class); checkView(MetaAndViewOfOnDiffBean4$NestedBeanView.class); checkView(NestedGenericBean$DynamicChildBeanView.class); checkView(NestedGenericBean$StaticChildBeanView.class); checkView(NestedGenericBeanView.class); checkView(SerializableBeanView.class); checkView(SimpleBeanView.class); checkView(SimpleBeanViewNotUnique.class); checkView(SimpleBeanWithDefaultGetters.class); checkView(SimpleBeanWithDefaultSetters.class); checkView(SimpleBeanWithInvalidIncludePattern.class, Collections.singletonList( "Invalid include pattern part:[\\s\\S]*" )); checkView(SimpleBeanWithoutGetters.class); checkView(SimpleBeanWithPrivateGetters.class); checkView(SimpleBeanWithPrivateSetters.class); checkView(SimpleBeanWithProtectedGetters.class); checkView(SimpleBeanWithProtectedSetters.class); checkView(SimpleBeanWithUnknownGetters.class); checkView(SimpleBeanWithUnknownSetters.class); checkView(StaticMethodPropertyBeanView.class); checkView(ViewOfDirectOnBeanView.class); checkView(ViewOfInNestBean$Bean1$Bean2$Bean3View.class); checkView(ViewOfInNestBean$Bean1View.class); checkView(ViewOfInNestBean$Bean2$Bean1$Bean3View.class); checkView(ViewOfInNestBean$Bean2$Bean1View.class); checkView(ViewPropertyBeanWithoutParent.class); checkView(ViewPropertyContainerBeanView.class); checkView(ViewPropertyWithExtraBeanView.class, Collections.singletonList( "Unable to convert from .+ to its view type .+\\. Because it has extra properties or extra params\\." )); checkView(WriteableBeanView.class); } } <|start_filename|>beanknife-core-base/src/main/java/io/github/vipcxj/beanknife/core/models/ViewMetaData.java<|end_filename|> package io.github.vipcxj.beanknife.core.models; import io.github.vipcxj.beanknife.core.utils.Utils; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import java.util.Map; public class ViewMetaData { private String value; private String packageName; private TypeElement of; private TypeElement config; ViewMetaData() { } public ViewMetaData(String value, String packageName, TypeElement of, TypeElement config) { this.value = value; this.packageName = packageName; this.of = of; this.config = config; } public static ViewMetaData read(ProcessingEnvironment environment, AnnotationMirror viewMeta, TypeElement configElement) { Map<? extends ExecutableElement, ? extends AnnotationValue> annValues = environment.getElementUtils().getElementValuesWithDefaults(viewMeta); ViewMetaData data = new ViewMetaData(); data.value = Utils.getStringAnnotationValue(viewMeta, annValues, "value"); data.packageName = Utils.getStringAnnotationValue(viewMeta, annValues, "packageName"); TypeElement of = (TypeElement) Utils.getTypeAnnotationValue(viewMeta, annValues, "of").asElement(); if (of.getQualifiedName().toString().equals("io.github.vipcxj.beanknife.runtime.utils.Self")) { of = configElement; } data.of = of; data.config = configElement; return data; } public String getValue() { return value; } public String getPackageName() { return packageName; } public TypeElement getOf() { return of; } public TypeElement getConfig() { return config; } } <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/beans/IllegalPropertyWithConflictPropertyBean.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.ViewMeta; @ViewMeta public class IllegalPropertyWithConflictPropertyBean { private String _while; public String getIf_() { return getIf(); } public String getIf() { return "if"; } public String getIf__() { return getIf_(); } public String getWhile() { return _while; } } <|start_filename|>beanknife-core-base/src/main/java/io/github/vipcxj/beanknife/core/utils/Utils.java<|end_filename|> package io.github.vipcxj.beanknife.core.utils; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import io.github.vipcxj.beanknife.core.models.*; import io.github.vipcxj.beanknife.runtime.annotations.Access; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; import io.github.vipcxj.beanknife.runtime.annotations.ViewOfs; import io.github.vipcxj.beanknife.runtime.annotations.ViewProperty; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedMeta; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedView; import io.github.vipcxj.beanknife.runtime.utils.Self; import org.apache.commons.text.StringEscapeUtils; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.SourceVersion; import javax.lang.model.element.*; import javax.lang.model.type.ArrayType; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import javax.tools.Diagnostic; import javax.tools.JavaFileObject; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Repeatable; import java.lang.annotation.Target; import java.lang.reflect.Array; import java.util.*; import java.util.function.Consumer; import java.util.stream.Collectors; public class Utils { public static String createGetterName(String fieldName, boolean isBoolean) { if (fieldName.isEmpty()) { throw new IllegalArgumentException("Empty field name is illegal."); } if (isBoolean && fieldName.length() >= 3 && fieldName.startsWith("is") && Character.isUpperCase(fieldName.charAt(2))) { return fieldName; } if (fieldName.length() == 1) { return isBoolean ? "is" + fieldName.toUpperCase() : "get" + fieldName.toUpperCase(); } else if (Character.isUpperCase(fieldName.charAt(1))){ return isBoolean ? "is" + fieldName : "get" + fieldName; } else { String part = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); return isBoolean ? "is" + part : "get" + part; } } public static String createSetterName(String fieldName, boolean isBoolean) { if (fieldName.isEmpty()) { throw new IllegalArgumentException("Empty field name is illegal."); } if (isBoolean && fieldName.length() >= 3 && fieldName.startsWith("is") && Character.isUpperCase(fieldName.charAt(2))) { return fieldName.replace("is", "set"); } if (fieldName.length() == 1) { return "set" + fieldName.toUpperCase(); } else if (Character.isUpperCase(fieldName.charAt(1))) { return "set" + fieldName; } else { String part = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); return "set" + part; } } public static String extractFieldName(String getterName) { boolean startsWithGet = getterName.startsWith("get"); boolean startsWithIs = getterName.startsWith("is"); if (startsWithGet || startsWithIs) { int preLen = startsWithGet ? 3 : 2; String part = getterName.substring(preLen); if (part.isEmpty()) { return null; } if (part.length() >= 2 && Character.isUpperCase(part.charAt(0)) && Character.isUpperCase(part.charAt(1))) { return part; } if (part.length() == 1) { return part.toLowerCase(); } else { return part.substring(0, 1).toLowerCase() + part.substring(1); } } return null; } public static String createValidFieldName(String name, Set<String> names) { name = name.replaceAll("\\.", "_"); if (SourceVersion.isKeyword(name) || names.contains(name)) { return createValidFieldName(name + "_", names); } else { return name; } } public static Modifier getPropertyModifier(Element e) { Set<Modifier> modifiers = e.getModifiers(); Modifier modifier = Modifier.DEFAULT; if (modifiers.contains(Modifier.PUBLIC)) { modifier = Modifier.PUBLIC; } else if (modifiers.contains(Modifier.PROTECTED)){ modifier = Modifier.PROTECTED; } else if (modifiers.contains(Modifier.PRIVATE)) { modifier = Modifier.PRIVATE; } return modifier; } public static ExecutableElement getSetterMethod(ProcessingEnvironment environment, String setterName, TypeMirror type, List<? extends Element> members) { ExecutableElement find = null; Elements elements = environment.getElementUtils(); Types types = environment.getTypeUtils(); for (Element member : members) { Set<Modifier> modifiers = member.getModifiers(); if (member.getKind() == ElementKind.METHOD && !modifiers.contains(Modifier.STATIC) && !modifiers.contains(Modifier.ABSTRACT) && setterName.equals(member.getSimpleName().toString()) ) { ExecutableElement setter = (ExecutableElement) member; List<? extends VariableElement> parameters = setter.getParameters(); if (parameters.size() != 1) { continue; } VariableElement variableElement = parameters.get(0); if (!types.isSameType(variableElement.asType(), type)) { continue; } if (setter.getReturnType().getKind() == TypeKind.VOID) { if (find == null || elements.hides(setter, find)) { find = setter; } } } } return find; } public static Access resolveGetterAccess(@CheckForNull ViewOfData viewOf, @NonNull Access access) { Access getter = viewOf != null ? viewOf.getGetters() : Access.UNKNOWN; if (access != Access.UNKNOWN) { getter = access; } return getter == Access.UNKNOWN ? Access.PUBLIC : getter; } public static Access resolveSetterAccess(@CheckForNull ViewOfData viewOf, @NonNull Access access) { Access setter = viewOf != null ? viewOf.getSetters() : Access.UNKNOWN; if (access != Access.UNKNOWN) { setter = access; } return setter == Access.UNKNOWN ? Access.NONE : setter; } public static Property createPropertyFromBase( @NonNull Context context, @CheckForNull ViewOfData viewOf, @NonNull VariableElement e, Access typeLombokGetter, Access typeLombokSetter ) { if (e.getKind() != ElementKind.FIELD) { return null; } Modifier modifier = getPropertyModifier(e); String name = e.getSimpleName().toString(); ViewProperty viewProperty = e.getAnnotation(ViewProperty.class); Access getter = viewProperty != null ? viewProperty.getter() : Access.UNKNOWN; Access setter = viewProperty != null ? viewProperty.setter() : Access.UNKNOWN; TypeMirror type = e.asType(); String setterName = createSetterName(name, type.getKind() == TypeKind.BOOLEAN); LombokInfo lombokInfo = new LombokInfo(e, typeLombokGetter, typeLombokSetter); return new Property( name, true, modifier, resolveGetterAccess(viewOf, getter), resolveSetterAccess(viewOf, setter), Type.extract(context, e, null), false, createGetterName(name, type.getKind() == TypeKind.BOOLEAN), setterName, e, context.getProcessingEnv().getElementUtils().getDocComment(e), lombokInfo ); } public static Property createPropertyFromBase( @NonNull Context context, @CheckForNull ViewOfData viewOf, @NonNull ExecutableElement e ) { if (e.getKind() != ElementKind.METHOD) { return null; } if (!e.getParameters().isEmpty()) { return null; } TypeMirror type = e.getReturnType(); if (type.getKind() == TypeKind.VOID) { return null; } String methodName = e.getSimpleName().toString(); String name = extractFieldName(methodName); if (name == null) { return null; } ViewProperty viewProperty = e.getAnnotation(ViewProperty.class); String setterName = createSetterName(name, type.getKind() == TypeKind.BOOLEAN); return new Property( name, true, getPropertyModifier(e), resolveGetterAccess(viewOf, viewProperty != null ? viewProperty.getter() : Access.UNKNOWN), resolveSetterAccess(viewOf, viewProperty != null ? viewProperty.setter() : Access.UNKNOWN), Type.extract(context, e, null), true, methodName, setterName, e, context.getProcessingEnv().getElementUtils().getDocComment(e), null ); } public static boolean canSeeFromOtherClass(Modifier modifier, boolean samePackage) { if (samePackage) { return modifier != Modifier.PRIVATE; } else { return modifier == Modifier.PUBLIC; } } public static boolean canNotSeeFromOtherClass(Property property, boolean samePackage) { if (property.hasLombokGetter()) { return !property.isLombokReadable(samePackage); } else { return !canSeeFromOtherClass(property.getModifier(), samePackage); } } public static boolean canSeeFromOtherClass(Element element, boolean samePackage) { if (samePackage) { return !element.getModifiers().contains(Modifier.PRIVATE); } else { return element.getModifiers().contains(Modifier.PUBLIC); } } public static boolean isNotObjectProperty(Property property) { Element parent = property.getElement().getEnclosingElement(); return parent.getKind() != ElementKind.CLASS || !((TypeElement) parent).getQualifiedName().toString().equals("java.lang.Object"); } @NonNull public static String getAnnotationName(@NonNull AnnotationMirror mirror) { return toElement(mirror.getAnnotationType()).getQualifiedName().toString(); } @CheckForNull public static AnnotationValue getAnnotationValue(@NonNull AnnotationMirror annotation, @NonNull String name) { for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : annotation.getElementValues().entrySet()) { if (name.equals(entry.getKey().getSimpleName().toString())) { return entry.getValue(); } } return null; } @CheckForNull public static String getStringAnnotationValue(@NonNull AnnotationMirror annotation, @NonNull String name) { AnnotationValue annotationValue = getAnnotationValue(annotation, name); if (annotationValue == null) { return null; } return (String) annotationValue.getValue(); } @CheckForNull public static <T extends Enum<T>> T getEnumAnnotationValue(@NonNull AnnotationMirror annotation, @NonNull String name, Class<T> enumType) { AnnotationValue annotationValue = getAnnotationValue(annotation, name); if (annotationValue == null) { return null; } return toEnum(annotationValue, enumType); } @CheckForNull public static String getEnumAnnotationValue(@NonNull AnnotationMirror annotation, @NonNull String name) { AnnotationValue annotationValue = getAnnotationValue(annotation, name); if (annotationValue == null) { return null; } return toEnumString(annotationValue); } @CheckForNull public static Boolean getBooleanAnnotationValue(@NonNull AnnotationMirror annotation, @NonNull String name) { AnnotationValue annotationValue = getAnnotationValue(annotation, name); if (annotationValue == null) { return null; } return (Boolean) annotationValue.getValue(); } @CheckForNull public static Long getLongAnnotationValue(@NonNull AnnotationMirror annotation, @NonNull String name) { AnnotationValue annotationValue = getAnnotationValue(annotation, name); if (annotationValue == null) { return null; } return (Long) annotationValue.getValue(); } @CheckForNull public static List<String> getStringArrayAnnotationValue(@NonNull AnnotationMirror annotation, @NonNull String name) { AnnotationValue annotationValue = getAnnotationValue(annotation, name); if (annotationValue == null) { return null; } //noinspection unchecked List<? extends AnnotationValue> arrayValue = (List<? extends AnnotationValue>) annotationValue.getValue(); return arrayValue.stream().map(value -> (String) value.getValue()).collect(Collectors.toList()); } @CheckForNull public static List<TypeMirror> getTypeArrayAnnotationValue(@NonNull AnnotationMirror annotation, @NonNull String name) { AnnotationValue annotationValue = getAnnotationValue(annotation, name); if (annotationValue == null) { return null; } //noinspection unchecked List<? extends AnnotationValue> arrayValue = (List<? extends AnnotationValue>) annotationValue.getValue(); return arrayValue.stream().map(value -> (TypeMirror) value.getValue()).collect(Collectors.toList()); } public static AnnotationValue getAnnotationValue(AnnotationMirror annotation, @NonNull Map<? extends ExecutableElement, ? extends AnnotationValue> annotationValues, @NonNull String name) { for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : annotationValues.entrySet()) { if (name.equals(entry.getKey().getSimpleName().toString())) { return entry.getValue(); } } throw new IllegalArgumentException("There is no attribute named \"" + name + "\" in annotation " + getAnnotationName(annotation)); } private static String toEnumString(AnnotationValue annotationValue) { VariableElement variableElement = (VariableElement) annotationValue.getValue(); TypeElement enumClass = (TypeElement) variableElement.getEnclosingElement(); return enumClass.getQualifiedName() + "." + variableElement.getSimpleName(); } @CheckForNull private static <T extends Enum<T>> T getEnum(String qName, Class<T> type) { String typeName = type.getName(); for (T constant : type.getEnumConstants()) { if (Objects.equals(qName, typeName + "." + constant.name())) { return constant; } } return null; } private static <T extends Enum<T>> T toEnum(AnnotationValue annotationValue, Class<T> enumType) { return getEnum(toEnumString(annotationValue), enumType); } public enum AnnotationValueKind { BOXED, STRING, TYPE, ENUM, ANNOTATION, ARRAY } private static AnnotationValueKind getAnnotationValueType(@NonNull AnnotationValue value) { Object v = value.getValue(); if (v instanceof Boolean || v instanceof Integer || v instanceof Long || v instanceof Float || v instanceof Short || v instanceof Character || v instanceof Double || v instanceof Byte ) { return AnnotationValueKind.BOXED; } else if (v instanceof String) { return AnnotationValueKind.STRING; } else if (v instanceof TypeMirror) { return AnnotationValueKind.TYPE; } else if (v instanceof VariableElement) { return AnnotationValueKind.ENUM; } else if (v instanceof AnnotationMirror) { return AnnotationValueKind.ANNOTATION; } else if (v instanceof List) { return AnnotationValueKind.ARRAY; } throw new IllegalArgumentException("This is impossible."); } private static void throwCastAnnotationValueTypeError( @NonNull AnnotationMirror annotation, @NonNull String attributeName, @NonNull AnnotationValueKind fromKind, @NonNull AnnotationValueKind toKind ) { throw new IllegalArgumentException( "Unable to cast attribute named \"" + attributeName + "\" in annotation " + getAnnotationName(annotation) + " from " + fromKind + " to " + toKind + "." ); } public static String getStringAnnotationValue(@NonNull AnnotationMirror annotation, @NonNull Map<? extends ExecutableElement, ? extends AnnotationValue> annotationValues, @NonNull String name) { AnnotationValue annotationValue = getAnnotationValue(annotation, annotationValues, name); AnnotationValueKind kind = getAnnotationValueType(annotationValue); if (kind == AnnotationValueKind.STRING) { return (String) annotationValue.getValue(); } throwCastAnnotationValueTypeError(annotation, name, kind, AnnotationValueKind.STRING); throw new IllegalArgumentException("This is impossible."); } public static boolean getBooleanAnnotationValue(@NonNull AnnotationMirror annotation, @NonNull Map<? extends ExecutableElement, ? extends AnnotationValue> annotationValues, @NonNull String name) { AnnotationValue annotationValue = getAnnotationValue(annotation, annotationValues, name); AnnotationValueKind kind = getAnnotationValueType(annotationValue); if (kind == AnnotationValueKind.BOXED) { return (Boolean) annotationValue.getValue(); } throwCastAnnotationValueTypeError(annotation, name, kind, AnnotationValueKind.BOXED); throw new IllegalArgumentException("This is impossible."); } public static long getLongAnnotationValue(@NonNull AnnotationMirror annotation, @NonNull Map<? extends ExecutableElement, ? extends AnnotationValue> annotationValues, @NonNull String name) { AnnotationValue annotationValue = getAnnotationValue(annotation, annotationValues, name); AnnotationValueKind kind = getAnnotationValueType(annotationValue); if (kind == AnnotationValueKind.BOXED) { return (Long) annotationValue.getValue(); } throwCastAnnotationValueTypeError(annotation, name, kind, AnnotationValueKind.BOXED); throw new IllegalArgumentException("This is impossible."); } public static DeclaredType getTypeAnnotationValue(@NonNull AnnotationMirror annotation, @NonNull Map<? extends ExecutableElement, ? extends AnnotationValue> annotationValues, @NonNull String name) { AnnotationValue annotationValue = getAnnotationValue(annotation, annotationValues, name); AnnotationValueKind kind = getAnnotationValueType(annotationValue); if (kind == AnnotationValueKind.TYPE) { return (DeclaredType) annotationValue.getValue(); } throwCastAnnotationValueTypeError(annotation, name, kind, AnnotationValueKind.TYPE); throw new IllegalArgumentException("This is impossible."); } public static String getEnumAnnotationValue(@NonNull AnnotationMirror annotation, @NonNull Map<? extends ExecutableElement, ? extends AnnotationValue> annotationValues, @NonNull String name) { AnnotationValue annotationValue = getAnnotationValue(annotation, annotationValues, name); AnnotationValueKind kind = getAnnotationValueType(annotationValue); if (kind == AnnotationValueKind.ENUM) { return toEnumString(annotationValue); } throwCastAnnotationValueTypeError(annotation, name, kind, AnnotationValueKind.ENUM); throw new IllegalArgumentException("This is impossible."); } @NonNull public static <T extends Enum<T>> T getEnumAnnotationValue(@NonNull AnnotationMirror annotation, @NonNull Map<? extends ExecutableElement, ? extends AnnotationValue> annotationValues, @NonNull String name, @NonNull Class<T> enumType) { String qName = getEnumAnnotationValue(annotation, annotationValues, name); return Objects.requireNonNull(getEnum(qName, enumType)); } public static List<? extends AnnotationValue> getArrayAnnotationValue(@NonNull AnnotationMirror annotation, @NonNull Map<? extends ExecutableElement, ? extends AnnotationValue> annotationValues, @NonNull String name) { AnnotationValue annotationValue = getAnnotationValue(annotation, annotationValues, name); AnnotationValueKind kind = getAnnotationValueType(annotationValue); if (kind == AnnotationValueKind.ARRAY) { //noinspection unchecked return (List<? extends AnnotationValue>) annotationValue.getValue(); } throwCastAnnotationValueTypeError(annotation, name, kind, AnnotationValueKind.ARRAY); throw new IllegalArgumentException("This is impossible."); } public static String[] getStringArrayAnnotationValue(@NonNull AnnotationMirror annotation, @NonNull Map<? extends ExecutableElement, ? extends AnnotationValue> annotationValues, @NonNull String name) { List<? extends AnnotationValue> annValues = getArrayAnnotationValue(annotation, annotationValues, name); String[] values = new String[annValues.size()]; int i = 0; for (AnnotationValue annValue : annValues) { values[i++] = (String) annValue.getValue(); } return values; } public static DeclaredType[] getTypeArrayAnnotationValue(@NonNull AnnotationMirror annotation, @NonNull Map<? extends ExecutableElement, ? extends AnnotationValue> annotationValues, @NonNull String name) { List<? extends AnnotationValue> annValues = getArrayAnnotationValue(annotation, annotationValues, name); DeclaredType[] values = new DeclaredType[annValues.size()]; int i = 0; for (AnnotationValue annValue : annValues) { values[i++] = (DeclaredType) annValue.getValue(); } return values; } public static <T extends Enum<T>> T[] getEnumArrayAnnotationValue(@NonNull AnnotationMirror annotation, @NonNull Map<? extends ExecutableElement, ? extends AnnotationValue> annotationValues, @NonNull String name, @NonNull Class<T> enumType) { List<? extends AnnotationValue> annValues = getArrayAnnotationValue(annotation, annotationValues, name); //noinspection unchecked T[] values = (T[]) Array.newInstance(enumType, annValues.size()); int i = 0; for (AnnotationValue annValue : annValues) { VariableElement variableElement = (VariableElement) annValue.getValue(); TypeElement enumClass = (TypeElement) variableElement.getEnclosingElement(); String qName = enumClass.getQualifiedName() + "." + variableElement.getSimpleName(); values[i++] = getEnum(qName, enumType); } return values; } public static AnnotationMirror[] getAnnotationArrayAnnotationValue(@NonNull AnnotationMirror annotation, @NonNull Map<? extends ExecutableElement, ? extends AnnotationValue> annotationValues, @NonNull String name) { List<? extends AnnotationValue> annValues = getArrayAnnotationValue(annotation, annotationValues, name); AnnotationMirror[] annotationMirrors = new AnnotationMirror[annValues.size()]; int i = 0; for (AnnotationValue annValue : annValues) { annotationMirrors[i++] = (AnnotationMirror) annValue.getValue(); } return annotationMirrors; } public static List<AnnotationMirror> getAnnotationElement(AnnotationMirror annotation, @NonNull Map<? extends ExecutableElement, ? extends AnnotationValue> annotationValues) { for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : annotationValues.entrySet()) { if ("value".equals(entry.getKey().getSimpleName().toString())) { //noinspection unchecked List<? extends AnnotationValue> values = (List<? extends AnnotationValue>) entry.getValue().getValue(); List<AnnotationMirror> annotations = new ArrayList<>(); for (AnnotationValue value : values) { annotations.add((AnnotationMirror) value.getValue()); } return annotations; } } throw new IllegalArgumentException("There is no attribute named value in annotation " + getAnnotationName(annotation)); } private static String getFlatQualifiedName(TypeElement element) { if (element.getNestingKind() == NestingKind.TOP_LEVEL) { return element.getQualifiedName().toString(); } else { Element parent = element.getEnclosingElement(); return getFlatQualifiedName((TypeElement) parent) + "$" + element.getSimpleName(); } } public static String extractGenTypeName(TypeElement baseTypeElement, String genName, String genPackage, String postfix) { if (genName.isEmpty()) { if (genPackage.isEmpty()) { return getFlatQualifiedName(baseTypeElement) + postfix; } else { String baseName = getFlatQualifiedName(baseTypeElement); int index = baseName.lastIndexOf('.'); if (index != -1) { return genPackage+ '.' + baseName.substring(index + 1) + postfix; } else { return genPackage + '.' + baseName + postfix; } } } else { if (genPackage.isEmpty()) { String baseName = getFlatQualifiedName(baseTypeElement); int index = baseName.lastIndexOf('.'); return baseName.substring(0, index) + '.' + genName; } else { return genPackage + '.' + genName; } } } public static Type extractGenType(Type baseClassName, String genName, String genPackage, String postfix) { if (genName.isEmpty()) { if (genPackage.isEmpty()) { return baseClassName.appendName(postfix).flatten(); } else { return baseClassName.changePackage(genPackage).appendName(postfix).flatten(); } } else { if (genPackage.isEmpty()) { return baseClassName.changeSimpleName(genName, true); } else { return baseClassName.changePackage(genPackage).changeSimpleName(genName, true); } } } public static void logWarn(ProcessingEnvironment env, String message) { env.getMessager().printMessage(Diagnostic.Kind.WARNING, message); } public static void logError(ProcessingEnvironment env, String message) { env.getMessager().printMessage(Diagnostic.Kind.ERROR, message != null ? message : ""); System.err.println(message); } public static void logError(ProcessingEnvironment env, Throwable t) { StringWriter stringWriter = new StringWriter(); PrintWriter writer = new PrintWriter(stringWriter); t.printStackTrace(writer); env.getMessager().printMessage(Diagnostic.Kind.ERROR, stringWriter.toString()); System.err.println(stringWriter.toString()); } public static void printIndent(@NonNull PrintWriter writer, String indent, int num) { for (int i = 0; i < num; ++i) { writer.print(indent); } } public static void printModifier(@NonNull PrintWriter writer, @NonNull Modifier modifier) { if (modifier != Modifier.DEFAULT) { writer.print(modifier); writer.print(" "); } } public static void printAccess(@NonNull PrintWriter writer, @NonNull Access access) { if (access == Access.UNKNOWN) { throw new IllegalArgumentException("Unknown access is not supported."); } if (access != Access.NONE && access != Access.DEFAULT) { writer.print(access); writer.print(" "); } } private static int calcArrayLevel(TypeMirror typeMirror) { if (typeMirror.getKind() != TypeKind.ARRAY) { return 0; } ArrayType arrayType = (ArrayType) typeMirror; return 1 + calcArrayLevel(arrayType.getComponentType()); } private static TypeMirror getFinalComponentType(TypeMirror typeMirror) { if (typeMirror.getKind() != TypeKind.ARRAY) { return typeMirror; } ArrayType arrayType = (ArrayType) typeMirror; return getFinalComponentType(arrayType.getComponentType()); } private static void printTypeAnnotationValue(@NonNull PrintWriter writer, @NonNull Context context, @NonNull TypeMirror typeMirror, boolean hasDotClass) { if (typeMirror.getKind() == TypeKind.DECLARED) { DeclaredType declaredType = (DeclaredType) typeMirror; TypeElement typeElement = Utils.toElement(declaredType); Type type = Type.extract(context, typeElement); if (type == null) { context.error("Unable to resolve type: " + typeElement.getQualifiedName() + "."); writer.print("error"); return; } else { type.printType(writer, context, false, false); } } else if (typeMirror.getKind() == TypeKind.ARRAY) { int arrayLevel = calcArrayLevel(typeMirror); TypeMirror componentType = getFinalComponentType(typeMirror); printTypeAnnotationValue(writer, context, componentType, false); for (int i = 0; i < arrayLevel; ++i) { writer.print("[]"); } } else if (typeMirror.getKind() == TypeKind.INT) { writer.print("int"); } else if (typeMirror.getKind() == TypeKind.BOOLEAN) { writer.print("boolean"); } else if (typeMirror.getKind() == TypeKind.VOID) { writer.print("void"); } else if (typeMirror.getKind() == TypeKind.BYTE) { writer.print("byte"); } else if (typeMirror.getKind() == TypeKind.CHAR) { writer.print("char"); } else if (typeMirror.getKind() == TypeKind.DOUBLE) { writer.print("double"); } else if (typeMirror.getKind() == TypeKind.FLOAT) { writer.print("float"); } else if (typeMirror.getKind() == TypeKind.LONG) { writer.print("long"); } else if (typeMirror.getKind() == TypeKind.SHORT) { writer.print("short"); } else { context.error("Unable to resolve type: " + typeMirror + "."); writer.print("error"); return; } if (hasDotClass) { writer.print(".class"); } } public static void printAnnotationValue(@NonNull PrintWriter writer, @NonNull AnnotationValue annValue, @NonNull Context context, String indent, int indentNum) { Object value = annValue.getValue(); AnnotationValueKind valueType = getAnnotationValueType(annValue); switch (valueType) { case ENUM: { VariableElement enumValue = (VariableElement) value; TypeElement enumClass = (TypeElement) enumValue.getEnclosingElement(); Type enumClassType = Type.extract(context, enumClass); if (enumClassType == null) { context.error("Unable to resolve type: " + enumClass.getQualifiedName() + "."); writer.print("error"); } else { enumClassType.printType(writer, context, false, false); writer.print("."); writer.print(enumValue.getSimpleName()); } break; } case BOXED: { if (value instanceof Character) { writer.print("'"); writer.print(value); writer.print("'"); } else if (value instanceof Long) { writer.print(value); writer.print("l"); } else if (value instanceof Float) { writer.print(value); writer.print("f"); } else { writer.print(value); } break; } case TYPE: { TypeMirror typeMirror = (TypeMirror) value; printTypeAnnotationValue(writer, context, typeMirror, true); break; } case STRING: { writer.print("\""); writer.print(StringEscapeUtils.escapeJava((String) value)); writer.print("\""); break; } case ANNOTATION: { printAnnotation(writer, (AnnotationMirror) value, context, indent, indentNum); break; } case ARRAY: { //noinspection unchecked List<? extends AnnotationValue> annotationValues = (List<? extends AnnotationValue>) value; if (annotationValues.isEmpty()) { writer.print("{}"); } else { writer.println("{"); int i = 0; for (AnnotationValue annotationValue : annotationValues) { Utils.printIndent(writer, indent, indentNum + 1); printAnnotationValue(writer, annotationValue, context, indent, indentNum + 1); if (i != annotationValues.size() - 1) { writer.println(","); } else { writer.println(); } ++i; } Utils.printIndent(writer, indent, indentNum); writer.print("}"); } break; } default: throw new IllegalArgumentException("This is impossible."); } } private static boolean shouldBreakLineForPrintingAnnotation(Collection<? extends AnnotationValue> annotationValues) { return annotationValues.size() > 3 || (annotationValues.size() != 1 && annotationValues.stream().anyMatch(a -> a.getValue() instanceof List && !((List<?>) a.getValue()).isEmpty())); } public static void printAnnotation(@NonNull PrintWriter writer, @NonNull AnnotationMirror annotation, @NonNull Context context, String indent, int indentNum) { writer.print("@"); Type type = Type.extract(context, annotation.getAnnotationType().asElement()); type.printType(writer, context, false, false); Map<? extends ExecutableElement, ? extends AnnotationValue> attributes = annotation.getElementValues(); if (!attributes.isEmpty()) { boolean shouldBreakLine = shouldBreakLineForPrintingAnnotation(attributes.values()); boolean useValue = attributes.size() == 1 && attributes.keySet().iterator().next().getSimpleName().toString().equals("value"); if (useValue) { AnnotationValue annotationValue = attributes.values().iterator().next(); writer.print("("); printAnnotationValue(writer, annotationValue, context, indent, indentNum); writer.print(")"); } else if (shouldBreakLine) { writer.println("("); int i = 0; for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : attributes.entrySet()) { Utils.printIndent(writer, indent, indentNum + 1); writer.print(entry.getKey().getSimpleName()); writer.print(" = "); printAnnotationValue(writer, entry.getValue(), context, indent, indentNum + 1); if (i != attributes.size() - 1) { writer.println(","); } else { writer.println(); } ++i; } Utils.printIndent(writer, indent, indentNum); writer.print(")"); } else { writer.print("("); int i = 0; for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : attributes.entrySet()) { writer.print(entry.getKey().getSimpleName()); writer.print(" = "); printAnnotationValue(writer, entry.getValue(), context, indent, indentNum); if (i != attributes.size() - 1) { writer.print(", "); } ++i; } writer.print(")"); } } } public static boolean shouldIgnoredElement(Element element) { GeneratedMeta generatedMeta = element.getAnnotation(GeneratedMeta.class); if (generatedMeta != null) { return true; } GeneratedView generatedView = element.getAnnotation(GeneratedView.class); if (generatedView != null) { return true; } return element.getKind() != ElementKind.CLASS; } public static boolean isViewMetaTargetTo(ProcessingEnvironment environment, AnnotationMirror viewMeta, TypeElement sourceElement, TypeElement targetElement) { Map<? extends ExecutableElement, ? extends AnnotationValue> elementValuesWithDefaults = environment.getElementUtils().getElementValuesWithDefaults(viewMeta); for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : elementValuesWithDefaults.entrySet()) { if (entry.getKey().getSimpleName().toString().equals("of")) { TypeElement target = (TypeElement) ((DeclaredType) entry.getValue().getValue()).asElement(); if (target.getQualifiedName().toString().equals(Self.class.getCanonicalName())) { target = sourceElement; } if (target.equals(targetElement)) { return true; } } } return false; } public static List<TypeElement> calcDependencies(TypeElement element) { List<TypeElement> dependencies = new ArrayList<>(); dependencies.add(element); TypeMirror superclass = element.getSuperclass(); if (superclass.getKind() != TypeKind.NONE) { DeclaredType declaredType = (DeclaredType) superclass; dependencies.addAll(calcDependencies(Utils.toElement(declaredType))); } return dependencies; } private static Element[] calcDependencies(ViewContext context) { ViewOfData viewOf = context.getViewOf(); List<TypeElement> targetDependencies = calcDependencies(viewOf.getTargetElement()); List<TypeElement> configDependencies; if (!viewOf.getConfigElement().equals(viewOf.getTargetElement())) { configDependencies = calcDependencies(viewOf.getConfigElement()); } else { configDependencies = Collections.emptyList(); } Element[] dependencies = new Element[targetDependencies.size() + configDependencies.size()]; int i = 0; for (TypeElement targetDependency : targetDependencies) { dependencies[i++] = targetDependency; } for (TypeElement configDependency : configDependencies) { dependencies[i++] = configDependency; } return dependencies; } public static void writeViewFile(ViewContext context) throws IOException { Modifier modifier = context.getViewOf().getAccess(); if (modifier == null) { return; } Element[] dependencies = calcDependencies(context); JavaFileObject sourceFile = context.getProcessingEnv().getFiler().createSourceFile(context.getGenType().getQualifiedName(), dependencies); try (PrintWriter writer = new PrintWriter(sourceFile.openWriter())) { context.print(writer); } } public static void printComment(@NonNull PrintWriter writer, String comment, boolean getter, String indent, int indentNum) { if (comment == null || comment.isEmpty()) { return; } String[] lines = comment.split("[\\r\\n]+"); if (lines.length == 0) { return; } Utils.printIndent(writer, indent, indentNum); writer.println("/**"); for (String line : lines) { if (getter && line.trim().startsWith("@param ")) { continue; } Utils.printIndent(writer, indent, indentNum); writer.print(" * "); writer.println(line); } Utils.printIndent(writer, indent, indentNum); writer.println(" */"); } public static boolean isThisType(@NonNull TypeMirror typeMirror, @NonNull Class<?> type) { if (typeMirror.getKind().isPrimitive()) { return type.isPrimitive() &&((typeMirror.getKind() == TypeKind.BOOLEAN && type == boolean.class) || (typeMirror.getKind() == TypeKind.BYTE && type == byte.class) || (typeMirror.getKind() == TypeKind.CHAR && type == char.class) || (typeMirror.getKind() == TypeKind.SHORT && type == short.class) || (typeMirror.getKind() == TypeKind.INT && type == int.class) || (typeMirror.getKind() == TypeKind.LONG && type == long.class) || (typeMirror.getKind() == TypeKind.FLOAT && type == float.class) || (typeMirror.getKind() == TypeKind.DOUBLE && type == double.class)); } else if (typeMirror.getKind() == TypeKind.VOID) { return type == void.class; } else if (typeMirror.getKind() == TypeKind.ARRAY) { return type.isArray() && isThisType(((ArrayType) typeMirror).getComponentType(), type.getComponentType()); } else if (typeMirror.getKind() == TypeKind.DECLARED) { String canonicalName = type.getCanonicalName(); if (canonicalName == null) { throw new UnsupportedOperationException(); } DeclaredType declaredType = (DeclaredType) typeMirror; return toElement(declaredType).getQualifiedName().toString().equals(canonicalName); } else { throw new UnsupportedOperationException(); } } public static boolean isThisTypeElement(@NonNull TypeElement typeElement, @NonNull Class<?> type) { return typeElement.getQualifiedName().toString().equals(type.getCanonicalName()); } public static boolean isThisAnnotation(@NonNull AnnotationMirror annotation, @NonNull Class<?> type) { TypeElement element = (TypeElement) annotation.getAnnotationType().asElement(); return element.getQualifiedName().toString().equals(type.getCanonicalName()); } public static boolean isThisAnnotation(@NonNull AnnotationMirror annotation, @NonNull String typeName) { TypeElement element = (TypeElement) annotation.getAnnotationType().asElement(); return element.getQualifiedName().toString().equals(typeName); } public static List<AnnotationMirror> getAnnotationsOn(@NonNull Elements elements, @NonNull Element element, @NonNull Class<?> type, @CheckForNull Class<?> repeatContainerType) { return getAnnotationsOn(elements, element, type, repeatContainerType, new HashSet<>(), true, true); } public static List<AnnotationMirror> getAnnotationsOn(@NonNull Elements elements, @NonNull Element element, @NonNull Class<?> type, @CheckForNull Class<?> repeatContainerType, boolean indirect) { return getAnnotationsOn(elements, element, type, repeatContainerType, new HashSet<>(), indirect, true); } public static List<AnnotationMirror> getAnnotationsOn(@NonNull Elements elements, @NonNull Element element, @NonNull Class<?> type, @CheckForNull Class<?> repeatContainerType, boolean indirect, boolean metaExtends) { return getAnnotationsOn(elements, element, type, repeatContainerType, new HashSet<>(), indirect, metaExtends); } public static List<AnnotationMirror> getAnnotationsOn(@NonNull Elements elements, @NonNull Element element, @NonNull String typeName, @CheckForNull String repeatContainerTypeName, boolean indirect, boolean metaExtends) { return getAnnotationsOn(elements, element, typeName, repeatContainerTypeName, new HashSet<>(), indirect, metaExtends); } private static List<AnnotationMirror> getAnnotationsOn(@NonNull Elements elements, @NonNull Element element, @NonNull Class<?> type, @CheckForNull Class<?> repeatContainerType, @NonNull Set<Element> visited, boolean indirect, boolean metaExtends) { return getAnnotationsOn(elements, element, type.getName(), repeatContainerType != null ? repeatContainerType.getName() : null, visited, indirect, metaExtends); } private static List<AnnotationMirror> getAnnotationsOn(@NonNull Elements elements, @NonNull Element element, @NonNull String typeName, @CheckForNull String repeatContainerTypeName, @NonNull Set<Element> visited, boolean indirect, boolean metaExtends) { if (visited.contains(element)) { return Collections.emptyList(); } visited.add(element); List<AnnotationMirror> result = new ArrayList<>(); List<? extends AnnotationMirror> allAnnotations = indirect ? getAllAnnotationMirrors(elements, element) : element.getAnnotationMirrors(); for (AnnotationMirror annotation : allAnnotations) { if (isThisAnnotation(annotation, typeName)) { result.add(annotation); } else if (repeatContainerTypeName != null && isThisAnnotation(annotation, repeatContainerTypeName)){ Map<? extends ExecutableElement, ? extends AnnotationValue> attributes = elements.getElementValuesWithDefaults(annotation); List<AnnotationMirror> annotations = getAnnotationElement(annotation, attributes); result.addAll(annotations); } else if (metaExtends) { result.addAll(getAnnotationsOn(elements, annotation.getAnnotationType().asElement(), typeName, repeatContainerTypeName, visited, indirect, true)); } } return result; } public static DeclaredType toType(TypeElement element) { return (DeclaredType) element.asType(); } public static TypeElement toElement(DeclaredType type) { return (TypeElement) type.asElement(); } public static DeclaredType findSuperType(DeclaredType theType, Class<?> type) { TypeElement element = toElement(theType); if (type.isInterface()) { for (TypeMirror anInterface : element.getInterfaces()) { if (isThisType(anInterface, type)) { return (DeclaredType) anInterface; } } } TypeMirror superType = element.getSuperclass(); if (superType.getKind() == TypeKind.NONE) { return null; } if (isThisType(superType, type)) { return (DeclaredType) superType; } return findSuperType((DeclaredType) superType, type); } public static boolean hasEmptyConstructor(ProcessingEnvironment env, TypeElement element) { ExecutableElement emptyConstructor = findMethod(env, element, "<init>", true); return emptyConstructor != null || findMethod(env, element, "<init>", false) == null; } public static ExecutableElement findMethod(ProcessingEnvironment env, TypeElement element, String name, boolean matchParameters, TypeMirror... argTypes) { Types typeUtils = env.getTypeUtils(); for (Element member : env.getElementUtils().getAllMembers(element)) { if (member.getKind() == ElementKind.METHOD && member.getSimpleName().toString().equals(name)) { ExecutableElement executable = (ExecutableElement) member; List<? extends VariableElement> parameters = executable.getParameters(); if (matchParameters) { if (parameters.size() != argTypes.length) { continue; } boolean matched = true; for (int i = 0; i < parameters.size(); ++i) { VariableElement variable = parameters.get(i); TypeMirror argType = argTypes[i]; if (!typeUtils.isAssignable(argType, variable.asType())) { matched = false; break; } } if (!matched) { continue; } } return executable; } } return null; } private static void collectViewOfs(List<ViewOfData> results, ProcessingEnvironment processingEnv, TypeElement candidate, TypeElement targetElement, AnnotationMirror viewOf) { Map<? extends ExecutableElement, ? extends AnnotationValue> elementValuesWithDefaults = processingEnv.getElementUtils().getElementValuesWithDefaults(viewOf); Map<String, ? extends AnnotationValue> attributes = CollectionUtils.mapKey(elementValuesWithDefaults, e -> e.getSimpleName().toString()); TypeElement target = (TypeElement) ((DeclaredType) attributes.get("value").getValue()).asElement(); if (target.getQualifiedName().toString().equals(Self.class.getCanonicalName())) { target = candidate; } if (!target.equals(targetElement)) { return; } TypeElement config = (TypeElement) ((DeclaredType) attributes.get("config").getValue()).asElement(); if (config.getQualifiedName().toString().equals(Self.class.getCanonicalName())) { config = candidate; } ViewOfData viewOfData = ViewOfData.read(processingEnv, viewOf, candidate); viewOfData.setConfigElement(config); viewOfData.setTargetElement(target); results.add(viewOfData); } private static void collectViewOfs(List<ViewOfData> results, ProcessingEnvironment processingEnv, TypeElement candidate, AnnotationMirror viewOf) { Map<? extends ExecutableElement, ? extends AnnotationValue> elementValuesWithDefaults = processingEnv.getElementUtils().getElementValuesWithDefaults(viewOf); TypeElement targetElement = toElement(getTypeAnnotationValue(viewOf, elementValuesWithDefaults, "value")); if (isThisTypeElement(targetElement, Self.class)) { targetElement = candidate; } TypeElement configElement = toElement(getTypeAnnotationValue(viewOf, elementValuesWithDefaults, "config")); if (isThisTypeElement(configElement, Self.class)) { configElement = candidate; } ViewOfData viewOfData = ViewOfData.read(processingEnv, viewOf, candidate); viewOfData.setConfigElement(configElement); viewOfData.setTargetElement(targetElement); results.add(viewOfData); } public static List<ViewOfData> collectViewOfs(ProcessingEnvironment processingEnv, RoundEnvironment roundEnv) { Set<? extends Element> proxySources = roundEnv.getElementsAnnotatedWith(GeneratedMeta.class); Map<String, TypeElement> configClasses = new HashMap<>(); for (Element proxySource : proxySources) { List<? extends AnnotationMirror> annotationMirrors = proxySource.getAnnotationMirrors(); for (AnnotationMirror annotationMirror : annotationMirrors) { if (Utils.isThisAnnotation(annotationMirror, GeneratedMeta.class)) { Map<? extends ExecutableElement, ? extends AnnotationValue> elementValuesWithDefaults = processingEnv.getElementUtils().getElementValuesWithDefaults(annotationMirror); DeclaredType[] proxies = Utils.getTypeArrayAnnotationValue(annotationMirror, elementValuesWithDefaults, "proxies"); for (DeclaredType proxy : proxies) { TypeElement proxyElement = toElement(proxy); configClasses.put(proxyElement.getQualifiedName().toString(), proxyElement); } } } } List<ViewOfData> out = new ArrayList<>(); for (TypeElement configElement : configClasses.values()) { List<? extends AnnotationMirror> annotationMirrors = configElement.getAnnotationMirrors(); for (AnnotationMirror annotationMirror : annotationMirrors) { if (Utils.isThisAnnotation(annotationMirror, ViewOf.class)) { collectViewOfs(out, processingEnv, configElement, annotationMirror); } } for (AnnotationMirror annotationMirror : annotationMirrors) { if (Utils.isThisAnnotation(annotationMirror, ViewOfs.class)) { Map<? extends ExecutableElement, ? extends AnnotationValue> elementValuesWithDefaults = processingEnv.getElementUtils().getElementValuesWithDefaults(annotationMirror); List<AnnotationMirror> viewOfs = Utils.getAnnotationElement(annotationMirror, elementValuesWithDefaults); for (AnnotationMirror viewOf : viewOfs) { collectViewOfs(out, processingEnv, configElement, viewOf); } } } } return out; } public static List<ViewOfData> collectViewOfs(ProcessingEnvironment processingEnv, RoundEnvironment roundEnv, TypeElement targetElement) { Set<? extends Element> candidates = roundEnv.getElementsAnnotatedWith(ViewOf.class); List<ViewOfData> out = new ArrayList<>(); for (Element candidate : candidates) { if (Utils.shouldIgnoredElement(candidate)) { continue; } List<? extends AnnotationMirror> annotationMirrors = candidate.getAnnotationMirrors(); for (AnnotationMirror annotationMirror : annotationMirrors) { if (Utils.isThisAnnotation(annotationMirror, ViewOf.class)) { collectViewOfs(out, processingEnv, (TypeElement) candidate, targetElement, annotationMirror); } } } candidates = roundEnv.getElementsAnnotatedWith(ViewOfs.class); for (Element candidate : candidates) { if (Utils.shouldIgnoredElement(candidate)) { continue; } List<? extends AnnotationMirror> annotationMirrors = candidate.getAnnotationMirrors(); for (AnnotationMirror annotationMirror : annotationMirrors) { if (Utils.isThisAnnotation(annotationMirror, ViewOfs.class)) { Map<? extends ExecutableElement, ? extends AnnotationValue> elementValuesWithDefaults = processingEnv.getElementUtils().getElementValuesWithDefaults(annotationMirror); List<AnnotationMirror> viewOfs = Utils.getAnnotationElement(annotationMirror, elementValuesWithDefaults); for (AnnotationMirror viewOf : viewOfs) { collectViewOfs(out, processingEnv, (TypeElement) candidate, targetElement, viewOf); } } } } return out; } public static Modifier accessToModifier(Access access) { switch (access) { case PUBLIC: return Modifier.PUBLIC; case DEFAULT: return Modifier.DEFAULT; case PROTECTED: return Modifier.PROTECTED; case PRIVATE: case UNKNOWN: case NONE: return Modifier.PRIVATE; default: throw new IllegalStateException("This is impossible!"); } } public static Access accessFromModifier(Modifier modifier) { if (modifier == null) { return Access.NONE; } switch (modifier) { case PUBLIC: return Access.PUBLIC; case DEFAULT: return Access.DEFAULT; case PROTECTED: return Access.PROTECTED; case PRIVATE: return Access.PRIVATE; default: return Access.UNKNOWN; } } public static List<AnnotationMirror> getRepeatableAnnotationComponents(@NonNull Elements elements, @NonNull AnnotationMirror annotation) { TypeElement componentElement = getRepeatableAnnotationComponentElement(elements, annotation); if (componentElement != null) { Map<? extends ExecutableElement, ? extends AnnotationValue> annotationValues = elements.getElementValuesWithDefaults(annotation); AnnotationMirror[] values = getAnnotationArrayAnnotationValue(annotation, annotationValues, "value"); return Arrays.asList(values); } return null; } private static TypeElement getRepeatableAnnotationContainerElement(@NonNull Elements elements, @NonNull TypeElement element) { if (element.getKind() == ElementKind.ANNOTATION_TYPE) { List<AnnotationMirror> repeatableList = getAnnotationsOn(elements, element, Repeatable.class, null, false, false); if (!repeatableList.isEmpty()) { AnnotationMirror repeatable = repeatableList.get(0); Map<? extends ExecutableElement, ? extends AnnotationValue> annValues = repeatable.getElementValues(); AnnotationValue annValue = annValues.values().iterator().next(); DeclaredType repeatableAnnotationType = (DeclaredType) annValue.getValue(); return toElement(repeatableAnnotationType); } } return null; } public static TypeElement getRepeatableAnnotationComponentElement(@NonNull Elements elements, AnnotationMirror annotation) { TypeElement typeElement = Utils.toElement(annotation.getAnnotationType()); Map<? extends ExecutableElement, ? extends AnnotationValue> elementValues = elements.getElementValuesWithDefaults(annotation); if (elementValues.size() == 1) { ExecutableElement key = elementValues.keySet().iterator().next(); if (key.getSimpleName().toString().equals("value")) { TypeMirror returnType = key.getReturnType(); if (returnType.getKind() == TypeKind.ARRAY) { ArrayType arrayType = (ArrayType) returnType; TypeMirror componentType = arrayType.getComponentType(); if (componentType.getKind() == TypeKind.DECLARED) { TypeElement componentElement = toElement((DeclaredType) componentType); TypeElement containerElement = getRepeatableAnnotationContainerElement(elements, componentElement); if (containerElement != null && containerElement.getQualifiedName().toString().equals(typeElement.getQualifiedName().toString())) { return componentElement; } } } } } return null; } public static boolean isAnnotationRepeatable(@NonNull Elements elements, AnnotationMirror annotation) { return !getAnnotationsOn(elements, annotation.getAnnotationType().asElement(), Repeatable.class, null, false, false).isEmpty(); } public static boolean isAnnotationInheritable(@NonNull Elements elements, AnnotationMirror annotation) { List<AnnotationMirror> inheritedList = getAnnotationsOn(elements, annotation.getAnnotationType().asElement(), Inherited.class, null, false, false); if (!inheritedList.isEmpty()) { return true; } TypeElement componentElement = getRepeatableAnnotationComponentElement(elements, annotation); if (componentElement != null) { return !getAnnotationsOn(elements, componentElement, Inherited.class, null, false, false).isEmpty(); } else { return false; } } @CheckForNull public static List<ElementType> getAnnotationTarget(@NonNull Elements elements, @NonNull AnnotationMirror annotation) { List<AnnotationMirror> targets = getAnnotationsOn(elements, annotation.getAnnotationType().asElement(), Target.class, null, false, false); if (targets.isEmpty()) { return null; } AnnotationMirror target = targets.get(0); Map<? extends ExecutableElement, ? extends AnnotationValue> values = elements.getElementValuesWithDefaults(target); return Arrays.asList(getEnumArrayAnnotationValue(target, values, "value", ElementType.class)); } public static boolean annotationCanPutOn(@NonNull Elements elements, @NonNull AnnotationMirror annotation, @NonNull ElementType elementType) { List<ElementType> types = getAnnotationTarget(elements, annotation); if (types == null) { return elementType != ElementType.TYPE_PARAMETER; } return types.contains(elementType); } private static void importTypeMirror(@NonNull Context context, @NonNull TypeMirror typeMirror) { if (typeMirror.getKind() == TypeKind.ARRAY) { ArrayType arrayType = (ArrayType) typeMirror; importTypeMirror(context, arrayType.getComponentType()); } else if (typeMirror.getKind() == TypeKind.DECLARED) { DeclaredType declaredType = (DeclaredType) typeMirror; TypeElement typeElement = toElement(declaredType); Type type = Type.extract(context, typeElement); if (type != null) { context.importVariable(type); } } } private static void importAnnotationValue(@NonNull Context context, @NonNull AnnotationValue annValue) { AnnotationValueKind type = getAnnotationValueType(annValue); if (type == AnnotationValueKind.TYPE) { TypeMirror typeMirror = (TypeMirror) annValue.getValue(); importTypeMirror(context, typeMirror); } else if (type == AnnotationValueKind.ANNOTATION) { AnnotationMirror annotationMirror = (AnnotationMirror) annValue.getValue(); importAnnotation(context, annotationMirror); } else if (type == AnnotationValueKind.ENUM) { VariableElement enumValue = (VariableElement) annValue.getValue(); TypeElement enumElement = (TypeElement) enumValue.getEnclosingElement(); Type enumType = Type.extract(context, enumElement); if (enumType != null) { context.importVariable(enumType); } } else if (type == AnnotationValueKind.ARRAY) { //noinspection unchecked List<? extends AnnotationValue> arrayValues = (List<? extends AnnotationValue>) annValue.getValue(); for (AnnotationValue arrayValue : arrayValues) { importAnnotationValue(context, arrayValue); } } } public static void importAnnotation(@NonNull Context context, @NonNull AnnotationMirror annotation) { Element element = annotation.getAnnotationType().asElement(); Type type = Type.extract(context, element); if (type == null) { context.error("Unable to resolve the type " + element + "."); return; } context.importVariable(type); Map<? extends ExecutableElement, ? extends AnnotationValue> annValues = annotation.getElementValues(); for (AnnotationValue annValue : annValues.values()) { importAnnotationValue(context, annValue); } } public static List<AnnotationMirror> getAllAnnotationMirrors(@NonNull Elements elements, @NonNull Element element) { return getAllAnnotationMirrors(elements, element, true); } private static List<AnnotationMirror> getAllAnnotationMirrors(@NonNull Elements elements, @NonNull Element element, boolean direct) { List<AnnotationMirror> results = new LinkedList<>(); if (direct) { results.addAll(element.getAnnotationMirrors()); } else { for (AnnotationMirror annotationMirror : element.getAnnotationMirrors()) { if (isAnnotationInheritable(elements, annotationMirror)) { results.add(annotationMirror); } } } if (element.getKind() == ElementKind.CLASS) { TypeElement typeElement = (TypeElement) element; TypeMirror superclass = typeElement.getSuperclass(); if (superclass.getKind() != TypeKind.NONE) { DeclaredType declaredType = (DeclaredType) superclass; results.addAll(0, getAllAnnotationMirrors(elements, declaredType.asElement(), false)); } } return results; } @CheckForNull public static AnnotationMirror getAnnotationDirectOn(@NonNull Element element, String qName) { for (AnnotationMirror annotationMirror : element.getAnnotationMirrors()) { if (toElement(annotationMirror.getAnnotationType()).getQualifiedName().toString().equals(qName)) { return annotationMirror; } } return null; } public static boolean appendMethodArg(PrintWriter writer, Consumer<PrintWriter> varWriter, boolean start, boolean breakLine, String indent, int indentNum) { if (breakLine) { if (start) { writer.println(); } else { writer.println(","); } Utils.printIndent(writer, indent, indentNum); } else if (!start) { writer.print(", "); } varWriter.accept(writer); return false; } } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/annotations/InjectProperty.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Used to inject the property to the dynamic property method. * @see Dynamic */ @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.SOURCE) public @interface InjectProperty { String value() default ""; } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/ViewMetaInNestBean$Bean1$Bean2$Bean3Meta.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedMeta; @GeneratedMeta(targetClass = ViewMetaInNestBean.Bean1.Bean2.Bean3.class, configClass = ViewMetaInNestBean.Bean1.Bean2.Bean3.class) public class ViewMetaInNestBean$Bean1$Bean2$Bean3Meta { public static final String a = "a"; public static final String b = "b"; } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/BeanAViewWithInheritedConfig.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedView; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; @GeneratedView(targetClass = BeanA.class, configClass = InheritedConfigBeanAViewConfig.class) public class BeanAViewWithInheritedConfig { private int a; private long b; private Date c; private Map<String, List<BeanB>> beanBMap; private String type; private Date timestamp; public BeanAViewWithInheritedConfig() { } public BeanAViewWithInheritedConfig( int a, long b, Date c, Map<String, List<BeanB>> beanBMap, String type, Date timestamp ) { this.a = a; this.b = b; this.c = c; this.beanBMap = beanBMap; this.type = type; this.timestamp = timestamp; } public BeanAViewWithInheritedConfig(BeanAViewWithInheritedConfig source) { this.a = source.a; this.b = source.b; this.c = source.c; this.beanBMap = source.beanBMap; this.type = source.type; this.timestamp = source.timestamp; } public BeanAViewWithInheritedConfig(BeanA source) { if (source == null) { throw new NullPointerException("The input source argument of the read constructor of class io.github.vipcxj.beanknife.cases.beans.BeanAViewWithInheritedConfig should not be null."); } this.a = source.a; this.b = source.b; this.c = source.getC(); this.beanBMap = source.getBeanBMap(); this.type = InheritedConfigBeanAViewConfig.type(source); this.timestamp = InheritedConfigBeanAViewConfig.timestamp(); } public static BeanAViewWithInheritedConfig read(BeanA source) { if (source == null) { return null; } return new BeanAViewWithInheritedConfig(source); } public static BeanAViewWithInheritedConfig[] read(BeanA[] sources) { if (sources == null) { return null; } BeanAViewWithInheritedConfig[] results = new BeanAViewWithInheritedConfig[sources.length]; for (int i = 0; i < sources.length; ++i) { results[i] = read(sources[i]); } return results; } public static List<BeanAViewWithInheritedConfig> read(List<BeanA> sources) { if (sources == null) { return null; } List<BeanAViewWithInheritedConfig> results = new ArrayList<>(); for (BeanA source : sources) { results.add(read(source)); } return results; } public static Set<BeanAViewWithInheritedConfig> read(Set<BeanA> sources) { if (sources == null) { return null; } Set<BeanAViewWithInheritedConfig> results = new HashSet<>(); for (BeanA source : sources) { results.add(read(source)); } return results; } public static Stack<BeanAViewWithInheritedConfig> read(Stack<BeanA> sources) { if (sources == null) { return null; } Stack<BeanAViewWithInheritedConfig> results = new Stack<>(); for (BeanA source : sources) { results.add(read(source)); } return results; } public static <K> Map<K, BeanAViewWithInheritedConfig> read(Map<K, BeanA> sources) { if (sources == null) { return null; } Map<K, BeanAViewWithInheritedConfig> results = new HashMap<>(); for (Map.Entry<K, BeanA> source : sources.entrySet()) { results.put(source.getKey(), read(source.getValue())); } return results; } public int getA() { return this.a; } public long getB() { return this.b; } public Date getC() { return this.c; } public Map<String, List<BeanB>> getBeanBMap() { return this.beanBMap; } public String getType() { return this.type; } public Date getTimestamp() { return this.timestamp; } public String getTypeWithTimestamp() { return InheritedConfigBeanAViewConfig.typeWithTimestamp(this.type, this.timestamp); } public Date getToday() { return InheritedConfigBeanAViewConfig.today(); } public Date getYesterday() { return InheritedConfigBeanAViewConfig.yesterday(); } public Date getTomorrow() { return InheritedConfigBeanAViewConfig.tomorrow(); } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/SerializableBean.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; @ViewOf(includes = {SerializableBeanMeta.a, SerializableBeanMeta.b}, serializable = true, serialVersionUID = 4L) public class SerializableBean { private String a; private long b; public String getA() { return a; } public long getB() { return b; } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/CommentBean.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; @ViewOf(includePattern = ".*") public class CommentBean { /** * this is a. * this is the second line. * {@link Object} this is some doc annotation. */ private String a; private String b; /** * this is c * this comment is on the field. * this is the second line. * {@link Object} this is some doc annotation. */ private long c; public String getA() { return a; } /** * this is b. * this is the second line. * {@link Object} this is some doc annotation. */ public String getB() { return b; } /** * this is c * this comment is on the method. * this is the second line. * {@link Object} this is some doc annotation. */ public long getC() { return c; } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/MetaAndViewOfOnDiffBean4MetaConfig.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.ViewMeta; @ViewMeta(of = MetaAndViewOfOnDiffBean4.NestedBean.class) public class MetaAndViewOfOnDiffBean4MetaConfig { } <|start_filename|>beanknife-jpa/src/main/java/io/github/vipcxj/beanknife/jpa/PropertyData.java<|end_filename|> package io.github.vipcxj.beanknife.jpa; import io.github.vipcxj.beanknife.core.models.Property; import io.github.vipcxj.beanknife.core.models.StaticMethodExtractor; import io.github.vipcxj.beanknife.core.models.Type; import io.github.vipcxj.beanknife.core.models.ViewContext; import io.github.vipcxj.beanknife.core.utils.ParamInfo; import io.github.vipcxj.beanknife.core.utils.Utils; import io.github.vipcxj.beanknife.core.utils.VarMapper; import io.github.vipcxj.beanknife.runtime.utils.BeanUsage; import javax.lang.model.element.Modifier; import javax.lang.model.element.PackageElement; import javax.lang.model.util.Elements; import java.io.PrintWriter; import java.util.*; public class PropertyData { private final JpaContext jpaContext; private final ViewContext context; private final Property target; private final PropertyData parent; private PropertyType propertyType; private boolean ignore; private boolean needParentSource; private boolean provideAsSource; private boolean useReaderMethod; private boolean useFieldsConstructor; private boolean constructNeedReflect; private ViewContext subContext; private List<PropertyData> viewPropertyData; private StaticMethodExtractor extractor; public PropertyData(JpaContext jpaContext, ViewContext context, Property target, PropertyData parent) { this.jpaContext = jpaContext; this.context = context; this.target = target; this.parent = parent; } public static List<PropertyData> collectData(JpaContext jpaContext) { return collectData(jpaContext, jpaContext.getViewContext(), null, null); } public static List<PropertyData> collectData(JpaContext jpaContext, ViewContext context, Set<String> typePool, PropertyData parent) { if (typePool == null) { typePool = new HashSet<>(); } List<PropertyData> dataList = new ArrayList<>(); for (Property property : context.getProperties()) { PropertyData propertyData = create(jpaContext, context, property, typePool, parent); if (propertyData != null) { dataList.add(propertyData); } } return dataList; } private void cleanBasePropertyArg() { if (propertyType == PropertyType.VIEW) { for (Property baseProperty : subContext.getBaseProperties()) { jpaContext.getConstructorVarMapper().removeVar(baseProperty); } } } private void markParentProvideSource() { if (parent != null) { parent.provideAsSource = true; parent.cleanBasePropertyArg(); } else { jpaContext.markProvideSource(); } } public static PropertyData create(JpaContext jpaContext, ViewContext context, Property property, Set<String> typePool, PropertyData parent) { if (property.isDynamic()) { return null; } PropertyData propertyData = new PropertyData(jpaContext, context, property, parent); if (property.getType().isView()) { String typeName = property.getType().getQualifiedName(); if (typePool.contains(typeName)) { propertyData.ignore = true; } else { typePool.add(typeName); } } if (propertyData.target.isCustomMethod()) { propertyData.propertyType = PropertyType.EXTRACTOR; propertyData.extractor = (StaticMethodExtractor) propertyData.target.getExtractor(); assert propertyData.extractor != null; List<ParamInfo> paramInfoList = propertyData.extractor.getParamInfoList(); propertyData.needParentSource = paramInfoList .stream() .anyMatch(paramInfo -> paramInfo.isSource() || (paramInfo.isPropertyParam() && JpaContext.unSupportType(paramInfo.getInjectedProperty().getType()))); if (propertyData.needParentSource) { propertyData.markParentProvideSource(); } if (propertyData.needParentSource && paramInfoList .stream() .anyMatch(paramInfo -> paramInfo.isPropertyParam() && !paramInfo.getInjectedProperty().sourceCanSeeFrom(jpaContext.getViewContext().getPackageName())) ) { jpaContext.importReflect(); } for (ParamInfo paramInfo : paramInfoList) { if (!propertyData.parentProvideSource() && paramInfo.isPropertyParam()) { Property injectedProperty = paramInfo.getInjectedProperty(); String name = injectedProperty.getName(); jpaContext.newConstructorVar(injectedProperty, propertyData.fixName(name), ArgData.pathVar(propertyData.getPath(name))); } if (paramInfo.isExtraParam()) { paramInfo = propertyData.normParamInfo(paramInfo); String name = propertyData.fixName(paramInfo.getExtraParamName()); jpaContext.newConstructorVar(paramInfo, name, ArgData.extraVar(paramInfo)); jpaContext.getSelectionMethodVarMapper().getVar(paramInfo, name); } } } else { Property base = propertyData.target.getBase(); if (base != null) { boolean unSupportType = JpaContext.unSupportType(base.getType()); if (property.isView()) { propertyData.propertyType = PropertyType.VIEW; propertyData.subContext = context.getViewContext(property.getType()); assert propertyData.subContext != null; if (unSupportType) { if (!propertyData.subContext.hasExtraParams() && !propertyData.subContext.hasExtraProperties()) { propertyData.markParentProvideSource(); propertyData.useReaderMethod = true; } else { propertyData.ignore = true; } } if (!propertyData.ignore && !propertyData.useReaderMethod) { propertyData.viewPropertyData = collectData(jpaContext, propertyData.subContext, typePool, propertyData); propertyData.useReaderMethod = (propertyData.parentProvideSource() || propertyData.provideAsSource) && propertyData.viewPropertyData .stream() .noneMatch(data -> data.ignore && data.propertyType != PropertyType.BASEABLE && data.propertyType != PropertyType.EXTRA); if (!propertyData.parentProvideSource() && propertyData.provideAsSource) { jpaContext.newConstructorVar(base, propertyData.fixName(base.getName()), ArgData.pathVar(propertyData.getPath(base.getName()))); } if (!propertyData.useReaderMethod) { if (propertyData.subContext.hasFieldsConstructor()) { propertyData.useFieldsConstructor = true; propertyData.constructNeedReflect = !propertyData.subContext.canSeeFieldsConstructor(jpaContext.getViewContext().getPackageName()); } else { propertyData.constructNeedReflect = !propertyData.subContext.canSeeEmptyConstructor(jpaContext.getViewContext().getPackageName()); } if (propertyData.constructNeedReflect) { jpaContext.importReflect(); } } } } else { propertyData.propertyType = PropertyType.BASEABLE; if (unSupportType) { propertyData.needParentSource = true; propertyData.markParentProvideSource(); } if (!propertyData.parentProvideSource()) { jpaContext.newConstructorVar(base, propertyData.fixName(base.getName()), ArgData.pathVar(propertyData.getPath(base.getName()))); } } if (propertyData.parentProvideSource() && !canAccessFromProperty(jpaContext, base)) { jpaContext.importReflect(); } } else { propertyData.propertyType = PropertyType.EXTRA; if (JpaContext.unSupportType(property.getType())) { propertyData.ignore = true; } if (!propertyData.ignore) { String name = propertyData.fixName(property.getName()); jpaContext.newConstructorVar(property, name, ArgData.extraVar(property)); jpaContext.getSelectionMethodVarMapper().getVar(property, name); } } } return propertyData; } public PropertyType getPropertyType() { return propertyType; } public boolean isNeedParentSource() { return needParentSource; } public boolean isProvideAsSource() { return provideAsSource; } public boolean isIgnore() { return ignore; } public void markConstructNeedReflect() { this.constructNeedReflect = true; this.jpaContext.importReflect(); } private ParamInfo normParamInfo(ParamInfo paramInfo) { return context.getExtraParams().get(paramInfo.getExtraParamName()); } private static String capitalizeHeader(String value) { if (value == null) { return null; } if (value.isEmpty()) { return value; } if (value.length() == 1) { return value.toUpperCase(); } return Character.toUpperCase(value.charAt(0)) + value.substring(1); } public List<String> getPath() { return getPath(null); } public List<String> getPath(String name) { if (name == null) { name = target.getBase() != null ? target.getBase().getName() : target.getName(); } if (parent == null) { return Collections.singletonList(name); } else { List<String> path = new ArrayList<>(parent.getPath()); path.add(name); return path; } } private String fixName(String name) { if (parent != null) { List<String> path = parent.getPath(); Optional<String> parentName = path.stream().reduce((n1, n2) -> n1 + capitalizeHeader(n2)); return parentName.map(s -> (s + capitalizeHeader(name))).orElse(name); } else { return name; } } private boolean parentProvideSource() { return parent != null ? parent.isProvideAsSource() : jpaContext.isProvideSource(); } private static String getPropertyPackageName(JpaContext jpaContext, Property property) { Elements elementUtils = jpaContext.getViewContext().getProcessingEnv().getElementUtils(); PackageElement propertyPackage = elementUtils.getPackageOf(property.getElement()); return propertyPackage.getQualifiedName().toString(); } private static boolean canAccessFromProperty(JpaContext jpaContext, Property property) { String propertyPackage = getPropertyPackageName(jpaContext, property); String packageName = jpaContext.getViewContext().getPackageName(); boolean samePackage = packageName.equals(propertyPackage); Modifier modifier = property.getModifier(); if (samePackage) { return modifier != null && modifier != Modifier.PRIVATE; } else { return modifier == Modifier.PUBLIC; } } private String getReflectUtilsType() { return jpaContext.getViewContext().getImportedName(JpaContext.TYPE_REFLECT_UTILS, JpaContext.SIMPLE_TYPE_REFLECT_UTILS); } private String getSourceVarInConstructor() { if (ignore) { return null; } if (propertyType == PropertyType.BASEABLE) { Property base = target.getBase(); assert base != null; if (parentProvideSource()) { return getPropertyVar(base, getParentSourceVar()); } else { return jpaContext.getConstructorVarMapper().getVar(base); } } else if (propertyType == PropertyType.EXTRA) { return jpaContext.getConstructorVarMapper().getVar(target); } else if (propertyType == PropertyType.EXTRACTOR) { return null; } else if (propertyType == PropertyType.VIEW) { Property base = target.getBase(); assert base != null; if (parentProvideSource()) { return getPropertyVar(base, getParentSourceVar()); } else if (provideAsSource) { return jpaContext.getConstructorVarMapper().getVar(base); } else { return null; } } else { return null; } } private boolean appendMethodArg(PrintWriter writer, String var, boolean start, boolean breakLine, String indent, int indentNum) { return Utils.appendMethodArg(writer, w -> w.print(var), start, breakLine, indent, indentNum); } private String getParentSourceVar() { return parent != null ? parent.getSourceVarInConstructor() : jpaContext.getConstructorVarMapper().getVar(JpaContext.SOURCE_ARG_KEY); } private String getConfigBeanVar() { return jpaContext.getConstructorVarMapper().getVar(context.getConfigType().getQualifiedName()); } private String getPropertyVar(Property property, String parentSourceVar) { if (property.sourceCanSeeFrom(jpaContext.getViewContext().getPackageName())) { if (property.isMethod()) { return parentSourceVar + "." + property.getGetterName() + "()"; } else { return parentSourceVar + "." + property.getName(); } } else { return getReflectUtilsType() + ".getProperty(" + parentSourceVar + ", " + property.getName() + ", " + (property.isMethod() ? property.getGetterName() : "null") + ")"; } } private void printExtractor(PrintWriter writer, String indent, int indentNum) { assert propertyType == PropertyType.EXTRACTOR; if (extractor.useBeanProvider()) { writer.print(getConfigBeanVar()); } else { context.getConfigType().printType(writer, jpaContext.getViewContext(), false, false); } writer.print("."); writer.print(extractor.getExecutableElement().getSimpleName().toString()); writer.print("("); boolean start = true; boolean breakLine = extractor.getParamInfoList().size() > 3; for (ParamInfo paramInfo : extractor.getParamInfoList()) { String var = null; if (paramInfo.isSource()) { var = getParentSourceVar(); } else if (paramInfo.isPropertyParam()) { Property injectedProperty = paramInfo.getInjectedProperty(); if (parentProvideSource()) { String parentSourceVar = getParentSourceVar(); var = getPropertyVar(injectedProperty, parentSourceVar); } else { var = jpaContext.getConstructorVarMapper().getVar(injectedProperty); } } else if (paramInfo.isExtraParam()) { var = jpaContext.getConstructorVarMapper().getVar(paramInfo); } start = appendMethodArg(writer, var != null ? var : "null", start, breakLine, indent, indentNum + 1); } if (breakLine) { writer.println(); Utils.printIndent(writer, indent, indentNum); } writer.print(")"); } private void printConvertedVar(PrintWriter writer, Type converter, String sourceVar) { converter.startInvokeNew(writer, jpaContext.getViewContext()); converter.endInvokeNew(writer); writer.print(".convert("); writer.print(sourceVar); writer.print(")"); } public void printAssignmentInConstructor(PrintWriter writer, String indent, int indentNum) { if (ignore) { writer.print("null"); } else if (propertyType == PropertyType.VIEW) { VarMapper varMapper = jpaContext.getConstructorVarMapper(); writer.print(varMapper.getVar(target)); } else if (propertyType == PropertyType.BASEABLE) { String sourceVar = getSourceVarInConstructor(); Type converter = target.getConverter(); if (converter != null && sourceVar != null) { printConvertedVar(writer, converter, sourceVar); } else { writer.print(sourceVar); } } else if (propertyType == PropertyType.EXTRACTOR) { printExtractor(writer, indent, indentNum); } else if (propertyType == PropertyType.EXTRA) { VarMapper varMapper = jpaContext.getConstructorVarMapper(); writer.print(varMapper.getVar(target)); } } private Type getViewType(Type from) { if (from.isView()) { return from; } if (from.isType(List.class) || from.isType(Set.class) || from.isType(Stack.class)) { return getViewType(from.getParameters().get(0)); } else if (from.isType(Map.class)) { return getViewType(from.getParameters().get(1)); } else if (from.isArray()) { Type componentType = from.getComponentType(); assert componentType != null; return getViewType(componentType); } else { throw new IllegalArgumentException("Unsupported view collection type: " + from + "."); } } public void prepareConstructor(PrintWriter writer, String indent, int indentNum) { if (ignore) { return; } VarMapper varMapper = jpaContext.getConstructorVarMapper(); if (propertyType == PropertyType.VIEW) { if (useReaderMethod) { String tempVar = varMapper.getVar(target, "viewVar", true); jpaContext.startAssignVar(writer, target.getType(), tempVar, indent, indentNum); getViewType(target.getType()).printType(writer, jpaContext.getViewContext(), false, false); writer.print(".read("); List<Property> extraProperties = subContext.getExtraProperties(); Map<String, ParamInfo> extraParams = subContext.getExtraParams(); boolean breakLine = extraProperties.size() + extraParams.size() > 5; appendMethodArg(writer, getSourceVarInConstructor(), true, breakLine, indent, indentNum + 1); for (Property extraProperty : extraProperties) { String var = jpaContext.getConstructorVarMapper().getVar(extraProperty); appendMethodArg(writer, var != null ? var : "null", false, breakLine, indent, indentNum + 1); } for (ParamInfo paramInfo : extraParams.values()) { String var = jpaContext.getConstructorVarMapper().getVar(paramInfo); appendMethodArg(writer, var != null ? var : "null", false, breakLine, indent, indentNum + 1); } if (breakLine) { Utils.printIndent(writer, indent, indentNum); } writer.println(");"); } else { for (PropertyData propertyData : viewPropertyData) { propertyData.prepareConstructor(writer, indent, indentNum); } String tempVar = varMapper.getVar(target, "viewVar", true); jpaContext.startAssignVar(writer, target.getType(), tempVar, indent, indentNum); if (useFieldsConstructor) { boolean start = true; boolean breakLine = subContext.getProperties().stream().filter(p -> !p.isDynamic()).count() > 5; if (constructNeedReflect) { writer.print(getReflectUtilsType()); writer.println(".newInstance("); Utils.printIndent(writer, indent, indentNum + 1); writer.print(getReflectUtilsType()); writer.print(".getConstructor("); for (Property property : subContext.getProperties()) { if (!property.isDynamic()) { start = Utils.appendMethodArg(writer, w -> { property.getType().printType(w, jpaContext.getViewContext(), false, false); w.print(".class"); }, start, breakLine, indent, indentNum + 2); } } Utils.printIndent(writer, indent, indentNum + 1); writer.print(")"); start = false; breakLine = true; } else { target.getType().startInvokeNew(writer, jpaContext.getViewContext()); } int i = 0; for (Property property : subContext.getProperties()) { if (!property.isDynamic()) { int pos = Helper.findViewPropertyData(viewPropertyData, property, i); PropertyData propertyData = pos != -1 ? viewPropertyData.get(i++) : null; start = Utils.appendMethodArg(writer, (w) -> { if (propertyData != null) { propertyData.printAssignmentInConstructor(w, indent, indentNum + 2); } else { w.print("null"); } }, start, breakLine, indent, indentNum + 1); } } target.getType().endInvokeNew(writer); writer.println(";"); } else { if (constructNeedReflect) { writer.print(getReflectUtilsType()); writer.print(".newInstance("); target.printType(writer, jpaContext.getViewContext(), false, false); writer.println(".class);"); } else { target.getType().startInvokeNew(writer, jpaContext.getViewContext()); target.getType().endInvokeNew(writer); writer.println(";"); } int i = 0; for (Property property : subContext.getProperties()) { if (!property.isDynamic()) { jpaContext.startAssignVar(writer, null, tempVar + "." + subContext.getMappedFieldName(property), indent, indentNum); int pos = Helper.findViewPropertyData(viewPropertyData, property, i); PropertyData propertyData = pos != -1 ? viewPropertyData.get(i++) : null; if (propertyData != null) { propertyData.printAssignmentInConstructor(writer, indent, indentNum + 1); } else { writer.print("null"); } writer.println(";"); } } } } } else if (propertyType == PropertyType.EXTRACTOR) { if (parent == null || !parent.useReaderMethod) { if (extractor.useBeanProvider()) { String configVar = varMapper.getVar(context.getConfigType().getQualifiedName(), "configVar", true); jpaContext.startAssignVar(writer, context.getConfigType(), configVar, indent, indentNum); jpaContext.getViewContext().printBeanProviderGetInstance(writer, context.getConfigType(), BeanUsage.CONFIGURE, "this", false); writer.println(";"); } } } } public Property getTarget() { return target; } } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/annotations/internal/GeneratedMeta.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.annotations.internal; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface GeneratedMeta { Class<?> targetClass(); Class<?> configClass(); Class<?>[] proxies() default {}; } <|start_filename|>beanknife-jpa-runtime/src/main/java/io/github/vipcxj/beanknife/jpa/runtime/utils/ReflectUtils.java<|end_filename|> package io.github.vipcxj.beanknife.jpa.runtime.utils; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class ReflectUtils { public static <T> Constructor<T> getConstructor(Class<T> type, Class<?>... argTypes) { try { return type.getConstructor(argTypes); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } } public static <T> T newInstance(Constructor<T> constructor, Object... args) { try { constructor.setAccessible(true); return constructor.newInstance(args); } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } } public static <T> T newInstance(Class<T> type) { return newInstance(getConstructor(type)); } public static <T> T getProperty(Object target, String propertyName, String getterName) { Class<?> clazz = target.getClass(); if (getterName != null) { try { Method method = clazz.getMethod(getterName); method.setAccessible(true); //noinspection unchecked return (T) method.invoke(target); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { throw new RuntimeException(e); } } else { try { Field clazzField = clazz.getField(propertyName); clazzField.setAccessible(true); //noinspection unchecked return (T) clazzField.get(target); } catch (NoSuchFieldException | IllegalAccessException e) { throw new RuntimeException(e); } } } public static void setProperty(Object target, String field, Object value) { Class<?> clazz = target.getClass(); try { Field clazzField = clazz.getField(field); clazzField.setAccessible(true); clazzField.set(target, value); } catch (NoSuchFieldException | IllegalAccessException e) { throw new RuntimeException(e); } } } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/annotations/ViewWriteBackExclude.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.annotations; import java.lang.annotation.*; @Target(ElementType.TYPE) @Retention(RetentionPolicy.SOURCE) @Repeatable(ViewWriteBackExcludes.class) @Inherited public @interface ViewWriteBackExclude { String[] value(); } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/BeanProviders.java<|end_filename|> package io.github.vipcxj.beanknife.runtime; import io.github.vipcxj.beanknife.runtime.providers.DefaultBeanProvider; import io.github.vipcxj.beanknife.runtime.spi.BeanProvider; import io.github.vipcxj.beanknife.runtime.utils.BeanUsage; import java.lang.ref.WeakReference; import java.util.*; import java.util.concurrent.ConcurrentHashMap; public enum BeanProviders { INSTANCE; private final ServiceLoader<BeanProvider> loader; private Map<String, WeakReference<?>> cacheMap; BeanProviders() { loader = ServiceLoader.load(BeanProvider.class); cacheMap = new ConcurrentHashMap<>(); } public <T> T get(Class<T> type, BeanUsage usage, Object requester, boolean useDefaultBeanProvider, boolean cache) { String key = null; if (cache) { key = type.getName() + "_" + usage.name(); WeakReference<?> reference = cacheMap.get(key); if (reference != null) { Object inst = reference.get(); if (inst != null) { //noinspection unchecked return (T) inst; } // Don't remove invalid reference here. it will be replaced next step. Remove it here may cause concurrent error. } } int priority = Integer.MIN_VALUE; T instance = null; List<Throwable> suppressed = new ArrayList<>(); Throwable throwable = null; for (BeanProvider provider : loader) { if (support(provider, type, usage, useDefaultBeanProvider)) { T inst; try { inst = provider.get(type, usage, requester); } catch (Throwable t) { inst = null; if (throwable != null) { suppressed.add(throwable); } throwable = t; } if (inst != null) { if (provider.getPriority() > priority) { priority = provider.getPriority(); instance = inst; } } } } if (instance == null) { RuntimeException e = new RuntimeException("Unable to initialize the class: " + type.getName() + " for " + usage + " usage."); for (Throwable t : suppressed) { e.addSuppressed(t); } throw e; } if (cache) { cacheMap.put(key, new WeakReference<>(instance)); } return instance; } private <T> boolean support(BeanProvider provider, Class<T> type, BeanUsage usage, boolean useDefaultBeanProvider) { try { if (provider instanceof DefaultBeanProvider && !useDefaultBeanProvider) { return false; } return provider.support(type, usage); } catch (Throwable t) { return false; } } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/SerializableBeanView.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedView; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; @GeneratedView(targetClass = SerializableBean.class, configClass = SerializableBean.class) public class SerializableBeanView implements Serializable { private static final long serialVersionUID = 4L; private String a; private long b; public SerializableBeanView() { } public SerializableBeanView( String a, long b ) { this.a = a; this.b = b; } public SerializableBeanView(SerializableBeanView source) { this.a = source.a; this.b = source.b; } public SerializableBeanView(SerializableBean source) { if (source == null) { throw new NullPointerException("The input source argument of the read constructor of class io.github.vipcxj.beanknife.cases.beans.SerializableBeanView should not be null."); } this.a = source.getA(); this.b = source.getB(); } public static SerializableBeanView read(SerializableBean source) { if (source == null) { return null; } return new SerializableBeanView(source); } public static SerializableBeanView[] read(SerializableBean[] sources) { if (sources == null) { return null; } SerializableBeanView[] results = new SerializableBeanView[sources.length]; for (int i = 0; i < sources.length; ++i) { results[i] = read(sources[i]); } return results; } public static List<SerializableBeanView> read(List<SerializableBean> sources) { if (sources == null) { return null; } List<SerializableBeanView> results = new ArrayList<>(); for (SerializableBean source : sources) { results.add(read(source)); } return results; } public static Set<SerializableBeanView> read(Set<SerializableBean> sources) { if (sources == null) { return null; } Set<SerializableBeanView> results = new HashSet<>(); for (SerializableBean source : sources) { results.add(read(source)); } return results; } public static Stack<SerializableBeanView> read(Stack<SerializableBean> sources) { if (sources == null) { return null; } Stack<SerializableBeanView> results = new Stack<>(); for (SerializableBean source : sources) { results.add(read(source)); } return results; } public static <K> Map<K, SerializableBeanView> read(Map<K, SerializableBean> sources) { if (sources == null) { return null; } Map<K, SerializableBeanView> results = new HashMap<>(); for (Map.Entry<K, SerializableBean> source : sources.entrySet()) { results.put(source.getKey(), read(source.getValue())); } return results; } public String getA() { return this.a; } public long getB() { return this.b; } } <|start_filename|>beanknife-jpa/src/test/java/io/github/vipcxj/beanknife/jpa/models/Company.java<|end_filename|> package io.github.vipcxj.beanknife.jpa.models; import lombok.Getter; import lombok.Setter; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.OneToMany; import java.util.List; @Entity @Getter @Setter public class Company { @Id private String code; private String name; private double money; private Address address; @OneToMany(mappedBy = "company") private List<Department> departments; @OneToMany(mappedBy = "company") private List<Employee> employees; } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/BeanA.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import java.util.Date; import java.util.List; import java.util.Map; public class BeanA { public int a; // (1) protected long b; // (2) public String c; // (3) private boolean d; // (4) private Map<String, List<BeanB>> beanBMap; private String shouldBeRemoved; public Date getC() { // (3) return new Date(); } // (5) public Map<String, List<BeanB>> getBeanBMap() { return beanBMap; } public String getShouldBeRemoved() { return shouldBeRemoved; } } <|start_filename|>beanknife-spring/src/main/java/module-info.java<|end_filename|> open module beanknife.spring { requires beanknife.runtime; requires spring.context; requires static com.github.spotbugs.annotations; provides io.github.vipcxj.beanknife.runtime.spi.BeanProvider with io.github.vipcxj.beanknife.spring.SpringBeanProvider; } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/utils/CacheType.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.utils; public enum CacheType { NONE, LOCAL, GLOBAL } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/ViewMetaInNestBeanMeta.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedMeta; @GeneratedMeta(targetClass = ViewMetaInNestBean.class, configClass = ViewMetaInNestBean.class) public class ViewMetaInNestBeanMeta { public static final String a = "a"; public static final String b = "b"; } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/SimpleBeanWithDefaultSetters.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedView; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; @GeneratedView(targetClass = SimpleBean.class, configClass = SetterAccessViewConfig.class) public class SimpleBeanWithDefaultSetters { private String a; private Integer b; private long c; public SimpleBeanWithDefaultSetters() { } public SimpleBeanWithDefaultSetters( String a, Integer b, long c ) { this.a = a; this.b = b; this.c = c; } public SimpleBeanWithDefaultSetters(SimpleBeanWithDefaultSetters source) { this.a = source.a; this.b = source.b; this.c = source.c; } public SimpleBeanWithDefaultSetters(SimpleBean source) { if (source == null) { throw new NullPointerException("The input source argument of the read constructor of class io.github.vipcxj.beanknife.cases.beans.SimpleBeanWithDefaultSetters should not be null."); } this.a = source.getA(); this.b = source.getB(); this.c = source.getC(); } public static SimpleBeanWithDefaultSetters read(SimpleBean source) { if (source == null) { return null; } return new SimpleBeanWithDefaultSetters(source); } public static SimpleBeanWithDefaultSetters[] read(SimpleBean[] sources) { if (sources == null) { return null; } SimpleBeanWithDefaultSetters[] results = new SimpleBeanWithDefaultSetters[sources.length]; for (int i = 0; i < sources.length; ++i) { results[i] = read(sources[i]); } return results; } public static List<SimpleBeanWithDefaultSetters> read(List<SimpleBean> sources) { if (sources == null) { return null; } List<SimpleBeanWithDefaultSetters> results = new ArrayList<>(); for (SimpleBean source : sources) { results.add(read(source)); } return results; } public static Set<SimpleBeanWithDefaultSetters> read(Set<SimpleBean> sources) { if (sources == null) { return null; } Set<SimpleBeanWithDefaultSetters> results = new HashSet<>(); for (SimpleBean source : sources) { results.add(read(source)); } return results; } public static Stack<SimpleBeanWithDefaultSetters> read(Stack<SimpleBean> sources) { if (sources == null) { return null; } Stack<SimpleBeanWithDefaultSetters> results = new Stack<>(); for (SimpleBean source : sources) { results.add(read(source)); } return results; } public static <K> Map<K, SimpleBeanWithDefaultSetters> read(Map<K, SimpleBean> sources) { if (sources == null) { return null; } Map<K, SimpleBeanWithDefaultSetters> results = new HashMap<>(); for (Map.Entry<K, SimpleBean> source : sources.entrySet()) { results.put(source.getKey(), read(source.getValue())); } return results; } public String getA() { return this.a; } public Integer getB() { return this.b; } public long getC() { return this.c; } void setA(String a) { this.a = a; } void setB(Integer b) { this.b = b; } void setC(long c) { this.c = c; } } <|start_filename|>beanknife-jpa/src/test/java/io/github/vipcxj/beanknife/jpa/models/Employee.java<|end_filename|> package io.github.vipcxj.beanknife.jpa.models; import lombok.Getter; import lombok.Setter; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.ManyToOne; @Entity @Getter @Setter public class Employee { @Id private String number; private String name; @ManyToOne private Department department; @ManyToOne private Company company; } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/CommentBeanView.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedView; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; @GeneratedView(targetClass = CommentBean.class, configClass = CommentBean.class) public class CommentBeanView { private String a; private String b; private long c; public CommentBeanView() { } public CommentBeanView( String a, String b, long c ) { this.a = a; this.b = b; this.c = c; } public CommentBeanView(CommentBeanView source) { this.a = source.a; this.b = source.b; this.c = source.c; } public CommentBeanView(CommentBean source) { if (source == null) { throw new NullPointerException("The input source argument of the read constructor of class io.github.vipcxj.beanknife.cases.beans.CommentBeanView should not be null."); } this.a = source.getA(); this.b = source.getB(); this.c = source.getC(); } public static CommentBeanView read(CommentBean source) { if (source == null) { return null; } return new CommentBeanView(source); } public static CommentBeanView[] read(CommentBean[] sources) { if (sources == null) { return null; } CommentBeanView[] results = new CommentBeanView[sources.length]; for (int i = 0; i < sources.length; ++i) { results[i] = read(sources[i]); } return results; } public static List<CommentBeanView> read(List<CommentBean> sources) { if (sources == null) { return null; } List<CommentBeanView> results = new ArrayList<>(); for (CommentBean source : sources) { results.add(read(source)); } return results; } public static Set<CommentBeanView> read(Set<CommentBean> sources) { if (sources == null) { return null; } Set<CommentBeanView> results = new HashSet<>(); for (CommentBean source : sources) { results.add(read(source)); } return results; } public static Stack<CommentBeanView> read(Stack<CommentBean> sources) { if (sources == null) { return null; } Stack<CommentBeanView> results = new Stack<>(); for (CommentBean source : sources) { results.add(read(source)); } return results; } public static <K> Map<K, CommentBeanView> read(Map<K, CommentBean> sources) { if (sources == null) { return null; } Map<K, CommentBeanView> results = new HashMap<>(); for (Map.Entry<K, CommentBean> source : sources.entrySet()) { results.put(source.getKey(), read(source.getValue())); } return results; } /** * this is a. * this is the second line. * {@link Object} this is some doc annotation. */ public String getA() { return this.a; } /** * this is b. * this is the second line. * {@link Object} this is some doc annotation. */ public String getB() { return this.b; } /** * this is c * this comment is on the method. * this is the second line. * {@link Object} this is some doc annotation. */ public long getC() { return this.c; } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/IllegalPropertyBeanMeta.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedMeta; @GeneratedMeta(targetClass = IllegalPropertyBean.class, configClass = IllegalPropertyBean.class) public class IllegalPropertyBeanMeta { public static final String if_ = "if"; public static final String while_ = "while"; } <|start_filename|>beanknife-core-base/src/main/java/io/github/vipcxj/beanknife/core/GeneratedMetaProcessor.java<|end_filename|> package io.github.vipcxj.beanknife.core; import com.sun.source.util.Trees; import io.github.vipcxj.beanknife.core.models.ProcessorData; import io.github.vipcxj.beanknife.core.models.ViewContext; import io.github.vipcxj.beanknife.core.models.ViewOfData; import io.github.vipcxj.beanknife.core.utils.JetbrainUtils; import io.github.vipcxj.beanknife.core.utils.Utils; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedMeta; import javax.annotation.processing.*; import javax.lang.model.SourceVersion; import javax.lang.model.element.*; import javax.lang.model.type.DeclaredType; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Set; @SupportedAnnotationTypes({"io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedMeta"}) public class GeneratedMetaProcessor extends AbstractProcessor { private ProcessorData processorData; @Override public synchronized void init(ProcessingEnvironment processingEnv) { System.out.println("GeneratedMetaProcessor Init"); super.init(processingEnv); ProcessingEnvironment unwrappedProcessingEnv = JetbrainUtils.jbUnwrap(ProcessingEnvironment.class, this.processingEnv); Trees trees = Trees.instance(unwrappedProcessingEnv); this.processorData = new ProcessorData(trees, unwrappedProcessingEnv); } @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { try { this.processorData.clearViewContextMap(); this.processorData.collect(roundEnv); for (TypeElement annotation : annotations) { // this.processorData.fix(processingEnv); Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(annotation); for (Element element : elements) { List<? extends AnnotationMirror> annotationMirrors = processingEnv.getElementUtils().getAllAnnotationMirrors(element); for (AnnotationMirror annotationMirror : annotationMirrors) { if (Utils.isThisAnnotation(annotationMirror, GeneratedMeta.class)) { Map<? extends ExecutableElement, ? extends AnnotationValue> annotationValues = processingEnv.getElementUtils().getElementValuesWithDefaults(annotationMirror); TypeElement targetElement = (TypeElement) Utils.getTypeAnnotationValue(annotationMirror, annotationValues, "targetClass").asElement(); DeclaredType[] proxies = Utils.getTypeArrayAnnotationValue(annotationMirror, annotationValues, "proxies"); for (DeclaredType proxy : proxies) { TypeElement proxyElement = (TypeElement) proxy.asElement(); List<ViewOfData> viewOfs = this.processorData.getByConfigElement(proxyElement); for (ViewOfData viewOf : viewOfs) { processViewOf(this.processorData, viewOf, targetElement); } } } } } } return true; } catch (Throwable t) { Utils.logError(processingEnv, t); return false; } } private void processViewOf(ProcessorData processorData, ViewOfData viewOfData, TypeElement targetElement) { if (viewOfData.getTargetElement().equals(targetElement)) { ViewContext context = processorData.getViewContext(viewOfData); try { Utils.writeViewFile(context); } catch (IOException e) { Utils.logError(processingEnv, e.getMessage()); } } } @Override public SourceVersion getSupportedSourceVersion() { return SourceVersion.latest(); } } <|start_filename|>beanknife-jpa-examples/src/main/java/io/github/vipcxj/beanknfie/jpa/examples/dto/BaseDtoConfiguration.java<|end_filename|> package io.github.vipcxj.beanknfie.jpa.examples.dto; import io.github.vipcxj.beanknife.jpa.runtime.annotations.AddJpaSupport; import io.github.vipcxj.beanknife.runtime.annotations.ViewGenNameMapper; import io.github.vipcxj.beanknife.runtime.annotations.ViewPropertiesIncludePattern; @ViewPropertiesIncludePattern(".*") @ViewGenNameMapper("${name}Info") @AddJpaSupport public class BaseDtoConfiguration { } <|start_filename|>beanknife-core-base/src/test/java/io/github/vipcxj/beanknife/tests/Utils.java<|end_filename|> package io.github.vipcxj.beanknife.tests; import com.google.testing.compile.Compilation; import com.google.testing.compile.CompilationSubject; import com.google.testing.compile.Compiler; import com.google.testing.compile.JavaFileObjects; import javax.annotation.processing.Processor; import javax.tools.JavaFileObject; import java.util.List; import java.util.stream.Collectors; public class Utils { private static String toSourcePath(String qualifiedClassName) { return qualifiedClassName.replaceAll("\\.", "/") + ".java"; } public static void testViewCase(List<Processor> processors, List<String> qualifiedClassNames, List<String> targetQualifiedClassNames) { List<JavaFileObject> sourceFiles = qualifiedClassNames.stream() .map(Utils::toSourcePath) .map(JavaFileObjects::forResource) .collect(Collectors.toList()); Compilation compilation = Compiler.javac() .withProcessors(processors.toArray(new Processor[0])) .compile(sourceFiles); for (String targetQualifiedClassName : targetQualifiedClassNames) { String genClassPath = toSourcePath(targetQualifiedClassName); CompilationSubject.assertThat(compilation) .generatedSourceFile(targetQualifiedClassName) .hasSourceEquivalentTo(JavaFileObjects.forResource(genClassPath)); } } } <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/beans/MetaAndViewOfOnDiffBean2ViewConfig.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; @ViewOf(value = MetaAndViewOfOnDiffBean2.class, includes = {MetaAndViewOfOnDiffBean2Meta.pa}) public class MetaAndViewOfOnDiffBean2ViewConfig { } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/FieldBeanView.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedView; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; @GeneratedView(targetClass = FieldBean.class, configClass = FieldBeanViewConfig.class) public class FieldBeanView { private long b; private Date c; private Number[] d; public FieldBeanView() { } public FieldBeanView( long b, Date c, Number[] d ) { this.b = b; this.c = c; this.d = d; } public FieldBeanView(FieldBeanView source) { this.b = source.b; this.c = source.c; this.d = source.d; } public FieldBeanView(FieldBean source) { if (source == null) { throw new NullPointerException("The input source argument of the read constructor of class io.github.vipcxj.beanknife.cases.beans.FieldBeanView should not be null."); } this.b = source.b; this.c = source.c; this.d = source.d; } public static FieldBeanView read(FieldBean source) { if (source == null) { return null; } return new FieldBeanView(source); } public static FieldBeanView[] read(FieldBean[] sources) { if (sources == null) { return null; } FieldBeanView[] results = new FieldBeanView[sources.length]; for (int i = 0; i < sources.length; ++i) { results[i] = read(sources[i]); } return results; } public static List<FieldBeanView> read(List<FieldBean> sources) { if (sources == null) { return null; } List<FieldBeanView> results = new ArrayList<>(); for (FieldBean source : sources) { results.add(read(source)); } return results; } public static Set<FieldBeanView> read(Set<FieldBean> sources) { if (sources == null) { return null; } Set<FieldBeanView> results = new HashSet<>(); for (FieldBean source : sources) { results.add(read(source)); } return results; } public static Stack<FieldBeanView> read(Stack<FieldBean> sources) { if (sources == null) { return null; } Stack<FieldBeanView> results = new Stack<>(); for (FieldBean source : sources) { results.add(read(source)); } return results; } public static <K> Map<K, FieldBeanView> read(Map<K, FieldBean> sources) { if (sources == null) { return null; } Map<K, FieldBeanView> results = new HashMap<>(); for (Map.Entry<K, FieldBean> source : sources.entrySet()) { results.put(source.getKey(), read(source.getValue())); } return results; } public long getB() { return this.b; } public Date getC() { return this.c; } public Number[] getD() { return this.d; } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/LombokBeanViewConfigure.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.cases.annotations.MethodAnnotation1; import io.github.vipcxj.beanknife.cases.annotations.PropertyAnnotation1; import io.github.vipcxj.beanknife.runtime.annotations.UseAnnotation; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; @ViewOf(LombokBean.class) @UseAnnotation(PropertyAnnotation1.class) @UseAnnotation(MethodAnnotation1.class) public class LombokBeanViewConfigure extends IncludeAllBaseConfigure { } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/annotations/OverrideViewProperty.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Change a exist property. <br/> * If put on a field, the type of the field should be convertible from the original type.<br/> * Here are three cases:<br/> * 1. The field type can be assigned by the original type.<br/> * 2. Specialize a suitable converter to manually convert the original type to the field type.<br/> * 3. The field type is the DTO version of the original type. * Or the field type is the Array, List, Set, Stack, Map of DTO version of the original type and their composition, and they share the same shape. * For example: BeanDTO vs Bean, * List&lt;BeanDTO&gt; vs List&lt;Bean&gt;, * Map&lt;String, Set&lt;BeanDTO&gt; vs Map&lt;String, Set&lt;Bean&gt; * * @see NewViewProperty */ @Target({ElementType.FIELD, ElementType.METHOD}) @Retention(RetentionPolicy.SOURCE) public @interface OverrideViewProperty { /** * The original property name. * @return The original property name. */ String value(); /** * The access type of the getter methods. * By default, inherited from the {@link ViewOf} or {@link ViewProperty} annotation. * @return the access type of the getter methods */ Access getter() default Access.UNKNOWN; /** * The access type of the setter methods. * By default, inherited from the {@link ViewOf} or {@link ViewProperty} annotation. * @return the access type of the setter methods */ Access setter() default Access.UNKNOWN; } <|start_filename|>beanknife-jpa/src/test/java/io/github/vipcxj/beanknife/jpa/dao/DepartmentRepository.java<|end_filename|> package io.github.vipcxj.beanknife.jpa.dao; import io.github.vipcxj.beanknife.jpa.models.Department; import org.springframework.data.jpa.repository.JpaRepository; public interface DepartmentRepository extends JpaRepository<Department, String> { } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/annotations/ViewMeta.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.annotations; import io.github.vipcxj.beanknife.runtime.utils.Self; import java.lang.annotation.*; /** * Used to generate the meta class. However even not use it, * {@link ViewOf} will generate the meta class as well. * But if you want to change the simple name or package name of the generated class, this is your best choose. */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.SOURCE) @Repeatable(ViewMetas.class) public @interface ViewMeta { /** * The simple name if the generated class . By default, (the simple name if the original Class + "Meta") is used. * @return the target class */ String value() default ""; /** * The package of the generated class. Bu default, the package fo the original class is used. * @return the package of the generated. */ String packageName() default ""; Class<?> of() default Self.class; } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/BeanBViewWithInheritedConfig.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedView; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; @GeneratedView(targetClass = BeanB.class, configClass = InheritedConfigBeanBViewConfig.class) public class BeanBViewWithInheritedConfig { private String a; private BeanA beanA; private String type; private Date timestamp; public BeanBViewWithInheritedConfig() { } public BeanBViewWithInheritedConfig( String a, BeanA beanA, String type, Date timestamp ) { this.a = a; this.beanA = beanA; this.type = type; this.timestamp = timestamp; } public BeanBViewWithInheritedConfig(BeanBViewWithInheritedConfig source) { this.a = source.a; this.beanA = source.beanA; this.type = source.type; this.timestamp = source.timestamp; } public BeanBViewWithInheritedConfig(BeanB source) { if (source == null) { throw new NullPointerException("The input source argument of the read constructor of class io.github.vipcxj.beanknife.cases.beans.BeanBViewWithInheritedConfig should not be null."); } this.a = source.getA(); this.beanA = source.getBeanA(); this.type = InheritedConfigBeanBViewConfig.type(source); this.timestamp = InheritedConfigBeanBViewConfig.timestamp(); } public static BeanBViewWithInheritedConfig read(BeanB source) { if (source == null) { return null; } return new BeanBViewWithInheritedConfig(source); } public static BeanBViewWithInheritedConfig[] read(BeanB[] sources) { if (sources == null) { return null; } BeanBViewWithInheritedConfig[] results = new BeanBViewWithInheritedConfig[sources.length]; for (int i = 0; i < sources.length; ++i) { results[i] = read(sources[i]); } return results; } public static List<BeanBViewWithInheritedConfig> read(List<BeanB> sources) { if (sources == null) { return null; } List<BeanBViewWithInheritedConfig> results = new ArrayList<>(); for (BeanB source : sources) { results.add(read(source)); } return results; } public static Set<BeanBViewWithInheritedConfig> read(Set<BeanB> sources) { if (sources == null) { return null; } Set<BeanBViewWithInheritedConfig> results = new HashSet<>(); for (BeanB source : sources) { results.add(read(source)); } return results; } public static Stack<BeanBViewWithInheritedConfig> read(Stack<BeanB> sources) { if (sources == null) { return null; } Stack<BeanBViewWithInheritedConfig> results = new Stack<>(); for (BeanB source : sources) { results.add(read(source)); } return results; } public static <K> Map<K, BeanBViewWithInheritedConfig> read(Map<K, BeanB> sources) { if (sources == null) { return null; } Map<K, BeanBViewWithInheritedConfig> results = new HashMap<>(); for (Map.Entry<K, BeanB> source : sources.entrySet()) { results.put(source.getKey(), read(source.getValue())); } return results; } public String getA() { return this.a; } public BeanA getBeanA() { return this.beanA; } public String getType() { return this.type; } public Date getTimestamp() { return this.timestamp; } public String getTypeWithTimestamp() { return InheritedConfigBeanBViewConfig.typeWithTimestamp(this.type, this.timestamp); } public Date getToday() { return InheritedConfigBeanBViewConfig.today(); } public Date getYesterday() { return InheritedConfigBeanBViewConfig.yesterday(); } public Date getTomorrow() { return InheritedConfigBeanBViewConfig.tomorrow(); } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/NestedGenericBeanMeta.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedMeta; import java.util.List; import java.util.Set; @GeneratedMeta( targetClass = NestedGenericBean.class, configClass = NestedGenericBean.class, proxies = { NestedGenericBean.class } ) public class NestedGenericBeanMeta { public static final String a = "a"; public static final String b = "b"; public static class Views { public static final String io_github_vipcxj_beanknife_cases_beans_NestedGenericBeanView = "io.github.vipcxj.beanknife.cases.beans.NestedGenericBeanView"; } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/ViewMetaInNestBean$Bean2$Bean1$Bean3Meta.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedMeta; @GeneratedMeta(targetClass = ViewMetaInNestBean.Bean2.Bean1.Bean3.class, configClass = ViewMetaInNestBean.Bean2.Bean1.Bean3.class) public class ViewMetaInNestBean$Bean2$Bean1$Bean3Meta { public static final String c = "c"; } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/ViewOfInNestBean$Bean2$Bean1$Bean3View.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedView; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; @GeneratedView(targetClass = ViewOfInNestBean.Bean2.Bean1.Bean3.class, configClass = ViewOfInNestBean.Bean2.Bean1.Bean3.class) public class ViewOfInNestBean$Bean2$Bean1$Bean3View { public ViewOfInNestBean$Bean2$Bean1$Bean3View() { } public ViewOfInNestBean$Bean2$Bean1$Bean3View(ViewOfInNestBean$Bean2$Bean1$Bean3View source) { } public ViewOfInNestBean$Bean2$Bean1$Bean3View(ViewOfInNestBean.Bean2.Bean1.Bean3 source) { if (source == null) { throw new NullPointerException("The input source argument of the read constructor of class io.github.vipcxj.beanknife.cases.beans.ViewOfInNestBean$Bean2$Bean1$Bean3View should not be null."); } } public static ViewOfInNestBean$Bean2$Bean1$Bean3View read(ViewOfInNestBean.Bean2.Bean1.Bean3 source) { if (source == null) { return null; } return new ViewOfInNestBean$Bean2$Bean1$Bean3View(source); } public static ViewOfInNestBean$Bean2$Bean1$Bean3View[] read(ViewOfInNestBean.Bean2.Bean1.Bean3[] sources) { if (sources == null) { return null; } ViewOfInNestBean$Bean2$Bean1$Bean3View[] results = new ViewOfInNestBean$Bean2$Bean1$Bean3View[sources.length]; for (int i = 0; i < sources.length; ++i) { results[i] = read(sources[i]); } return results; } public static List<ViewOfInNestBean$Bean2$Bean1$Bean3View> read(List<ViewOfInNestBean.Bean2.Bean1.Bean3> sources) { if (sources == null) { return null; } List<ViewOfInNestBean$Bean2$Bean1$Bean3View> results = new ArrayList<>(); for (ViewOfInNestBean.Bean2.Bean1.Bean3 source : sources) { results.add(read(source)); } return results; } public static Set<ViewOfInNestBean$Bean2$Bean1$Bean3View> read(Set<ViewOfInNestBean.Bean2.Bean1.Bean3> sources) { if (sources == null) { return null; } Set<ViewOfInNestBean$Bean2$Bean1$Bean3View> results = new HashSet<>(); for (ViewOfInNestBean.Bean2.Bean1.Bean3 source : sources) { results.add(read(source)); } return results; } public static Stack<ViewOfInNestBean$Bean2$Bean1$Bean3View> read(Stack<ViewOfInNestBean.Bean2.Bean1.Bean3> sources) { if (sources == null) { return null; } Stack<ViewOfInNestBean$Bean2$Bean1$Bean3View> results = new Stack<>(); for (ViewOfInNestBean.Bean2.Bean1.Bean3 source : sources) { results.add(read(source)); } return results; } public static <K> Map<K, ViewOfInNestBean$Bean2$Bean1$Bean3View> read(Map<K, ViewOfInNestBean.Bean2.Bean1.Bean3> sources) { if (sources == null) { return null; } Map<K, ViewOfInNestBean$Bean2$Bean1$Bean3View> results = new HashMap<>(); for (Map.Entry<K, ViewOfInNestBean.Bean2.Bean1.Bean3> source : sources.entrySet()) { results.put(source.getKey(), read(source.getValue())); } return results; } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/ViewPropertyWithExtraBeanView.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedView; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; @GeneratedView(targetClass = ViewPropertyWithExtraBean.class, configClass = ViewPropertyWithExtraContainerBeanViewConfig.class) public class ViewPropertyWithExtraBeanView { public ViewPropertyWithExtraBeanView() { } public ViewPropertyWithExtraBeanView(ViewPropertyWithExtraBeanView source) { } public ViewPropertyWithExtraBeanView(ViewPropertyWithExtraBean source) { if (source == null) { throw new NullPointerException("The input source argument of the read constructor of class io.github.vipcxj.beanknife.cases.beans.ViewPropertyWithExtraBeanView should not be null."); } } public static ViewPropertyWithExtraBeanView read(ViewPropertyWithExtraBean source) { if (source == null) { return null; } return new ViewPropertyWithExtraBeanView(source); } public static ViewPropertyWithExtraBeanView[] read(ViewPropertyWithExtraBean[] sources) { if (sources == null) { return null; } ViewPropertyWithExtraBeanView[] results = new ViewPropertyWithExtraBeanView[sources.length]; for (int i = 0; i < sources.length; ++i) { results[i] = read(sources[i]); } return results; } public static List<ViewPropertyWithExtraBeanView> read(List<ViewPropertyWithExtraBean> sources) { if (sources == null) { return null; } List<ViewPropertyWithExtraBeanView> results = new ArrayList<>(); for (ViewPropertyWithExtraBean source : sources) { results.add(read(source)); } return results; } public static Set<ViewPropertyWithExtraBeanView> read(Set<ViewPropertyWithExtraBean> sources) { if (sources == null) { return null; } Set<ViewPropertyWithExtraBeanView> results = new HashSet<>(); for (ViewPropertyWithExtraBean source : sources) { results.add(read(source)); } return results; } public static Stack<ViewPropertyWithExtraBeanView> read(Stack<ViewPropertyWithExtraBean> sources) { if (sources == null) { return null; } Stack<ViewPropertyWithExtraBeanView> results = new Stack<>(); for (ViewPropertyWithExtraBean source : sources) { results.add(read(source)); } return results; } public static <K> Map<K, ViewPropertyWithExtraBeanView> read(Map<K, ViewPropertyWithExtraBean> sources) { if (sources == null) { return null; } Map<K, ViewPropertyWithExtraBeanView> results = new HashMap<>(); for (Map.Entry<K, ViewPropertyWithExtraBean> source : sources.entrySet()) { results.put(source.getKey(), read(source.getValue())); } return results; } public static String error0() { return "Unable to convert from io.github.vipcxj.beanknife.cases.beans.SimpleBean to its view type io.github.vipcxj.beanknife.cases.beans.ExtraParamsBeanView. Because it has extra properties or extra params."; } public static String error1() { return "Unable to convert from io.github.vipcxj.beanknife.cases.beans.SimpleBean to its view type io.github.vipcxj.beanknife.cases.beans.ExtraProperties1BeanView. Because it has extra properties or extra params."; } public static String error2() { return "Unable to convert from io.github.vipcxj.beanknife.cases.beans.SimpleBean to its view type io.github.vipcxj.beanknife.cases.beans.ExtraProperties2BeanView. Because it has extra properties or extra params."; } } <|start_filename|>beanknife-jpa-runtime/src/main/java/io/github/vipcxj/beanknife/jpa/runtime/annotations/AddJpaSupport.java<|end_filename|> package io.github.vipcxj.beanknife.jpa.runtime.annotations; import java.lang.annotation.*; @Target({ElementType.TYPE}) @Retention(RetentionPolicy.SOURCE) @Inherited public @interface AddJpaSupport { Class<?>[] value() default {}; Class<?>[] extraTargets() default {}; } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/utils/BeanUsage.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.utils; public enum BeanUsage { CONFIGURE, CONVERT_BACK } <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/beans/AObjectMetaConfig.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.cases.models.AObject; import io.github.vipcxj.beanknife.runtime.annotations.ViewMeta; @ViewMeta(of = AObject.class) public class AObjectMetaConfig { } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/annotations/UnUseAnnotation.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.annotations; import java.lang.annotation.*; @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.SOURCE) @Repeatable(UnUseAnnotations.class) @Inherited public @interface UnUseAnnotation { Class<? extends Annotation>[] value() default {}; } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/NestedGenericBean.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; import java.util.List; import java.util.Set; @ViewOf(includePattern = ".*") public class NestedGenericBean<T1 extends CharSequence & Set<? extends Character>, T2 extends List<? extends Set<? super String>>> { private T1 a; private T2 b; public T1 getA() { return a; } public T2 getB() { return b; } @ViewOf(includePattern = ".*") public static class StaticChildBean<T1 extends String> { private T1 a; public T1 getA() { return a; } } @ViewOf(includePattern = ".*") public class DynamicChildBean<T3> { private T1 a; private T2 b; private T3 c; public T1 getA() { return a; } public T2 getB() { return b; } public T3 getC() { return c; } } } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/annotations/ViewPropertiesIncludes.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.annotations; import java.lang.annotation.*; @Target(ElementType.TYPE) @Retention(RetentionPolicy.SOURCE) @Inherited public @interface ViewPropertiesIncludes { ViewPropertiesInclude[] value(); } <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/beans/ExtraProperty1ViewConfigure.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.NewViewProperty; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; import java.util.Date; import java.util.List; @ViewOf(value = SimpleBean.class, genName = "ExtraProperties1BeanView") public class ExtraProperty1ViewConfigure extends IncludeAllBaseConfigure { @NewViewProperty("x") private List<Date> x; } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/annotations/ViewOf.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.annotations; import io.github.vipcxj.beanknife.runtime.utils.BeanUsage; import io.github.vipcxj.beanknife.runtime.utils.CacheType; import io.github.vipcxj.beanknife.runtime.utils.Self; import java.lang.annotation.*; /** * Used to generate the DTO type. */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.SOURCE) @Repeatable(ViewOfs.class) public @interface ViewOf { /** * The targetType * @return the target type. By default the annotated class is used. */ Class<?> value() default Self.class; /** * The configType * @return the config type. By default the annotated class is used. */ Class<?> config() default Self.class; /** * The package name of the generated class. By default the package name of the target class is used. * @return the package name of the generated class */ String genPackage() default ""; /** * The simple name of the generated class. By default the simple name of the target class + View is used. * @return the simple name of the generated class */ String genName() default ""; /** * The access type of the generated class. * @return the access type of the generated class. */ Access access() default Access.PUBLIC; /** * The included properties. By default, nothing is included. * @return the included properties */ String[] includes() default {}; /** * The excluded properties. By default, nothing is excluded. * @return the excluded properties */ String[] excludes() default {}; /** * The regex pattern of the included properties. By default, nothing is included. * @return the regex pattern of the included properties */ String includePattern() default ""; /** * The regex pattern of the excluded properties. By default, nothing is excluded. * @return the regex pattern of the excluded properties */ String excludePattern() default ""; /** * The access type of the empty constructor. By default, public is used. * @return the access type of the empty constructor */ Access emptyConstructor() default Access.PUBLIC; /** * The access type of the field constructor. By default, public is used. * @return the access type of the field constructor */ Access fieldsConstructor() default Access.PUBLIC; /** * The access type of the copy constructor. By default, public is used. * @return the access type of the copy constructor */ Access copyConstructor() default Access.PUBLIC; /** * The access type of the read constructor. By default, public is used. * This constructor accept the original class instance as the only argument. * @return the access type of the read constructor */ Access readConstructor() default Access.PUBLIC; /** * The access type of the getter methods. By default, public is used. * It can be override by the {@link ViewProperty}, {@link OverrideViewProperty} and {@link NewViewProperty}. * @return the access type of the getter methods */ Access getters() default Access.PUBLIC; /** * The access type of the setter methods. By default, none is used, which means there are no setter method. * It can be override by the {@link ViewProperty}, {@link OverrideViewProperty} and {@link NewViewProperty}. * @return the access type of the setter methods */ Access setters() default Access.NONE; /** * Used to control whether to add the error methods. Default is true. * @return whether to add the error methods */ boolean errorMethods() default true; /** * Whether the generated class should implement {@link java.io.Serializable}. By default false. * @return whether the generated class should implement {@link java.io.Serializable} */ boolean serializable() default false; /** * Specialize the serialVersionUID value of the {@link java.io.Serializable}. Only valid when {@link ViewOf#serializable()} is <code>true<code/>. * @return the serialVersionUID value of the {@link java.io.Serializable} */ long serialVersionUID() default 0L; /** * When initialize the configure bean instance, whether to use the default bean provider. * The default bean provider use the empty constructor to initialize the bean. * @see io.github.vipcxj.beanknife.runtime.spi.BeanProvider * @return whether to use default bean provider */ boolean useDefaultBeanProvider() default false; /** * The cache type of the configure bean instance achieved from {@link io.github.vipcxj.beanknife.runtime.spi.BeanProvider}. * By default, {@link CacheType#LOCAL} is used. it means the configure bean instance is cached as a private field in the generated class. * {@link CacheType#NONE} means no cache, call {@link io.github.vipcxj.beanknife.runtime.spi.BeanProvider#get(Class, BeanUsage, Object)} every time. * {@link CacheType#GLOBAL} means cached only once in the whole application context. * @return The cache type of the configure bean instance */ CacheType configureBeanCacheType() default CacheType.LOCAL; /** * Generate a write-back method. Which writing back to the original type instance. * The method does not create a new original type instance. * You should create it yourself and send it to the method as a parameter. * This means collection and map version write-back methods are not possible. * @return The access level of the generated write-back method. By default, {@link Access#NONE} is used, it means no method is generated. */ Access writeBackMethod() default Access.NONE; /** * Generate a create-and-write-back method. Which creating a new original type instance and then writing back to it. * The method create a new original type instance through {@link io.github.vipcxj.beanknife.runtime.spi.BeanProvider}. * By default, no default bean-provider is provided. Set {@link #useDefaultBeanProvider()} to true to activate the default bean provider which just new the instance by reflection. * You can also change the default behaviour by put the annotation {@link ViewUseDefaultBeanProvider} on a base configuration class. * Because there is no external parameters is used, The collection and map version create-and-write-back methods are generated as well. * @see #useDefaultBeanProvider() * @see ViewUseDefaultBeanProvider * @return The access level of the generated create-and-write-back method. By default, {@link Access#NONE} is used, it means no method is generated. */ Access createAndWriteBackMethod() default Access.NONE; } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/converters/NullByteAsZeroConverter.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.converters; import io.github.vipcxj.beanknife.runtime.PropertyConverter; public class NullByteAsZeroConverter implements PropertyConverter<Byte, Byte> { @Override public Byte convert(Byte value) { return value != null ? value : 0; } @Override public Byte convertBack(Byte value) { return value; } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/StaticMethodPropertyBeanView.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.BeanProviders; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedView; import io.github.vipcxj.beanknife.runtime.utils.BeanUsage; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; @GeneratedView(targetClass = SimpleBean.class, configClass = StaticMethodPropertyBeanViewConfig.class) public class StaticMethodPropertyBeanView { private String a; private Object b; private int one; private Integer c; private Integer d; private String e; public StaticMethodPropertyBeanView() { } public StaticMethodPropertyBeanView( String a, Object b, int one, Integer c, Integer d, String e ) { this.a = a; this.b = b; this.one = one; this.c = c; this.d = d; this.e = e; } public StaticMethodPropertyBeanView(StaticMethodPropertyBeanView source) { this.a = source.a; this.b = source.b; this.one = source.one; this.c = source.c; this.d = source.d; this.e = source.e; } public StaticMethodPropertyBeanView(SimpleBean source) { if (source == null) { throw new NullPointerException("The input source argument of the read constructor of class io.github.vipcxj.beanknife.cases.beans.StaticMethodPropertyBeanView should not be null."); } StaticMethodPropertyBeanViewConfig configureBean = BeanProviders.INSTANCE.get(StaticMethodPropertyBeanViewConfig.class, BeanUsage.CONFIGURE, source, false, false); this.a = source.getA(); this.b = StaticMethodPropertyBeanViewConfig.getB(); this.one = StaticMethodPropertyBeanViewConfig.getOne(); this.c = StaticMethodPropertyBeanViewConfig.getC(source); this.d = StaticMethodPropertyBeanViewConfig.getD(source); this.e = configureBean.getABC(source); } public static StaticMethodPropertyBeanView read(SimpleBean source) { if (source == null) { return null; } return new StaticMethodPropertyBeanView(source); } public static StaticMethodPropertyBeanView[] read(SimpleBean[] sources) { if (sources == null) { return null; } StaticMethodPropertyBeanView[] results = new StaticMethodPropertyBeanView[sources.length]; for (int i = 0; i < sources.length; ++i) { results[i] = read(sources[i]); } return results; } public static List<StaticMethodPropertyBeanView> read(List<SimpleBean> sources) { if (sources == null) { return null; } List<StaticMethodPropertyBeanView> results = new ArrayList<>(); for (SimpleBean source : sources) { results.add(read(source)); } return results; } public static Set<StaticMethodPropertyBeanView> read(Set<SimpleBean> sources) { if (sources == null) { return null; } Set<StaticMethodPropertyBeanView> results = new HashSet<>(); for (SimpleBean source : sources) { results.add(read(source)); } return results; } public static Stack<StaticMethodPropertyBeanView> read(Stack<SimpleBean> sources) { if (sources == null) { return null; } Stack<StaticMethodPropertyBeanView> results = new Stack<>(); for (SimpleBean source : sources) { results.add(read(source)); } return results; } public static <K> Map<K, StaticMethodPropertyBeanView> read(Map<K, SimpleBean> sources) { if (sources == null) { return null; } Map<K, StaticMethodPropertyBeanView> results = new HashMap<>(); for (Map.Entry<K, SimpleBean> source : sources.entrySet()) { results.put(source.getKey(), read(source.getValue())); } return results; } public String getA() { return this.a; } public Object getB() { return this.b; } public int getOne() { return this.one; } public Integer getC() { return this.c; } public Integer getD() { return this.d; } /** * test non static method as a static method property. * Though the source can be compiled, * this will cause a exception in the runtime. Because {@link ViewOf#useDefaultBeanProvider()} is false here. * So no bean provider is used. Then the configure class {@link StaticMethodPropertyBeanViewConfig} can not be initialized. * @return the property value */ public String getE() { return this.e; } } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/annotations/ExtraParam.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.SOURCE) public @interface ExtraParam { String value(); } <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/beans/ViewPropertyWithExtraContainerBeanViewConfig.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.OverrideViewProperty; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; import java.util.List; import java.util.Map; import java.util.Set; @ViewOf(value = ViewPropertyWithExtraBean.class) public class ViewPropertyWithExtraContainerBeanViewConfig extends IncludeAllBaseConfigure { @OverrideViewProperty(ViewPropertyWithExtraBeanMeta.a) private ExtraParamsBeanView a; @OverrideViewProperty(ViewPropertyWithExtraBeanMeta.b) private Map<String, List<ExtraProperties1BeanView[]>> b; @OverrideViewProperty(ViewPropertyWithExtraBeanMeta.c) private Set<ExtraProperties2BeanView> c; } <|start_filename|>beanknife-core-base/src/main/java/io/github/vipcxj/beanknife/core/ViewCodeGenerators.java<|end_filename|> package io.github.vipcxj.beanknife.core; import io.github.vipcxj.beanknife.core.spi.ViewCodeGenerator; import io.github.vipcxj.beanknife.core.utils.ResourceFinder; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import java.util.ServiceLoader; public enum ViewCodeGenerators { INSTANCE; private final List<ViewCodeGenerator> generators; ViewCodeGenerators() { this.generators = new ArrayList<>(); ResourceFinder finder = new ResourceFinder("META-INF/services/", ViewOfProcessor.class.getClassLoader()); try { List<Class<? extends ViewCodeGenerator>> implementations = finder.findAllImplementations(ViewCodeGenerator.class); for (Class<? extends ViewCodeGenerator> implementation : implementations) { generators.add(implementation.getDeclaredConstructor().newInstance()); } } catch (IOException | ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { e.printStackTrace(); } } public List<ViewCodeGenerator> getGenerators() { return generators; } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/Parent1ViewConfigure.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.ViewGenNameMapper; import io.github.vipcxj.beanknife.runtime.annotations.ViewPropertiesIncludePattern; @ViewGenNameMapper("ViewOf${name}") @ViewPropertiesIncludePattern(".*") public class Parent1ViewConfigure extends GrandparentViewConfigure { } <|start_filename|>beanknife-jpa/src/test/java/io/github/vipcxj/beanknife/jpa/dao/CompanyRepository.java<|end_filename|> package io.github.vipcxj.beanknife.jpa.dao; import io.github.vipcxj.beanknife.jpa.models.Company; import org.springframework.data.jpa.repository.JpaRepository; public interface CompanyRepository extends JpaRepository<Company, String> { } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/ChangePackageMetaConfig.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.ViewMeta; @ViewMeta(packageName = "io.github.vipcxj.beanknife.cases.otherbean", of = InheritedBean.class) public class ChangePackageMetaConfig { } <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/beans/GenericBean.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.ViewMeta; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; import java.util.List; import java.util.Map; import java.util.Set; @ViewMeta @ViewOf(includes = {GenericBeanMeta.a, GenericBeanMeta.b, GenericBeanMeta.c, GenericBeanMeta.d, GenericBeanMeta.e}) public class GenericBean<T1 extends CharSequence & Set<? extends Character>, T2 extends List<? extends Set<? super String>>> { private T1 a; private T2 b; private List<T1> c; private T2[] d; private List<Map<String, Map<T1, T2>>[]>[] e; public T1 getA() { return a; } public T2 getB() { return b; } public List<T1> getC() { return c; } public T2[] getD() { return d; } public List<Map<String, Map<T1, T2>>[]>[] getE() { return e; } } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/annotations/Dynamic.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * The property annotated by this annotation is the dynamic property, * which means the property value is calculated when the getter method is called. * In other words, there is no really field in the generated class, * the property value is calculated on the fly.<br/> * The method annotated by this annotation should has the shape as following: <br/> * <pre> * public static PropertyType methodName(@InjectProperty TypeOfPropertyA a, @InjectProperty TypeOfPropertyB b, ...) * <pre/> */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.SOURCE) public @interface Dynamic { } <|start_filename|>beanknife-jpa-examples/src/main/java/io/github/vipcxj/beanknfie/jpa/examples/dao/EmployeeRepository.java<|end_filename|> package io.github.vipcxj.beanknfie.jpa.examples.dao; import io.github.vipcxj.beanknfie.jpa.examples.models.Employee; import org.springframework.data.jpa.repository.JpaRepository; public interface EmployeeRepository extends JpaRepository<Employee, String> { } <|start_filename|>beanknife-runtime/src/main/java/module-info.java<|end_filename|> open module beanknife.runtime { uses io.github.vipcxj.beanknife.runtime.spi.BeanProvider; exports io.github.vipcxj.beanknife.runtime; exports io.github.vipcxj.beanknife.runtime.annotations; exports io.github.vipcxj.beanknife.runtime.annotations.internal; exports io.github.vipcxj.beanknife.runtime.converters; exports io.github.vipcxj.beanknife.runtime.spi; exports io.github.vipcxj.beanknife.runtime.utils; } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/Leaf21BeanViewConfigure.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; import io.github.vipcxj.beanknife.runtime.annotations.ViewPropertiesInclude; @ViewOf(Leaf21Bean.class) @ViewPropertiesInclude(Leaf21BeanMeta.c) public class Leaf21BeanViewConfigure extends Parent2ViewConfigure { } <|start_filename|>beanknife-jpa-examples/src/main/java/io/github/vipcxj/beanknfie/jpa/examples/dao/CompanyRepository.java<|end_filename|> package io.github.vipcxj.beanknfie.jpa.examples.dao; import io.github.vipcxj.beanknfie.jpa.examples.models.Company; import org.springframework.data.jpa.repository.JpaRepository; public interface CompanyRepository extends JpaRepository<Company, String> { } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/AnnotationBeanMeta.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedMeta; @GeneratedMeta( targetClass = AnnotationBean.class, configClass = AnnotationBean.class, proxies = { AnnotationBeanViewConfigure.class } ) public class AnnotationBeanMeta { public static final String type = "type"; public static final String a = "a"; public static final String b = "b"; public static final String c = "c"; public static final String d = "d"; public static final String e = "e"; public static final String f = "f"; public static final String g = "g"; public static class Views { public static final String io_github_vipcxj_beanknife_cases_beans_AnnotationBeanView = "io.github.vipcxj.beanknife.cases.beans.AnnotationBeanView"; } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/ViewOfLeaf11Bean.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedView; import java.io.Serializable; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; @GeneratedView(targetClass = Leaf11Bean.class, configClass = Leaf11BeanViewConfigure.class) public class ViewOfLeaf11Bean implements Serializable { private static final long serialVersionUID = 0L; private Class<? extends Annotation> b; private List<? extends String> c; private long d; private String e; public ViewOfLeaf11Bean() { } public ViewOfLeaf11Bean( Class<? extends Annotation> b, List<? extends String> c, long d, String e ) { this.b = b; this.c = c; this.d = d; this.e = e; } public ViewOfLeaf11Bean(ViewOfLeaf11Bean source) { this.b = source.b; this.c = source.c; this.d = source.d; this.e = source.e; } public static ViewOfLeaf11Bean read(Leaf11Bean source) { if (source == null) { return null; } ViewOfLeaf11Bean out = new ViewOfLeaf11Bean(); out.b = source.getB(); out.c = source.getC(); out.d = source.getD(); out.e = source.getE(); return out; } public static ViewOfLeaf11Bean[] read(Leaf11Bean[] sources) { if (sources == null) { return null; } ViewOfLeaf11Bean[] results = new ViewOfLeaf11Bean[sources.length]; for (int i = 0; i < sources.length; ++i) { results[i] = read(sources[i]); } return results; } public static List<ViewOfLeaf11Bean> read(List<Leaf11Bean> sources) { if (sources == null) { return null; } List<ViewOfLeaf11Bean> results = new ArrayList<>(); for (Leaf11Bean source : sources) { results.add(read(source)); } return results; } public static Set<ViewOfLeaf11Bean> read(Set<Leaf11Bean> sources) { if (sources == null) { return null; } Set<ViewOfLeaf11Bean> results = new HashSet<>(); for (Leaf11Bean source : sources) { results.add(read(source)); } return results; } public static Stack<ViewOfLeaf11Bean> read(Stack<Leaf11Bean> sources) { if (sources == null) { return null; } Stack<ViewOfLeaf11Bean> results = new Stack<>(); for (Leaf11Bean source : sources) { results.add(read(source)); } return results; } public static <K> Map<K, ViewOfLeaf11Bean> read(Map<K, Leaf11Bean> sources) { if (sources == null) { return null; } Map<K, ViewOfLeaf11Bean> results = new HashMap<>(); for (Map.Entry<K, Leaf11Bean> source : sources.entrySet()) { results.put(source.getKey(), read(source.getValue())); } return results; } public Class<? extends Annotation> getB() { return this.b; } public List<? extends String> getC() { return this.c; } public long getD() { return this.d; } public String getE() { return this.e; } protected void setB(Class<? extends Annotation> b) { this.b = b; } protected void setC(List<? extends String> c) { this.c = c; } protected void setD(long d) { this.d = d; } protected void setE(String e) { this.e = e; } } <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/beans/IncludeAllBaseConfigure.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.ViewPropertiesIncludePattern; @ViewPropertiesIncludePattern(".*") public class IncludeAllBaseConfigure { } <|start_filename|>tools-dependency-maven-plugin/src/main/java/io/github/vipcxj/maven/plugins/ToolsDependencyMojo.java<|end_filename|> package io.github.vipcxj.maven.plugins; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.factory.ArtifactFactory; import org.apache.maven.execution.MavenSession; import org.apache.maven.model.Dependency; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Component; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import org.apache.maven.project.MavenProjectHelper; import org.apache.maven.toolchain.Toolchain; import org.apache.maven.toolchain.ToolchainManager; import org.apache.maven.toolchain.java.DefaultJavaToolChain; import java.io.File; import java.io.IOException; import java.util.Set; @Mojo(name = "resolve", defaultPhase = LifecyclePhase.INITIALIZE, threadSafe = true) public class ToolsDependencyMojo extends AbstractMojo { @Component private ToolchainManager toolchainManager; @Component private ArtifactFactory artifactFactory; @Parameter(defaultValue = "${session}", readonly = false, required = true) private MavenSession session; @Parameter(defaultValue = "${project}", readonly = false, required = true) private MavenProject project; private DefaultJavaToolChain getToolchain() { DefaultJavaToolChain javaToolchain = null; if (toolchainManager != null) { final Toolchain tc = toolchainManager.getToolchainFromBuildContext("jdk", session); if (tc.getClass().equals(DefaultJavaToolChain.class)) { // can this ever NOT happen? javaToolchain = (DefaultJavaToolChain) tc; } } return javaToolchain; } public static String normalize(String path) { String normalized = path; while(true) { int index = normalized.indexOf("//"); if (index < 0) { while(true) { index = normalized.indexOf("/./"); if (index < 0) { while(true) { index = normalized.indexOf("/../"); if (index < 0) { return normalized; } if (index == 0) { return null; } int index2 = normalized.lastIndexOf(47, index - 1); normalized = normalized.substring(0, index2) + normalized.substring(index + 3); } } normalized = normalized.substring(0, index) + normalized.substring(index + 2); } } normalized = normalized.substring(0, index) + normalized.substring(index + 1); } } private File findTools(String javaHome) { String normalize = normalize(javaHome); if (normalize == null) { return null; } File installFolder = new File(normalize); if (!installFolder.exists()) { return null; } File toolsFile = new File(installFolder, "lib/tools.jar"); if (!toolsFile.exists()) { toolsFile = new File(installFolder, "Classes/classes.jar"); if (!toolsFile.exists()) { return null; } } return toolsFile; } public void execute() { String javaHome; DefaultJavaToolChain tc = getToolchain(); if (tc != null) { getLog().info("Toolchain in javahome-resolver-maven-plugin: " + tc); // we are interested in JAVA_HOME for given jdk javaHome = tc.getJavaHome(); } else { javaHome = System.getenv("JAVA_HOME"); if (javaHome == null) { getLog().error("No toolchain configured. No JAVA_HOME configured"); return; } getLog().error("No toolchain in javahome-resolver-maven-plugin. Using default JDK[" + javaHome + "]"); } File toolsFile = findTools(javaHome); if (toolsFile != null) { addOptionJarDependency("jdk.tools", "jdk.tools", "1.0.0", toolsFile); getLog().info("Success add tools dependency. The tools.jar is at \"" + toolsFile.getAbsolutePath() + "\""); } } private void addOptionJarDependency(String groupId, String artifactId, String version, File file) { //noinspection unchecked Set<Artifact> artifacts = project.getDependencyArtifacts(); for (Artifact artifact : artifacts) { if (artifact.getGroupId().equals(groupId) && artifact.getArtifactId().equals(artifactId)) { return; } } Artifact artifact = artifactFactory.createArtifact(groupId, artifactId, version, "system", "jar"); artifact.setFile(file); artifact.setOptional(true); artifacts.add(artifact); } } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/annotations/Access.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.annotations; public enum Access { PUBLIC, PRIVATE, PROTECTED, DEFAULT, NONE, UNKNOWN; @Override public String toString() { return name().toLowerCase(); } } <|start_filename|>beanknife-jpa/src/test/java/io/github/vipcxj/beanknife/jpa/dto/BaseDtoConfiguration.java<|end_filename|> package io.github.vipcxj.beanknife.jpa.dto; import io.github.vipcxj.beanknife.runtime.annotations.ViewGenNameMapper; import io.github.vipcxj.beanknife.runtime.annotations.ViewPropertiesIncludePattern; @ViewPropertiesIncludePattern(".*") @ViewGenNameMapper("${name}Info") public class BaseDtoConfiguration { } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/BeanAView.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedView; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; @GeneratedView(targetClass = BeanA.class, configClass = ConfigBeanA.class) public class BeanAView { private int a; private long b; private Date c; private Map<String, List<BeanBView>> beanBMap; private boolean d; public BeanAView() { } public BeanAView( int a, long b, Date c, Map<String, List<BeanBView>> beanBMap, boolean d ) { this.a = a; this.b = b; this.c = c; this.beanBMap = beanBMap; this.d = d; } public BeanAView(BeanAView source) { this.a = source.a; this.b = source.b; this.c = source.c; this.beanBMap = source.beanBMap; this.d = source.d; } public BeanAView(BeanA source) { if (source == null) { throw new NullPointerException("The input source argument of the read constructor of class io.github.vipcxj.beanknife.cases.beans.BeanAView should not be null."); } Map<String, List<BeanBView>> p0 = new HashMap<>(); for (Map.Entry<String, List<BeanB>> el0 : source.getBeanBMap().entrySet()) { List<BeanBView> result0 = new ArrayList<>(); for (BeanB el1 : el0.getValue()) { BeanBView result1 = BeanBView.read(el1); result0.add(result1); } p0.put(el0.getKey(), result0); } this.a = source.a; this.b = source.b; this.c = source.getC(); this.beanBMap = p0; this.d = ConfigBeanA.d(source); } public static BeanAView read(BeanA source) { if (source == null) { return null; } return new BeanAView(source); } public static BeanAView[] read(BeanA[] sources) { if (sources == null) { return null; } BeanAView[] results = new BeanAView[sources.length]; for (int i = 0; i < sources.length; ++i) { results[i] = read(sources[i]); } return results; } public static List<BeanAView> read(List<BeanA> sources) { if (sources == null) { return null; } List<BeanAView> results = new ArrayList<>(); for (BeanA source : sources) { results.add(read(source)); } return results; } public static Set<BeanAView> read(Set<BeanA> sources) { if (sources == null) { return null; } Set<BeanAView> results = new HashSet<>(); for (BeanA source : sources) { results.add(read(source)); } return results; } public static Stack<BeanAView> read(Stack<BeanA> sources) { if (sources == null) { return null; } Stack<BeanAView> results = new Stack<>(); for (BeanA source : sources) { results.add(read(source)); } return results; } public static <K> Map<K, BeanAView> read(Map<K, BeanA> sources) { if (sources == null) { return null; } Map<K, BeanAView> results = new HashMap<>(); for (Map.Entry<K, BeanA> source : sources.entrySet()) { results.put(source.getKey(), read(source.getValue())); } return results; } public int getA() { return this.a; } public long getB() { return this.b; } public Date getC() { return this.c; } public Map<String, List<BeanBView>> getBeanBMap() { return this.beanBMap; } public boolean isD() { return this.d; } public String getE() { return ConfigBeanA.e(this.a, this.b); } } <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/beans/InheritedConfigBaseViewConfig.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.Dynamic; import io.github.vipcxj.beanknife.runtime.annotations.InjectProperty; import io.github.vipcxj.beanknife.runtime.annotations.NewViewProperty; import io.github.vipcxj.beanknife.runtime.annotations.RemoveViewProperty; import java.util.Calendar; import java.util.Date; @RemoveViewProperty("shouldBeRemoved") public class InheritedConfigBaseViewConfig { @NewViewProperty("type") public static String type(Object source) { return source.getClass().getCanonicalName(); } @NewViewProperty("timestamp") public static Date timestamp() { return new Date(); } @NewViewProperty("typeWithTimestamp") @Dynamic public static String typeWithTimestamp(@InjectProperty String type, @InjectProperty Date timestamp) { return type + timestamp.getTime(); } private static Calendar currentDay() { Calendar instance = Calendar.getInstance(); instance.set(Calendar.HOUR_OF_DAY, 0); return instance; } @NewViewProperty("today") @Dynamic public static Date today() { return currentDay().getTime(); } @NewViewProperty("yesterday") @Dynamic public static Date yesterday() { Calendar instance = currentDay(); instance.add(Calendar.DAY_OF_MONTH, -1); return instance.getTime(); } @NewViewProperty("tomorrow") @Dynamic public static Date tomorrow() { Calendar instance = currentDay(); instance.add(Calendar.DAY_OF_MONTH, 1); return instance.getTime(); } } <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/beans/ViewPropertyBeanViewConfig.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.RemoveViewProperty; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; @ViewOf(value = ViewPropertyBean.class, genName = "ViewPropertyBeanWithoutParent", includePattern = ".*") @RemoveViewProperty(ViewPropertyBeanMeta.parent) public class ViewPropertyBeanViewConfig { } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/ViewOfInNestBean$Bean2$Bean1$Bean3Meta.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedMeta; @GeneratedMeta( targetClass = ViewOfInNestBean.Bean2.Bean1.Bean3.class, configClass = ViewOfInNestBean.Bean2.Bean1.Bean3.class, proxies = { ViewOfInNestBean.Bean2.Bean1.Bean3.class } ) public class ViewOfInNestBean$Bean2$Bean1$Bean3Meta { public static final String c = "c"; public static class Views { public static final String io_github_vipcxj_beanknife_cases_beans_ViewOfInNestBean$Bean2$Bean1$Bean3View = "io.github.vipcxj.beanknife.cases.beans.ViewOfInNestBean$Bean2$Bean1$Bean3View"; } } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/PropertyConverter.java<|end_filename|> package io.github.vipcxj.beanknife.runtime; /** * All type converter should implement this interface. * And the implementation should instantiate the generic parameters.<br/> * Such as:<br/><br/> * <pre> * public class MyConverter implements PropertyConverter&lt;Integer, String&gt; { * String convert(Integer from) { * ... * } * } * </pre> * In other words, the implementation shouldn't has generic parameters. * Or the library can't detect what <code>FromType<code/> and <code>ToType<code/> really are. * @param <FromType> from type * @param <ToType> to type */ public interface PropertyConverter<FromType, ToType> { ToType convert(FromType value); FromType convertBack(ToType value); } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/Leaf11BeanViewConfigure.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; @ViewOf(Leaf11Bean.class) public class Leaf11BeanViewConfigure extends Parent1ViewConfigure { } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/converters/NullShortAsZeroConverter.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.converters; import io.github.vipcxj.beanknife.runtime.PropertyConverter; public class NullShortAsZeroConverter implements PropertyConverter<Short, Short> { @Override public Short convert(Short value) { return value != null ? value : 0; } @Override public Short convertBack(Short value) { return value; } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/AnnotationBeanView.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.cases.annotations.DocumentedTypeAnnotation; import io.github.vipcxj.beanknife.cases.annotations.FieldAnnotation1; import io.github.vipcxj.beanknife.cases.annotations.FieldAnnotation2; import io.github.vipcxj.beanknife.cases.annotations.InheritableTypeAnnotation; import io.github.vipcxj.beanknife.cases.annotations.MethodAnnotation1; import io.github.vipcxj.beanknife.cases.annotations.PropertyAnnotation1; import io.github.vipcxj.beanknife.cases.annotations.PropertyAnnotation2; import io.github.vipcxj.beanknife.cases.annotations.TypeAnnotation; import io.github.vipcxj.beanknife.cases.annotations.ValueAnnotation1; import io.github.vipcxj.beanknife.cases.annotations.ValueAnnotation2; import io.github.vipcxj.beanknife.cases.models.AEnum; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedView; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; @GeneratedView(targetClass = AnnotationBean.class, configClass = AnnotationBeanViewConfigure.class) @InheritableTypeAnnotation( annotation = @ValueAnnotation1(type = { int.class }), annotations = { @ValueAnnotation1(type = { void.class }), @ValueAnnotation1(type = { String.class }), @ValueAnnotation1(type = { int[][][].class }), @ValueAnnotation1(type = { Void.class }), @ValueAnnotation1(type = { Void[].class }) } ) @TypeAnnotation(Date.class) @DocumentedTypeAnnotation( enumValue = AEnum.B, enumValues = { AEnum.C, AEnum.B, AEnum.A } ) public class AnnotationBeanView { @FieldAnnotation1(enumClassArray = { AEnum.class, AEnum.class }) private Class<?> type; @FieldAnnotation1(doubleArray = { 1.0 }) private String a; private String b; @FieldAnnotation1(charValue = '0') @FieldAnnotation2(stringArray = { "5" }) private String[] c; private int d; @PropertyAnnotation2(stringValue = "config_e") private Date e; @PropertyAnnotation2(stringValue = "field_f") private List<String> f; @PropertyAnnotation1(stringValue = "field_g") private short g; public AnnotationBeanView() { } public AnnotationBeanView( Class<?> type, String a, String b, String[] c, int d, Date e, List<String> f, short g ) { this.type = type; this.a = a; this.b = b; this.c = c; this.d = d; this.e = e; this.f = f; this.g = g; } public AnnotationBeanView(AnnotationBeanView source) { this.type = source.type; this.a = source.a; this.b = source.b; this.c = source.c; this.d = source.d; this.e = source.e; this.f = source.f; this.g = source.g; } public AnnotationBeanView(AnnotationBean source) { if (source == null) { throw new NullPointerException("The input source argument of the read constructor of class io.github.vipcxj.beanknife.cases.beans.AnnotationBeanView should not be null."); } this.type = source.type; this.a = source.getA(); this.b = source.getB(); this.c = source.getC(); this.d = source.getD(); this.e = source.getE(); this.f = source.getF(); this.g = source.getG(); } public static AnnotationBeanView read(AnnotationBean source) { if (source == null) { return null; } return new AnnotationBeanView(source); } public static AnnotationBeanView[] read(AnnotationBean[] sources) { if (sources == null) { return null; } AnnotationBeanView[] results = new AnnotationBeanView[sources.length]; for (int i = 0; i < sources.length; ++i) { results[i] = read(sources[i]); } return results; } public static List<AnnotationBeanView> read(List<AnnotationBean> sources) { if (sources == null) { return null; } List<AnnotationBeanView> results = new ArrayList<>(); for (AnnotationBean source : sources) { results.add(read(source)); } return results; } public static Set<AnnotationBeanView> read(Set<AnnotationBean> sources) { if (sources == null) { return null; } Set<AnnotationBeanView> results = new HashSet<>(); for (AnnotationBean source : sources) { results.add(read(source)); } return results; } public static Stack<AnnotationBeanView> read(Stack<AnnotationBean> sources) { if (sources == null) { return null; } Stack<AnnotationBeanView> results = new Stack<>(); for (AnnotationBean source : sources) { results.add(read(source)); } return results; } public static <K> Map<K, AnnotationBeanView> read(Map<K, AnnotationBean> sources) { if (sources == null) { return null; } Map<K, AnnotationBeanView> results = new HashMap<>(); for (Map.Entry<K, AnnotationBean> source : sources.entrySet()) { results.put(source.getKey(), read(source.getValue())); } return results; } public Class<?> getType() { return this.type; } public String getA() { return this.a; } public String getB() { return this.b; } public String[] getC() { return this.c; } @PropertyAnnotation1 @MethodAnnotation1( charValue = 'a', annotations = { @ValueAnnotation1, @ValueAnnotation1(annotations = { @ValueAnnotation2 }) } ) public int getD() { return this.d; } public Date getE() { return this.e; } public List<String> getF() { return this.f; } @PropertyAnnotation1(stringValue = "getter_g") public short getG() { return this.g; } } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/converters/NullBigIntegerAsZeroConverter.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.converters; import io.github.vipcxj.beanknife.runtime.PropertyConverter; import java.math.BigInteger; public class NullBigIntegerAsZeroConverter implements PropertyConverter<BigInteger, BigInteger> { @Override public BigInteger convert(BigInteger value) { return value != null ? value : BigInteger.ZERO; } @Override public BigInteger convertBack(BigInteger value) { return value; } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/GenericBeanMeta.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedMeta; import java.util.List; import java.util.Set; @GeneratedMeta( targetClass = GenericBean.class, configClass = GenericBean.class, proxies = { GenericBean.class } ) public class GenericBeanMeta { public static final String a = "a"; public static final String b = "b"; public static final String c = "c"; public static final String d = "d"; public static final String e = "e"; public static class Views { public static final String io_github_vipcxj_beanknife_cases_beans_GenericBeanView = "io.github.vipcxj.beanknife.cases.beans.GenericBeanView"; } } <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/beans/ViewPropertyContainerBean.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.ViewMeta; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; @ViewMeta public class ViewPropertyContainerBean { private long a; private String b; private ViewPropertyBean view; private ViewPropertyBean[] viewArray; private List<ViewPropertyBean> viewList; private Set<ViewPropertyBean> viewSet; private Map<String, ViewPropertyBean> viewMap; private List<Map<String, ViewPropertyBean>> viewMapList; private Map<String, List<ViewPropertyBean>> viewListMap; private Map<String, List<Map<Integer, Stack<ViewPropertyBean>>>> viewStackMapListMap; private Map<String, List<Map<Integer, Stack<ViewPropertyBean>>>>[][][] viewStackMapListMapArrayArrayArray; public long getA() { return a; } public String getB() { return b; } public ViewPropertyBean getView() { return view; } public List<ViewPropertyBean> getViewList() { return viewList; } public ViewPropertyBean[] getViewArray() { return viewArray; } public Set<ViewPropertyBean> getViewSet() { return viewSet; } public Map<String, ViewPropertyBean> getViewMap() { return viewMap; } public List<Map<String, ViewPropertyBean>> getViewMapList() { return viewMapList; } public Map<String, List<ViewPropertyBean>> getViewListMap() { return viewListMap; } public Map<String, List<Map<Integer, Stack<ViewPropertyBean>>>> getViewStackMapListMap() { return viewStackMapListMap; } public Map<String, List<Map<Integer, Stack<ViewPropertyBean>>>>[][][] getViewStackMapListMapArrayArrayArray() { return viewStackMapListMapArrayArrayArray; } } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/converters/NullStringAsEmpty.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.converters; import io.github.vipcxj.beanknife.runtime.annotations.UsePropertyConverter; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ ElementType.FIELD, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.SOURCE) @UsePropertyConverter(NullStringAsEmptyConverter.class) public @interface NullStringAsEmpty { } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/converters/NullIntegerAsZeroConverter.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.converters; import io.github.vipcxj.beanknife.runtime.PropertyConverter; public class NullIntegerAsZeroConverter implements PropertyConverter<Integer, Integer> { @Override public Integer convert(Integer value) { return value != null ? value : 0; } @Override public Integer convertBack(Integer value) { return value; } } <|start_filename|>beanknife-spring/src/main/java/io/github/vipcxj/beanknife/spring/SpringBeanProviderAutoConfigure.java<|end_filename|> package io.github.vipcxj.beanknife.spring; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; @Configuration @Import(BeanUtils.class) public class SpringBeanProviderAutoConfigure { } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/ViewPropertyContainerBeanView.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedView; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; @GeneratedView(targetClass = ViewPropertyContainerBean.class, configClass = ViewPropertyContainerBeanViewConfig.class) public class ViewPropertyContainerBeanView { private long a; private String b; private ViewPropertyBeanWithoutParent view; private ViewPropertyBeanWithoutParent[] viewArray; private List<ViewPropertyBeanWithoutParent> viewList; private Set<ViewPropertyBeanWithoutParent> viewSet; private Map<String, ViewPropertyBeanWithoutParent> viewMap; private List<Map<String, ViewPropertyBeanWithoutParent>> viewMapList; private Map<String, List<ViewPropertyBeanWithoutParent>> viewListMap; private Map<String, List<Map<Integer, Stack<ViewPropertyBeanWithoutParent>>>> viewStackMapListMap; private Map<String, List<Map<Integer, Stack<ViewPropertyBeanWithoutParent>>>>[][][] viewStackMapListMapArrayArrayArray; public ViewPropertyContainerBeanView() { } public ViewPropertyContainerBeanView( long a, String b, ViewPropertyBeanWithoutParent view, ViewPropertyBeanWithoutParent[] viewArray, List<ViewPropertyBeanWithoutParent> viewList, Set<ViewPropertyBeanWithoutParent> viewSet, Map<String, ViewPropertyBeanWithoutParent> viewMap, List<Map<String, ViewPropertyBeanWithoutParent>> viewMapList, Map<String, List<ViewPropertyBeanWithoutParent>> viewListMap, Map<String, List<Map<Integer, Stack<ViewPropertyBeanWithoutParent>>>> viewStackMapListMap, Map<String, List<Map<Integer, Stack<ViewPropertyBeanWithoutParent>>>>[][][] viewStackMapListMapArrayArrayArray ) { this.a = a; this.b = b; this.view = view; this.viewArray = viewArray; this.viewList = viewList; this.viewSet = viewSet; this.viewMap = viewMap; this.viewMapList = viewMapList; this.viewListMap = viewListMap; this.viewStackMapListMap = viewStackMapListMap; this.viewStackMapListMapArrayArrayArray = viewStackMapListMapArrayArrayArray; } public ViewPropertyContainerBeanView(ViewPropertyContainerBeanView source) { this.a = source.a; this.b = source.b; this.view = source.view; this.viewArray = source.viewArray; this.viewList = source.viewList; this.viewSet = source.viewSet; this.viewMap = source.viewMap; this.viewMapList = source.viewMapList; this.viewListMap = source.viewListMap; this.viewStackMapListMap = source.viewStackMapListMap; this.viewStackMapListMapArrayArrayArray = source.viewStackMapListMapArrayArrayArray; } public ViewPropertyContainerBeanView(ViewPropertyContainerBean source) { if (source == null) { throw new NullPointerException("The input source argument of the read constructor of class io.github.vipcxj.beanknife.cases.beans.ViewPropertyContainerBeanView should not be null."); } ViewPropertyBeanWithoutParent p0 = ViewPropertyBeanWithoutParent.read(source.getView()); ViewPropertyBeanWithoutParent[] p1 = new ViewPropertyBeanWithoutParent[source.getViewArray().length]; for (int i0 = 0; i0 < source.getViewArray().length; ++i0) { ViewPropertyBean el0 = source.getViewArray()[i0]; ViewPropertyBeanWithoutParent result0 = ViewPropertyBeanWithoutParent.read(el0); p1[i0] = result0; } List<ViewPropertyBeanWithoutParent> p2 = new ArrayList<>(); for (ViewPropertyBean el0 : source.getViewList()) { ViewPropertyBeanWithoutParent result0 = ViewPropertyBeanWithoutParent.read(el0); p2.add(result0); } Set<ViewPropertyBeanWithoutParent> p3 = new HashSet<>(); for (ViewPropertyBean el0 : source.getViewSet()) { ViewPropertyBeanWithoutParent result0 = ViewPropertyBeanWithoutParent.read(el0); p3.add(result0); } Map<String, ViewPropertyBeanWithoutParent> p4 = new HashMap<>(); for (Map.Entry<String, ViewPropertyBean> el0 : source.getViewMap().entrySet()) { ViewPropertyBeanWithoutParent result0 = ViewPropertyBeanWithoutParent.read(el0.getValue()); p4.put(el0.getKey(), result0); } List<Map<String, ViewPropertyBeanWithoutParent>> p5 = new ArrayList<>(); for (Map<String, ViewPropertyBean> el0 : source.getViewMapList()) { Map<String, ViewPropertyBeanWithoutParent> result0 = new HashMap<>(); for (Map.Entry<String, ViewPropertyBean> el1 : el0.entrySet()) { ViewPropertyBeanWithoutParent result1 = ViewPropertyBeanWithoutParent.read(el1.getValue()); result0.put(el1.getKey(), result1); } p5.add(result0); } Map<String, List<ViewPropertyBeanWithoutParent>> p6 = new HashMap<>(); for (Map.Entry<String, List<ViewPropertyBean>> el0 : source.getViewListMap().entrySet()) { List<ViewPropertyBeanWithoutParent> result0 = new ArrayList<>(); for (ViewPropertyBean el1 : el0.getValue()) { ViewPropertyBeanWithoutParent result1 = ViewPropertyBeanWithoutParent.read(el1); result0.add(result1); } p6.put(el0.getKey(), result0); } Map<String, List<Map<Integer, Stack<ViewPropertyBeanWithoutParent>>>> p7 = new HashMap<>(); for (Map.Entry<String, List<Map<Integer, Stack<ViewPropertyBean>>>> el0 : source.getViewStackMapListMap().entrySet()) { List<Map<Integer, Stack<ViewPropertyBeanWithoutParent>>> result0 = new ArrayList<>(); for (Map<Integer, Stack<ViewPropertyBean>> el1 : el0.getValue()) { Map<Integer, Stack<ViewPropertyBeanWithoutParent>> result1 = new HashMap<>(); for (Map.Entry<Integer, Stack<ViewPropertyBean>> el2 : el1.entrySet()) { Stack<ViewPropertyBeanWithoutParent> result2 = new Stack<>(); for (ViewPropertyBean el3 : el2.getValue()) { ViewPropertyBeanWithoutParent result3 = ViewPropertyBeanWithoutParent.read(el3); result2.add(result3); } result1.put(el2.getKey(), result2); } result0.add(result1); } p7.put(el0.getKey(), result0); } Map<String, List<Map<Integer, Stack<ViewPropertyBeanWithoutParent>>>>[][][] p8 = new Map[source.getViewStackMapListMapArrayArrayArray().length][][]; for (int i0 = 0; i0 < source.getViewStackMapListMapArrayArrayArray().length; ++i0) { Map<String, List<Map<Integer, Stack<ViewPropertyBean>>>>[][] el0 = source.getViewStackMapListMapArrayArrayArray()[i0]; Map<String, List<Map<Integer, Stack<ViewPropertyBeanWithoutParent>>>>[][] result0 = new Map[el0.length][]; for (int i1 = 0; i1 < el0.length; ++i1) { Map<String, List<Map<Integer, Stack<ViewPropertyBean>>>>[] el1 = el0[i1]; Map<String, List<Map<Integer, Stack<ViewPropertyBeanWithoutParent>>>>[] result1 = new Map[el1.length]; for (int i2 = 0; i2 < el1.length; ++i2) { Map<String, List<Map<Integer, Stack<ViewPropertyBean>>>> el2 = el1[i2]; Map<String, List<Map<Integer, Stack<ViewPropertyBeanWithoutParent>>>> result2 = new HashMap<>(); for (Map.Entry<String, List<Map<Integer, Stack<ViewPropertyBean>>>> el3 : el2.entrySet()) { List<Map<Integer, Stack<ViewPropertyBeanWithoutParent>>> result3 = new ArrayList<>(); for (Map<Integer, Stack<ViewPropertyBean>> el4 : el3.getValue()) { Map<Integer, Stack<ViewPropertyBeanWithoutParent>> result4 = new HashMap<>(); for (Map.Entry<Integer, Stack<ViewPropertyBean>> el5 : el4.entrySet()) { Stack<ViewPropertyBeanWithoutParent> result5 = new Stack<>(); for (ViewPropertyBean el6 : el5.getValue()) { ViewPropertyBeanWithoutParent result6 = ViewPropertyBeanWithoutParent.read(el6); result5.add(result6); } result4.put(el5.getKey(), result5); } result3.add(result4); } result2.put(el3.getKey(), result3); } result1[i2] = result2; } result0[i1] = result1; } p8[i0] = result0; } this.a = source.getA(); this.b = source.getB(); this.view = p0; this.viewArray = p1; this.viewList = p2; this.viewSet = p3; this.viewMap = p4; this.viewMapList = p5; this.viewListMap = p6; this.viewStackMapListMap = p7; this.viewStackMapListMapArrayArrayArray = p8; } public static ViewPropertyContainerBeanView read(ViewPropertyContainerBean source) { if (source == null) { return null; } return new ViewPropertyContainerBeanView(source); } public static ViewPropertyContainerBeanView[] read(ViewPropertyContainerBean[] sources) { if (sources == null) { return null; } ViewPropertyContainerBeanView[] results = new ViewPropertyContainerBeanView[sources.length]; for (int i = 0; i < sources.length; ++i) { results[i] = read(sources[i]); } return results; } public static List<ViewPropertyContainerBeanView> read(List<ViewPropertyContainerBean> sources) { if (sources == null) { return null; } List<ViewPropertyContainerBeanView> results = new ArrayList<>(); for (ViewPropertyContainerBean source : sources) { results.add(read(source)); } return results; } public static Set<ViewPropertyContainerBeanView> read(Set<ViewPropertyContainerBean> sources) { if (sources == null) { return null; } Set<ViewPropertyContainerBeanView> results = new HashSet<>(); for (ViewPropertyContainerBean source : sources) { results.add(read(source)); } return results; } public static Stack<ViewPropertyContainerBeanView> read(Stack<ViewPropertyContainerBean> sources) { if (sources == null) { return null; } Stack<ViewPropertyContainerBeanView> results = new Stack<>(); for (ViewPropertyContainerBean source : sources) { results.add(read(source)); } return results; } public static <K> Map<K, ViewPropertyContainerBeanView> read(Map<K, ViewPropertyContainerBean> sources) { if (sources == null) { return null; } Map<K, ViewPropertyContainerBeanView> results = new HashMap<>(); for (Map.Entry<K, ViewPropertyContainerBean> source : sources.entrySet()) { results.put(source.getKey(), read(source.getValue())); } return results; } public long getA() { return this.a; } public String getB() { return this.b; } public ViewPropertyBeanWithoutParent getView() { return this.view; } public ViewPropertyBeanWithoutParent[] getViewArray() { return this.viewArray; } public List<ViewPropertyBeanWithoutParent> getViewList() { return this.viewList; } public Set<ViewPropertyBeanWithoutParent> getViewSet() { return this.viewSet; } public Map<String, ViewPropertyBeanWithoutParent> getViewMap() { return this.viewMap; } public List<Map<String, ViewPropertyBeanWithoutParent>> getViewMapList() { return this.viewMapList; } public Map<String, List<ViewPropertyBeanWithoutParent>> getViewListMap() { return this.viewListMap; } public Map<String, List<Map<Integer, Stack<ViewPropertyBeanWithoutParent>>>> getViewStackMapListMap() { return this.viewStackMapListMap; } public Map<String, List<Map<Integer, Stack<ViewPropertyBeanWithoutParent>>>>[][][] getViewStackMapListMapArrayArrayArray() { return this.viewStackMapListMapArrayArrayArray; } } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/converters/NullLongAsZeroConverter.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.converters; import io.github.vipcxj.beanknife.runtime.PropertyConverter; public class NullLongAsZeroConverter implements PropertyConverter<Long, Long> { @Override public Long convert(Long value) { return value != null ? value : 0L; } @Override public Long convertBack(Long value) { return value; } } <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/beans/WriteableBeanViewConfigure.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.*; @ViewOf(WriteableBean.class) @ViewWriteBackMethod(Access.PUBLIC) @ViewCreateAndWriteBackMethod(Access.PROTECTED) @ViewWriteBackExclude(WriteableBeanMeta.f) public class WriteableBeanViewConfigure extends IncludeAllBaseConfigure { } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/models/AObjectMeta.java<|end_filename|> package io.github.vipcxj.beanknife.cases.models; import io.github.vipcxj.beanknife.cases.beans.AObjectMetaConfig; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedMeta; @GeneratedMeta(targetClass = AObject.class, configClass = AObjectMetaConfig.class) public class AObjectMeta { public static final String a = "a"; public static final String b = "b"; public static final String c = "c"; public static final String d = "d"; } <|start_filename|>beanknife-spring/src/main/java/io/github/vipcxj/beanknife/spring/SpringBeanProvider.java<|end_filename|> package io.github.vipcxj.beanknife.spring; import io.github.vipcxj.beanknife.runtime.spi.BeanProvider; import io.github.vipcxj.beanknife.runtime.utils.BeanUsage; public class SpringBeanProvider implements BeanProvider { public int getPriority() { return -100; } public boolean support(Class<?> type, BeanUsage usage) { return true; } public <T> T get(Class<T> type, BeanUsage usage, Object requester) { return BeanUtils.getBean(type); } } <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/beans/Leaf21BeanViewConfigure.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; import io.github.vipcxj.beanknife.runtime.annotations.ViewPropertiesInclude; @ViewOf(value = Leaf21Bean.class, includes = Leaf21BeanMeta.e) @ViewPropertiesInclude(Leaf21BeanMeta.c) public class Leaf21BeanViewConfigure extends Parent2ViewConfigure { } <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/beans/ViewPropertyContainerBeanViewConfig.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.OverrideViewProperty; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; import io.github.vipcxj.beanknife.runtime.annotations.ViewPropertiesIncludePattern; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; @ViewOf(value = ViewPropertyContainerBean.class, includePattern = ".*") @ViewPropertiesIncludePattern(".*") public class ViewPropertyContainerBeanViewConfig { @OverrideViewProperty(ViewPropertyContainerBeanMeta.view) private ViewPropertyBeanWithoutParent view; @OverrideViewProperty(ViewPropertyContainerBeanMeta.viewArray) private ViewPropertyBeanWithoutParent[] viewArray; @OverrideViewProperty(ViewPropertyContainerBeanMeta.viewList) private List<ViewPropertyBeanWithoutParent> viewList; @OverrideViewProperty(ViewPropertyContainerBeanMeta.viewSet) private Set<ViewPropertyBeanWithoutParent> viewSet; @OverrideViewProperty(ViewPropertyContainerBeanMeta.viewMap) private Map<String, ViewPropertyBeanWithoutParent> viewMap; @OverrideViewProperty(ViewPropertyContainerBeanMeta.viewMapList) private List<Map<String, ViewPropertyBeanWithoutParent>> viewMapList; @OverrideViewProperty(ViewPropertyContainerBeanMeta.viewListMap) private Map<String, List<ViewPropertyBeanWithoutParent>> viewListMap; @OverrideViewProperty(ViewPropertyContainerBeanMeta.viewStackMapListMap) private Map<String, List<Map<Integer, Stack<ViewPropertyBeanWithoutParent>>>> viewStackMapListMap; @OverrideViewProperty(ViewPropertyContainerBeanMeta.viewStackMapListMapArrayArrayArray) private Map<String, List<Map<Integer, Stack<ViewPropertyBeanWithoutParent>>>>[][][] viewStackMapListMapArrayArrayArray; } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/annotations/InjectSelf.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Used in dynamic method property. Inject the 'this' object to the method parameter. * The generated class may not exist yet, however, referencing it in the config class is legal. * Although the compiler may complain. Ignored it and after compiled, all will be ok. * Or compile first, after the class generated, the compiler will stop complain. * * @see Dynamic * @see NewViewProperty * @see OverrideViewProperty */ @Target(ElementType.PARAMETER) @Retention(RetentionPolicy.SOURCE) public @interface InjectSelf { } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/annotations/RemoveViewProperties.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.annotations; import java.lang.annotation.*; @Target({ElementType.TYPE}) @Retention(RetentionPolicy.SOURCE) @Inherited public @interface RemoveViewProperties { RemoveViewProperty[] value() default {}; } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/annotations/ValueAnnotation1.java<|end_filename|> package io.github.vipcxj.beanknife.cases.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Target; @Target(ElementType.TYPE) public @interface ValueAnnotation1 { Class<?>[] type() default ValueAnnotation1.class; ValueAnnotation2 annotation() default @ValueAnnotation2; ValueAnnotation2[] annotations() default {}; } <|start_filename|>beanknife-jpa/src/main/java/io/github/vipcxj/beanknife/jpa/ArgData.java<|end_filename|> package io.github.vipcxj.beanknife.jpa; import java.util.List; public class ArgData { private boolean extra; private Object varKey; private List<String> path; private ArgData(boolean extra, Object varKey, List<String> path) { this.extra = extra; this.varKey = varKey; this.path = path; } public static ArgData extraVar(Object key) { return new ArgData(true, key, null); } public static ArgData pathVar(List<String> path) { return new ArgData(false, null, path); } public boolean isExtra() { return extra; } public Object getVarKey() { return varKey; } public List<String> getPath() { return path; } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/IsPropertyBeanMeta.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedMeta; @GeneratedMeta(targetClass = IsPropertyBean.class, configClass = IsPropertyBean.class) public class IsPropertyBeanMeta { public static final String me = "me"; public static final String isTest = "isTest"; public static final String test = "test"; } <|start_filename|>beanknife-jpa-examples/src/main/java/io/github/vipcxj/beanknfie/jpa/examples/models/Employee.java<|end_filename|> package io.github.vipcxj.beanknfie.jpa.examples.models; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.*; import java.util.Date; @Entity @Getter @Setter @NoArgsConstructor @AllArgsConstructor public class Employee { @Id private String number; private String name; private String sex; private String nation; @Temporal(TemporalType.DATE) private Date birthDay; @Temporal(TemporalType.DATE) private Date enrollmentDay; @ManyToOne private Department department; @ManyToOne private Company company; } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/annotations/NullNumberAsZero.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.annotations; import io.github.vipcxj.beanknife.runtime.converters.*; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * a built-in converter to convert short, long, integer, float, double, byte, BigInteger or BigDecimal value to zero when it is null. */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.SOURCE) @UsePropertyConverter(NullBigDecimalAsZeroConverter.class) @UsePropertyConverter(NullBigIntegerAsZeroConverter.class) @UsePropertyConverter(NullByteAsZeroConverter.class) @UsePropertyConverter(NullDoubleAsZeroConverter.class) @UsePropertyConverter(NullFloatAsZeroConverter.class) @UsePropertyConverter(NullIntegerAsZeroConverter.class) @UsePropertyConverter(NullLongAsZeroConverter.class) @UsePropertyConverter(NullShortAsZeroConverter.class) public @interface NullNumberAsZero { } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/NestedGenericBean$DynamicChildBeanView.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedView; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; @GeneratedView(targetClass = NestedGenericBean.DynamicChildBean.class, configClass = NestedGenericBean.DynamicChildBean.class) public class NestedGenericBean$DynamicChildBeanView<T1 extends CharSequence & Set<? extends Character>, T2 extends List<? extends Set<? super String>>, T3> { private T1 a; private T2 b; private T3 c; public NestedGenericBean$DynamicChildBeanView() { } public NestedGenericBean$DynamicChildBeanView( T1 a, T2 b, T3 c ) { this.a = a; this.b = b; this.c = c; } public NestedGenericBean$DynamicChildBeanView(NestedGenericBean$DynamicChildBeanView<T1, T2, T3> source) { this.a = source.a; this.b = source.b; this.c = source.c; } public NestedGenericBean$DynamicChildBeanView(NestedGenericBean<T1, T2>.DynamicChildBean<T3> source) { if (source == null) { throw new NullPointerException("The input source argument of the read constructor of class io.github.vipcxj.beanknife.cases.beans.NestedGenericBean$DynamicChildBeanView should not be null."); } this.a = source.getA(); this.b = source.getB(); this.c = source.getC(); } public static <T1 extends CharSequence & Set<? extends Character>, T2 extends List<? extends Set<? super String>>, T3> NestedGenericBean$DynamicChildBeanView<T1, T2, T3> read(NestedGenericBean<T1, T2>.DynamicChildBean<T3> source) { if (source == null) { return null; } return new NestedGenericBean$DynamicChildBeanView<>(source); } public static <T1 extends CharSequence & Set<? extends Character>, T2 extends List<? extends Set<? super String>>, T3> NestedGenericBean$DynamicChildBeanView<T1, T2, T3>[] read(NestedGenericBean<T1, T2>.DynamicChildBean<T3>[] sources) { if (sources == null) { return null; } NestedGenericBean$DynamicChildBeanView<T1, T2, T3>[] results = new NestedGenericBean$DynamicChildBeanView[sources.length]; for (int i = 0; i < sources.length; ++i) { results[i] = read(sources[i]); } return results; } public static <T1 extends CharSequence & Set<? extends Character>, T2 extends List<? extends Set<? super String>>, T3> List<NestedGenericBean$DynamicChildBeanView<T1, T2, T3>> read(List<NestedGenericBean<T1, T2>.DynamicChildBean<T3>> sources) { if (sources == null) { return null; } List<NestedGenericBean$DynamicChildBeanView<T1, T2, T3>> results = new ArrayList<>(); for (NestedGenericBean<T1, T2>.DynamicChildBean<T3> source : sources) { results.add(read(source)); } return results; } public static <T1 extends CharSequence & Set<? extends Character>, T2 extends List<? extends Set<? super String>>, T3> Set<NestedGenericBean$DynamicChildBeanView<T1, T2, T3>> read(Set<NestedGenericBean<T1, T2>.DynamicChildBean<T3>> sources) { if (sources == null) { return null; } Set<NestedGenericBean$DynamicChildBeanView<T1, T2, T3>> results = new HashSet<>(); for (NestedGenericBean<T1, T2>.DynamicChildBean<T3> source : sources) { results.add(read(source)); } return results; } public static <T1 extends CharSequence & Set<? extends Character>, T2 extends List<? extends Set<? super String>>, T3> Stack<NestedGenericBean$DynamicChildBeanView<T1, T2, T3>> read(Stack<NestedGenericBean<T1, T2>.DynamicChildBean<T3>> sources) { if (sources == null) { return null; } Stack<NestedGenericBean$DynamicChildBeanView<T1, T2, T3>> results = new Stack<>(); for (NestedGenericBean<T1, T2>.DynamicChildBean<T3> source : sources) { results.add(read(source)); } return results; } public static <K, T1 extends CharSequence & Set<? extends Character>, T2 extends List<? extends Set<? super String>>, T3> Map<K, NestedGenericBean$DynamicChildBeanView<T1, T2, T3>> read(Map<K, NestedGenericBean<T1, T2>.DynamicChildBean<T3>> sources) { if (sources == null) { return null; } Map<K, NestedGenericBean$DynamicChildBeanView<T1, T2, T3>> results = new HashMap<>(); for (Map.Entry<K, NestedGenericBean<T1, T2>.DynamicChildBean<T3>> source : sources.entrySet()) { results.put(source.getKey(), read(source.getValue())); } return results; } public T1 getA() { return this.a; } public T2 getB() { return this.b; } public T3 getC() { return this.c; } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/ViewPropertyContainerBeanMeta.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedMeta; @GeneratedMeta( targetClass = ViewPropertyContainerBean.class, configClass = ViewPropertyContainerBean.class, proxies = { ViewPropertyContainerBeanViewConfig.class } ) public class ViewPropertyContainerBeanMeta { public static final String a = "a"; public static final String b = "b"; public static final String view = "view"; public static final String viewArray = "viewArray"; public static final String viewList = "viewList"; public static final String viewSet = "viewSet"; public static final String viewMap = "viewMap"; public static final String viewMapList = "viewMapList"; public static final String viewListMap = "viewListMap"; public static final String viewStackMapListMap = "viewStackMapListMap"; public static final String viewStackMapListMapArrayArrayArray = "viewStackMapListMapArrayArrayArray"; public static class Views { public static final String io_github_vipcxj_beanknife_cases_beans_ViewPropertyContainerBeanView = "io.github.vipcxj.beanknife.cases.beans.ViewPropertyContainerBeanView"; } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/ConverterBeanConfig.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.NullNumberAsZero; import io.github.vipcxj.beanknife.runtime.annotations.OverrideViewProperty; import io.github.vipcxj.beanknife.runtime.annotations.ViewMeta; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; @ViewMeta(of = ConverterBean.class) @ViewOf(value = ConverterBean.class, includes = {ConverterBeanMeta.a, ConverterBeanMeta.b}) public class ConverterBeanConfig { @OverrideViewProperty(ConverterBeanMeta.a) @NullNumberAsZero private long a; @OverrideViewProperty(ConverterBeanMeta.b) @NullNumberAsZero private Number b; } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/annotations/ViewMetas.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.TYPE) @Retention(RetentionPolicy.SOURCE) public @interface ViewMetas { ViewMeta[] value() default {}; } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/NestedGenericBean$DynamicChildBeanMeta.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedMeta; @GeneratedMeta( targetClass = NestedGenericBean.DynamicChildBean.class, configClass = NestedGenericBean.DynamicChildBean.class, proxies = { NestedGenericBean.DynamicChildBean.class } ) public class NestedGenericBean$DynamicChildBeanMeta { public static final String a = "a"; public static final String b = "b"; public static final String c = "c"; public static class Views { public static final String io_github_vipcxj_beanknife_cases_beans_NestedGenericBean$DynamicChildBeanView = "io.github.vipcxj.beanknife.cases.beans.NestedGenericBean$DynamicChildBeanView"; } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/MetaAndViewOfOnDiffBean1View.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedView; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; @GeneratedView(targetClass = MetaAndViewOfOnDiffBean1.class, configClass = MetaAndViewOfOnDiffBean1ViewConfig.class) public class MetaAndViewOfOnDiffBean1View { private int pb; public MetaAndViewOfOnDiffBean1View() { } public MetaAndViewOfOnDiffBean1View( int pb ) { this.pb = pb; } public MetaAndViewOfOnDiffBean1View(MetaAndViewOfOnDiffBean1View source) { this.pb = source.pb; } public MetaAndViewOfOnDiffBean1View(MetaAndViewOfOnDiffBean1 source) { if (source == null) { throw new NullPointerException("The input source argument of the read constructor of class io.github.vipcxj.beanknife.cases.beans.MetaAndViewOfOnDiffBean1View should not be null."); } this.pb = source.getPb(); } public static MetaAndViewOfOnDiffBean1View read(MetaAndViewOfOnDiffBean1 source) { if (source == null) { return null; } return new MetaAndViewOfOnDiffBean1View(source); } public static MetaAndViewOfOnDiffBean1View[] read(MetaAndViewOfOnDiffBean1[] sources) { if (sources == null) { return null; } MetaAndViewOfOnDiffBean1View[] results = new MetaAndViewOfOnDiffBean1View[sources.length]; for (int i = 0; i < sources.length; ++i) { results[i] = read(sources[i]); } return results; } public static List<MetaAndViewOfOnDiffBean1View> read(List<MetaAndViewOfOnDiffBean1> sources) { if (sources == null) { return null; } List<MetaAndViewOfOnDiffBean1View> results = new ArrayList<>(); for (MetaAndViewOfOnDiffBean1 source : sources) { results.add(read(source)); } return results; } public static Set<MetaAndViewOfOnDiffBean1View> read(Set<MetaAndViewOfOnDiffBean1> sources) { if (sources == null) { return null; } Set<MetaAndViewOfOnDiffBean1View> results = new HashSet<>(); for (MetaAndViewOfOnDiffBean1 source : sources) { results.add(read(source)); } return results; } public static Stack<MetaAndViewOfOnDiffBean1View> read(Stack<MetaAndViewOfOnDiffBean1> sources) { if (sources == null) { return null; } Stack<MetaAndViewOfOnDiffBean1View> results = new Stack<>(); for (MetaAndViewOfOnDiffBean1 source : sources) { results.add(read(source)); } return results; } public static <K> Map<K, MetaAndViewOfOnDiffBean1View> read(Map<K, MetaAndViewOfOnDiffBean1> sources) { if (sources == null) { return null; } Map<K, MetaAndViewOfOnDiffBean1View> results = new HashMap<>(); for (Map.Entry<K, MetaAndViewOfOnDiffBean1> source : sources.entrySet()) { results.put(source.getKey(), read(source.getValue())); } return results; } public int getPb() { return this.pb; } } <|start_filename|>beanknife-jpa/src/main/java/io/github/vipcxj/beanknife/jpa/JpaContext.java<|end_filename|> package io.github.vipcxj.beanknife.jpa; import io.github.vipcxj.beanknife.core.models.Property; import io.github.vipcxj.beanknife.core.models.Type; import io.github.vipcxj.beanknife.core.models.ViewContext; import io.github.vipcxj.beanknife.core.utils.ParamInfo; import io.github.vipcxj.beanknife.core.utils.Utils; import io.github.vipcxj.beanknife.core.utils.VarMapper; import org.apache.commons.text.StringEscapeUtils; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.TypeElement; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import java.io.PrintWriter; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class JpaContext { public static final String TYPE_ENTITY = "javax.persistence.Entity"; public static final String TYPE_EMBEDDABLE = "javax.persistence.Embeddable"; public static final String TYPE_CRITERIA_BUILDER = "javax.persistence.criteria.CriteriaBuilder"; public static final String SIMPLE_TYPE_CRITERIA_BUILDER = "CriteriaBuilder"; public static final String TYPE_SELECTION = "javax.persistence.criteria.Selection"; public static final String SIMPLE_TYPE_SELECTION = "Selection"; public static final String TYPE_FROM = "javax.persistence.criteria.From"; public static final String TYPE_REFLECT_UTILS = "io.github.vipcxj.beanknife.jpa.runtime.utils.ReflectUtils"; public static final String SIMPLE_TYPE_REFLECT_UTILS = "ReflectUtils"; public static final String SIMPLE_TYPE_FROM = "From"; private static final String INIT_ARG_SOURCE = "source"; private static final String PREVENT_CONFLICT_ARG_KEY = "prevent conflict arg"; public static final String SOURCE_ARG_KEY = "source arg"; private static final String TYPE_ADD_JPA_SUPPORT = "io.github.vipcxj.beanknife.jpa.runtime.annotations.AddJpaSupport"; private final ViewContext viewContext; private boolean enabled; private boolean fixConstructor; private boolean provideSource; private boolean canUseReader; private long argsNum; private String preventConflictArgVar = "preventConflictArg"; private final VarMapper constructorVarMapper; private VarMapper constructorArgsVarMapper; private final Map<String, ArgData> constructorArgDataMap; private final VarMapper selectionMethodVarMapper; private List<PropertyData> propertyDataList; public JpaContext(ViewContext viewContext) { this.viewContext = viewContext; this.constructorVarMapper = new VarMapper(); this.constructorArgDataMap = new HashMap<>(); this.selectionMethodVarMapper = new VarMapper("cb", "from"); init(); } private void init() { Types typeUtils = viewContext.getProcessingEnv().getTypeUtils(); TypeElement targetElement = viewContext.getViewOf().getTargetElement(); TypeElement configElement = viewContext.getViewOf().getConfigElement(); Elements elementUtils = viewContext.getProcessingEnv().getElementUtils(); List<AnnotationMirror> annotations = Utils.getAnnotationsOn(elementUtils, configElement, TYPE_ADD_JPA_SUPPORT, null, true, true); if (!annotations.isEmpty()) { AnnotationMirror addJpaSupport = annotations.get(annotations.size() - 1); List<TypeMirror> targets = Utils.getTypeArrayAnnotationValue(addJpaSupport, "value"); if (targets == null) { if (Utils.getAnnotationDirectOn(targetElement, TYPE_ENTITY) != null) { enabled = true; } } else { if (targets.stream().anyMatch(target -> typeUtils.isSameType(target, targetElement.asType()))) { enabled = true; } } if (!enabled) { List<TypeMirror> extraTargets = Utils.getTypeArrayAnnotationValue(addJpaSupport, "extraTargets"); if (extraTargets != null && extraTargets.stream().anyMatch(target -> typeUtils.isSameType(target, targetElement.asType()))) { enabled = true; } } } if (enabled) { viewContext.importVariable(TYPE_SELECTION, SIMPLE_TYPE_SELECTION); viewContext.importVariable(TYPE_CRITERIA_BUILDER, SIMPLE_TYPE_CRITERIA_BUILDER); viewContext.importVariable(TYPE_FROM, SIMPLE_TYPE_FROM); propertyDataList = PropertyData.collectData(this); if (provideSource) { newConstructorVar(SOURCE_ARG_KEY, INIT_ARG_SOURCE, ArgData.extraVar(SOURCE_ARG_KEY)); } canUseReader = viewContext.canSeeReadConstructor(viewContext.getPackageName()) && provideSource && propertyDataList .stream() .noneMatch(data -> data.isIgnore() && data.getPropertyType() != PropertyType.BASEABLE && data.getPropertyType() != PropertyType.EXTRA); // 最终properties里就三种Property, baseProperty,viewProperty,extraProperty checkConstructor(); } } public static boolean unSupportType(Type type) { return type.getQualifiedName().equals("java.util.List") || type.getQualifiedName().equals("java.util.Set") || type.getQualifiedName().equals("java.util.Collection") || type.getQualifiedName().equals("java.util.Map") || type.isArray(); } private boolean isObjectDirectWithAnnotation(Type type, String annotationName) { if (!type.isObject()) { return false; } Elements elementUtils = viewContext.getProcessingEnv().getElementUtils(); TypeElement typeElement = elementUtils.getTypeElement(type.getQualifiedName()); AnnotationMirror entityAnnotation = Utils.getAnnotationDirectOn(typeElement, annotationName); return entityAnnotation != null; } public boolean isEntity(Type type) { return isObjectDirectWithAnnotation(type, TYPE_ENTITY); } public boolean isEmbeddable(Type type) { return isObjectDirectWithAnnotation(type, TYPE_EMBEDDABLE); } private void checkConstructor() { if (!provideSource) { long fieldsCount = viewContext.getProperties().size() - viewContext.getProperties().stream().filter(Property::isDynamic).count(); argsNum = constructorVarMapper.getKeys().size(); List<Type> types = constructorVarMapper.getKeys() .stream() .map(key -> { if (key instanceof Property) { return ((Property) key).getType(); } else if (key instanceof ParamInfo) { return Type.extract(viewContext, ((ParamInfo) key).getVar()); } else if (key.equals(SOURCE_ARG_KEY)) { return viewContext.getTargetType(); } else { throw new IllegalArgumentException("This is impossible!"); } }).collect(Collectors.toList()); fixConstructor = true; if (argsNum == fieldsCount) { int i = 0; for (Property property : viewContext.getProperties()) { if (!property.isDynamic()) { Type type = types.get(i++); if (!type.sameType(property.getType(), true)) { fixConstructor = false; break; } } } } else { fixConstructor = false; } } else { fixConstructor = true; } if (fixConstructor) { argsNum += 1; this.preventConflictArgVar = newConstructorVar(PREVENT_CONFLICT_ARG_KEY, preventConflictArgVar, ArgData.extraVar(PREVENT_CONFLICT_ARG_KEY)); } constructorArgsVarMapper = new VarMapper(constructorVarMapper); } public VarMapper getConstructorVarMapper() { return constructorVarMapper; } public VarMapper getSelectionMethodVarMapper() { return selectionMethodVarMapper; } public void importReflect() { getViewContext().importVariable(TYPE_REFLECT_UTILS, SIMPLE_TYPE_REFLECT_UTILS); } public boolean isEnabled() { return enabled; } public String getPreventConflictArgVar() { return preventConflictArgVar; } public boolean isProvideSource() { return provideSource; } public boolean isCanUseReader() { return canUseReader; } public void markProvideSource() { this.provideSource = true; this.cleanBasePropertyArg(); } public boolean isFixConstructor() { return fixConstructor; } public long getArgsNum() { return argsNum; } public ViewContext getViewContext() { return viewContext; } public void cleanBasePropertyArg() { for (Property baseProperty : viewContext.getBaseProperties()) { constructorVarMapper.removeVar(baseProperty); if (constructorArgsVarMapper != null) { constructorArgsVarMapper.removeVar(baseProperty); } } } public String newConstructorVar(Object key, String varBaseName, ArgData argData) { String var = constructorVarMapper.getVar(key, varBaseName); constructorArgDataMap.put(var, argData); return var; } public void startAssignVar(PrintWriter writer, Type type, String var, String indent, int indentNum) { Utils.printIndent(writer, indent, indentNum); if (type != null) { type.printType(writer, getViewContext(), true, false); writer.print(" "); } writer.print(var); writer.print(" = "); } private Type extractKeyType(Object key) { if (key instanceof Property) { Property property = (Property) key; return property.getType(); } else if (key instanceof ParamInfo) { ParamInfo paramInfo = (ParamInfo) key; return Type.extract(viewContext, paramInfo.getVar()); } else if (key.equals(SOURCE_ARG_KEY)) { return viewContext.getTargetType(); } else if (key.equals(PREVENT_CONFLICT_ARG_KEY)) { return Type.create(viewContext, "", "int", 0, false); } else if (key instanceof String){ TypeElement typeElement = viewContext.getProcessingEnv().getElementUtils().getTypeElement((String) key); return Type.extract(viewContext, typeElement); } else { return null; } } public void printKeyVar(PrintWriter w, VarMapper varMapper, Object key, boolean wrapSelection) { Type type = extractKeyType(key); if (type == null) { type = Type.extract(viewContext, Object.class); } if (wrapSelection) { printSelectionType(w, type); } else { type.printType(w, viewContext, true, false); } w.print(" "); w.print(varMapper.getVar(key)); } public void printConstructor(PrintWriter writer, String indent, int indentNum) { boolean breakLine = constructorArgsVarMapper.getKeys().size() > 5; Utils.printIndent(writer, indent, indentNum); writer.print("public "); writer.print(viewContext.getGenType().getSimpleName()); writer.print(" ("); boolean start = true; for (Object key : constructorArgsVarMapper.getKeys()) { start = Utils.appendMethodArg(writer, w -> printKeyVar(w, constructorArgsVarMapper, key, false), start, breakLine, indent, indentNum + 1); } if (breakLine) { writer.println(); Utils.printIndent(writer, indent, indentNum); } writer.println(") {"); for (PropertyData propertyData : propertyDataList) { propertyData.prepareConstructor(writer, indent, indentNum + 1); } int i = 0; for (Property property : viewContext.getProperties()) { if (!property.isDynamic()) { int pos = Helper.findViewPropertyData(propertyDataList, property, i); PropertyData propertyData = pos != -1 ? propertyDataList.get(i++) : null; if (propertyData != null) { startAssignVar(writer, null, "this." + viewContext.getMappedFieldName(property), indent, indentNum + 1); propertyData.printAssignmentInConstructor(writer, indent, indentNum + 1); writer.println(";"); } } } Utils.printIndent(writer, indent, indentNum); writer.println("}"); writer.println(); } private void printSelectionType(PrintWriter writer, Type type) { if (viewContext.hasImport(JpaContext.TYPE_SELECTION)) { writer.print(JpaContext.SIMPLE_TYPE_SELECTION); } else { writer.print(JpaContext.TYPE_SELECTION); } writer.print("<"); type.printType(writer, viewContext, true, false); writer.print(">"); } public void printSelectionMethod(PrintWriter writer, String indent, int indentNum) { Utils.printIndent(writer, indent, indentNum); writer.print("public static <T> "); printSelectionType(writer, viewContext.getGenType()); writer.print(" toJpaSelection("); boolean breakLine = selectionMethodVarMapper.getKeys().size() > 5; Utils.appendMethodArg(writer, w -> { w.print(viewContext.getImportedName(JpaContext.TYPE_CRITERIA_BUILDER, SIMPLE_TYPE_CRITERIA_BUILDER)); w.print(" cb"); }, true, breakLine, indent, indentNum + 1); Utils.appendMethodArg(writer, w -> { w.print(viewContext.getImportedName(JpaContext.TYPE_FROM, SIMPLE_TYPE_FROM)); w.print("<T, "); viewContext.getTargetType().printType(w, viewContext, true, false); w.print("> from"); }, false, breakLine, indent, indentNum + 1); for (Object key : selectionMethodVarMapper.getKeys()) { Utils.appendMethodArg(writer, w -> printKeyVar(w, selectionMethodVarMapper, key, true), false, breakLine, indent, indentNum + 1); } if (breakLine) { writer.println(); Utils.printIndent(writer, indent, indentNum); } writer.println(") {"); Utils.printIndent(writer, indent, indentNum + 1); writer.print("return cb.construct("); Utils.appendMethodArg(writer, w -> { viewContext.getGenType().printType(w, viewContext, false, false); w.print(".class"); }, true, true, indent, indentNum + 2); // Utils.appendMethodArg(writer, w -> w.print("from"), false, true, indent, indentNum + 2); for (Object key : constructorArgsVarMapper.getKeys()) { String var = constructorArgsVarMapper.getVar(key); ArgData argData = constructorArgDataMap.get(var); String value; if (argData.isExtra()) { if (key.equals(SOURCE_ARG_KEY)) { value = "from"; } else if (key.equals(PREVENT_CONFLICT_ARG_KEY)) { value = "cb.literal(0)"; } else { value = var; } } else { List<String> path = argData.getPath(); value = "from" + path.stream().map(s -> ".get(\"" + StringEscapeUtils.escapeJava(s) + "\")").collect(Collectors.joining()); } Utils.appendMethodArg(writer, w -> w.print(value), false, true, indent, indentNum + 2); } writer.println(); Utils.printIndent(writer, indent, indentNum + 1); writer.println(");"); Utils.printIndent(writer, indent, indentNum); writer.println("}"); writer.println(); } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/ViewOfDirectOnBeanView.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedView; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; @GeneratedView(targetClass = ViewOfDirectOnBean.class, configClass = ViewOfDirectOnBean.class) public class ViewOfDirectOnBeanView { private long a; private String b; public ViewOfDirectOnBeanView() { } public ViewOfDirectOnBeanView( long a, String b ) { this.a = a; this.b = b; } public ViewOfDirectOnBeanView(ViewOfDirectOnBeanView source) { this.a = source.a; this.b = source.b; } public ViewOfDirectOnBeanView(ViewOfDirectOnBean source) { if (source == null) { throw new NullPointerException("The input source argument of the read constructor of class io.github.vipcxj.beanknife.cases.beans.ViewOfDirectOnBeanView should not be null."); } this.a = source.getA(); this.b = source.getB(); } public static ViewOfDirectOnBeanView read(ViewOfDirectOnBean source) { if (source == null) { return null; } return new ViewOfDirectOnBeanView(source); } public static ViewOfDirectOnBeanView[] read(ViewOfDirectOnBean[] sources) { if (sources == null) { return null; } ViewOfDirectOnBeanView[] results = new ViewOfDirectOnBeanView[sources.length]; for (int i = 0; i < sources.length; ++i) { results[i] = read(sources[i]); } return results; } public static List<ViewOfDirectOnBeanView> read(List<ViewOfDirectOnBean> sources) { if (sources == null) { return null; } List<ViewOfDirectOnBeanView> results = new ArrayList<>(); for (ViewOfDirectOnBean source : sources) { results.add(read(source)); } return results; } public static Set<ViewOfDirectOnBeanView> read(Set<ViewOfDirectOnBean> sources) { if (sources == null) { return null; } Set<ViewOfDirectOnBeanView> results = new HashSet<>(); for (ViewOfDirectOnBean source : sources) { results.add(read(source)); } return results; } public static Stack<ViewOfDirectOnBeanView> read(Stack<ViewOfDirectOnBean> sources) { if (sources == null) { return null; } Stack<ViewOfDirectOnBeanView> results = new Stack<>(); for (ViewOfDirectOnBean source : sources) { results.add(read(source)); } return results; } public static <K> Map<K, ViewOfDirectOnBeanView> read(Map<K, ViewOfDirectOnBean> sources) { if (sources == null) { return null; } Map<K, ViewOfDirectOnBeanView> results = new HashMap<>(); for (Map.Entry<K, ViewOfDirectOnBean> source : sources.entrySet()) { results.put(source.getKey(), read(source.getValue())); } return results; } public long getA() { return this.a; } public String getB() { return this.b; } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/MapPropertiesViewConfigure.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.MapViewProperty; import io.github.vipcxj.beanknife.runtime.annotations.NullNumberAsZero; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; import java.util.Date; @ViewOf(value = SimpleBean.class, genName = "MapPropertiesView") public class MapPropertiesViewConfigure extends IncludeAllBaseConfigure { @MapViewProperty(name = "aMap", map = SimpleBeanMeta.a) private String aMap; @MapViewProperty(name = "bMapWithConverter", map = SimpleBeanMeta.b) @NullNumberAsZero private int bMapWithConverter; @MapViewProperty(name = "cMapUseMethod", map = SimpleBeanMeta.c) public static Date cMapUseMethod(SimpleBean source) { return new Date(source.getC()); } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/Leaf21BeanDto.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedView; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; @GeneratedView(targetClass = Leaf21Bean.class, configClass = Leaf21BeanViewConfigure.class) public class Leaf21BeanDto implements Serializable { private static final long serialVersionUID = 0L; private List<? extends String> c; public Leaf21BeanDto() { } public Leaf21BeanDto( List<? extends String> c ) { this.c = c; } public Leaf21BeanDto(Leaf21BeanDto source) { this.c = source.c; } public static Leaf21BeanDto read(Leaf21Bean source) { if (source == null) { return null; } Leaf21BeanDto out = new Leaf21BeanDto(); out.c = source.getC(); return out; } public static Leaf21BeanDto[] read(Leaf21Bean[] sources) { if (sources == null) { return null; } Leaf21BeanDto[] results = new Leaf21BeanDto[sources.length]; for (int i = 0; i < sources.length; ++i) { results[i] = read(sources[i]); } return results; } public static List<Leaf21BeanDto> read(List<Leaf21Bean> sources) { if (sources == null) { return null; } List<Leaf21BeanDto> results = new ArrayList<>(); for (Leaf21Bean source : sources) { results.add(read(source)); } return results; } public static Set<Leaf21BeanDto> read(Set<Leaf21Bean> sources) { if (sources == null) { return null; } Set<Leaf21BeanDto> results = new HashSet<>(); for (Leaf21Bean source : sources) { results.add(read(source)); } return results; } public static Stack<Leaf21BeanDto> read(Stack<Leaf21Bean> sources) { if (sources == null) { return null; } Stack<Leaf21BeanDto> results = new Stack<>(); for (Leaf21Bean source : sources) { results.add(read(source)); } return results; } public static <K> Map<K, Leaf21BeanDto> read(Map<K, Leaf21Bean> sources) { if (sources == null) { return null; } Map<K, Leaf21BeanDto> results = new HashMap<>(); for (Map.Entry<K, Leaf21Bean> source : sources.entrySet()) { results.put(source.getKey(), read(source.getValue())); } return results; } public List<? extends String> getC() { return this.c; } } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/utils/Utils.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.utils; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedMeta; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedView; public class Utils { public static boolean isGeneratedView(Class<?> type) { GeneratedView annotation = type.getAnnotation(GeneratedView.class); return annotation != null; } public static boolean isGeneratedMeta(Class<?> type) { GeneratedMeta annotation = type.getAnnotation(GeneratedMeta.class); return annotation != null; } } <|start_filename|>beanknife-core-base/src/main/java/io/github/vipcxj/beanknife/core/models/ViewPropertyData.java<|end_filename|> package io.github.vipcxj.beanknife.core.models; import io.github.vipcxj.beanknife.runtime.annotations.Access; public class ViewPropertyData { private Access getter; private Access setter; } <|start_filename|>beanknife-core-base/src/main/java/io/github/vipcxj/beanknife/core/utils/VarMapper.java<|end_filename|> package io.github.vipcxj.beanknife.core.utils; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.annotations.NonNull; import java.util.*; public class VarMapper { private final Set<String> initVars; private final IdentityHashMap<Object, String> mapper; private final List<Object> keys; private final Map<String, Integer> indexMap; private boolean used; public VarMapper(String... initVars) { this(Arrays.asList(initVars)); } public VarMapper(@CheckForNull Collection<String> initVars) { this.initVars = initVars != null ? new HashSet<>(initVars) : Collections.emptySet(); this.mapper = new IdentityHashMap<>(); this.keys = new ArrayList<>(); this.indexMap = new HashMap<>(); this.used = false; } @SuppressWarnings("IncompleteCopyConstructor") public VarMapper(VarMapper other) { this.initVars = new HashSet<>(other.initVars); this.mapper = new IdentityHashMap<>(other.mapper); this.keys = new ArrayList<>(other.keys); this.indexMap = new HashMap<>(other.indexMap); this.used = other.used; } public void addInitVar(String var) { if (used) { throw new IllegalStateException("addInitVar method should be called before any getVar methods. use appendVar instead."); } this.initVars.add(var); } public String appendVar(String var) { if (initVars.contains(var) || mapper.containsValue(var)) { return appendVar(var + "_"); } return var; } public void removeVar(Object key) { mapper.remove(key); keys.remove(key); } public String nextVar(String name) { Integer index = indexMap.get(name); if (index == null) { indexMap.put(name, 0); return name + 0; } else { return name + index; } } private void consumeVar(String name) { indexMap.merge(name, 1, Integer::sum); } @NonNull public String getVar(@NonNull Object key, @NonNull String name) { return getVar(key, name, false); } @NonNull public String getVar(@NonNull Object key, @NonNull String name, boolean indexMode) { if (!this.used) { this.used = true; } String result = mapper.get(key); if (result != null) { return result; } String var = indexMode ? nextVar(name) : name; if (indexMode) { consumeVar(name); } if (!initVars.contains(name) && !mapper.containsValue(name)) { mapper.put(key, var); keys.add(key); return var; } else { return getVar(key, indexMode ? nextVar(name) : (name + "_"), indexMode); } } public List<Object> getKeys() { return keys; } @CheckForNull public String getVar(@NonNull Object key) { return mapper.get(key); } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/MethodBeanMeta.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedMeta; @GeneratedMeta(targetClass = MethodBean.class, configClass = MethodBean.class) public class MethodBeanMeta { public static final String now = "now"; } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/annotations/InheritableTypeAnnotation.java<|end_filename|> package io.github.vipcxj.beanknife.cases.annotations; import java.lang.annotation.*; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Inherited public @interface InheritableTypeAnnotation { ValueAnnotation1 annotation(); ValueAnnotation1[] annotations(); } <|start_filename|>beanknife-core-base/src/main/java/io/github/vipcxj/beanknife/core/spi/ViewCodeGenerator.java<|end_filename|> package io.github.vipcxj.beanknife.core.spi; import io.github.vipcxj.beanknife.core.models.ViewContext; import java.io.PrintWriter; public interface ViewCodeGenerator { void ready(ViewContext context); void print(PrintWriter writer, ViewContext context, String indent, int indentNum); } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/spi/BeanProvider.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.spi; import io.github.vipcxj.beanknife.runtime.utils.BeanUsage; /** * Used to tell the library how to instantiate a bean. */ public interface BeanProvider { int DEFAULT_PRIORITY = 0; /** * The priority. The higher is selected than lower. * @return the priority */ default int getPriority() { return DEFAULT_PRIORITY; } /** * Test whether the type is supported by this provider. If not sure or hard to check, just return true. * If {@link #get(Class, BeanUsage, Object)} return null, The library think this provider not support the type as well. * @param type the bean type * @param usage the bean usage * @return whether the type is supported by this provider. */ boolean support(Class<?> type, BeanUsage usage); /** * create or get a instance of the type. * @param type the bean type * @param usage the bean usage * @param requester the bean request the instance. * @param <T> the bean type * @return the bean instance. */ <T> T get(Class<T> type, BeanUsage usage, Object requester); } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/ConfigBeanB.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; @ViewOf(value=BeanB.class, includes={BeanBMeta.a}) // (14) public class ConfigBeanB { } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/DynamicMethodPropertyBeanViewConfig.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.*; @ViewOf(value = SimpleBean.class, genName = "DynamicMethodPropertyBeanView", includes = {SimpleBeanMeta.a, SimpleBeanMeta.b}) public class DynamicMethodPropertyBeanViewConfig { @OverrideViewProperty("b") @Dynamic public static String getB(@InjectSelf DynamicMethodPropertyBeanView self) { return self.getA(); } @NewViewProperty("c") @Dynamic public static String getC(@InjectSelf DynamicMethodPropertyBeanView self) { return self.getB(); } @NewViewProperty("d") @Dynamic public static String getABC(@InjectProperty String a, @InjectProperty String b, @InjectProperty String c) { return a + b + c; } /** * test non static method as a dynamic method property. * Though the source can be compiled, * this will cause a exception in the runtime. Because {@link ViewOf#useDefaultBeanProvider()} is false here. * So no bean provider is used. Then the configure class {@link DynamicMethodPropertyBeanViewConfig} can not be initialized. * @param self the view instance. * @return the property value */ @NewViewProperty("e") @Dynamic public String getABCD(@InjectSelf DynamicMethodPropertyBeanView self) { return self.getA() + self.getB() + self.getC() + self.getD(); } } <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/beans/IllegalPropertyBean.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.ViewMeta; @ViewMeta public class IllegalPropertyBean { private String _while; public String getIf() { return "if"; } public String getWhile() { return _while; } } <|start_filename|>beanknife-jpa-examples/src/main/java/io/github/vipcxj/beanknfie/jpa/examples/dto/CompanyInfoConfiguration.java<|end_filename|> package io.github.vipcxj.beanknfie.jpa.examples.dto; import io.github.vipcxj.beanknfie.jpa.examples.models.Company; import io.github.vipcxj.beanknfie.jpa.examples.models.CompanyMeta; import io.github.vipcxj.beanknife.runtime.annotations.NullNumberAsZero; import io.github.vipcxj.beanknife.runtime.annotations.OverrideViewProperty; import io.github.vipcxj.beanknife.runtime.annotations.RemoveViewProperty; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; @ViewOf(Company.class) @RemoveViewProperty({CompanyMeta.departments, CompanyMeta.employees}) public class CompanyInfoConfiguration extends BaseDtoConfiguration { @OverrideViewProperty(CompanyMeta.money) @NullNumberAsZero private double money; } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/ChangePackageAndNameMetaConfig.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.ViewMeta; @ViewMeta(value = "MetaOfFieldBean", packageName = "io.github.vipcxj.beanknife.cases.otherbean", of = FieldBean.class) public class ChangePackageAndNameMetaConfig { } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/Leaf12BeanViewConfigure.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; @ViewOf(Leaf12Bean.class) public class Leaf12BeanViewConfigure extends Parent1ViewConfigure { } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/MetaAndViewOfOnDiffBean2Meta.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedMeta; @GeneratedMeta( targetClass = MetaAndViewOfOnDiffBean2.class, configClass = MetaAndViewOfOnDiffBean2.class, proxies = { MetaAndViewOfOnDiffBean2ViewConfig.class } ) public class MetaAndViewOfOnDiffBean2Meta { public static final String pa = "pa"; public static final String pb = "pb"; public static class Views { public static final String io_github_vipcxj_beanknife_cases_beans_MetaAndViewOfOnDiffBean2View = "io.github.vipcxj.beanknife.cases.beans.MetaAndViewOfOnDiffBean2View"; } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/ConfigBeanA.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.*; import java.util.List; import java.util.Map; @ViewOf(value=BeanA.class, includes={BeanAMeta.a, BeanAMeta.b, BeanAMeta.c, BeanAMeta.beanBMap}) // (7) public class ConfigBeanA { @OverrideViewProperty(BeanAMeta.beanBMap) // (8) private Map<String, List<BeanBView>> beanBMap; @NewViewProperty("d") // (9) public static boolean d(BeanA source) { // (10) return true; // Generally you should achieve the data from the source. } @NewViewProperty("e") // (11) @Dynamic // (12) public static String e(@InjectProperty int a, @InjectProperty long b) { // (13) return "" + a + b; } } <|start_filename|>beanknife-core-base/src/main/java/io/github/vipcxj/beanknife/core/utils/CollectionUtils.java<|end_filename|> package io.github.vipcxj.beanknife.core.utils; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; public class CollectionUtils { public static <K1, K2, V> Map<K2, V> mapKey(Map<K1, V> map, Function<K1, K2> mapper) { Map<K2, V> out = new HashMap<>(); for (Map.Entry<K1, V> entry : map.entrySet()) { out.put(mapper.apply(entry.getKey()), entry.getValue()); } return out; } public static <T> List<List<T>> checkUnique(Collection<T> collection, Comparator<? super T> comparator) { TreeMap<T, List<T>> checks = new TreeMap<>(comparator); for (T el : collection) { List<T> check = checks.get(el); if (check == null) { List<T> value = new ArrayList<>(); value.add(el); checks.put(el, value); } else { check.add(el); } } return checks.values().stream().filter(v -> v.size() > 1).collect(Collectors.toList()); } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/MetaAndViewOfBothOnBean.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.ViewMeta; import io.github.vipcxj.beanknife.runtime.annotations.ViewOf; import java.util.Date; @ViewMeta @ViewOf(includes = {MetaAndViewOfBothOnBeanMeta.a, MetaAndViewOfBothOnBeanMeta.c, MetaAndViewOfBothOnBeanMeta.e}) public class MetaAndViewOfBothOnBean { private int a; private long b; private String c; private short d; private Date e; public int getA() { return a; } public void setA(int a) { this.a = a; } public long getB() { return b; } public void setB(long b) { this.b = b; } public String getC() { return c; } public void setC(String c) { this.c = c; } public short getD() { return d; } public void setD(short d) { this.d = d; } public Date getE() { return e; } public void setE(Date e) { this.e = e; } } <|start_filename|>beanknife-jpa-runtime/src/main/java/module-info.java<|end_filename|> module beanknife.jpa.runtime { exports io.github.vipcxj.beanknife.jpa.runtime.annotations; } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/ExtraParamsBeanView.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedView; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; @GeneratedView(targetClass = SimpleBean.class, configClass = ExtraParamsViewConfigure.class) public class ExtraParamsBeanView { private String a; private Integer b; private long c; private Class<?> x; private String y; private ExtraParamsBeanView z; public ExtraParamsBeanView() { } public ExtraParamsBeanView( String a, Integer b, long c, Class<?> x, String y, ExtraParamsBeanView z ) { this.a = a; this.b = b; this.c = c; this.x = x; this.y = y; this.z = z; } public ExtraParamsBeanView(ExtraParamsBeanView source) { this.a = source.a; this.b = source.b; this.c = source.c; this.x = source.x; this.y = source.y; this.z = source.z; } public ExtraParamsBeanView(SimpleBean source, Class<?> x, ExtraParamsBeanView z) { if (source == null) { throw new NullPointerException("The input source argument of the read constructor of class io.github.vipcxj.beanknife.cases.beans.ExtraParamsBeanView should not be null."); } this.a = source.getA(); this.b = source.getB(); this.c = source.getC(); this.x = ExtraParamsViewConfigure.x(x); this.y = ExtraParamsViewConfigure.y(x); this.z = ExtraParamsViewConfigure.z(z); } public static ExtraParamsBeanView read(SimpleBean source, Class<?> x, ExtraParamsBeanView z) { if (source == null) { return null; } return new ExtraParamsBeanView(source, x, z); } public String getA() { return this.a; } public Integer getB() { return this.b; } public long getC() { return this.c; } public Class<?> getX() { return this.x; } public String getY() { return this.y; } public ExtraParamsBeanView getZ() { return this.z; } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/BeanBView.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedView; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; @GeneratedView(targetClass = BeanB.class, configClass = ConfigBeanB.class) public class BeanBView { private String a; public BeanBView() { } public BeanBView( String a ) { this.a = a; } public BeanBView(BeanBView source) { this.a = source.a; } public BeanBView(BeanB source) { if (source == null) { throw new NullPointerException("The input source argument of the read constructor of class io.github.vipcxj.beanknife.cases.beans.BeanBView should not be null."); } this.a = source.getA(); } public static BeanBView read(BeanB source) { if (source == null) { return null; } return new BeanBView(source); } public static BeanBView[] read(BeanB[] sources) { if (sources == null) { return null; } BeanBView[] results = new BeanBView[sources.length]; for (int i = 0; i < sources.length; ++i) { results[i] = read(sources[i]); } return results; } public static List<BeanBView> read(List<BeanB> sources) { if (sources == null) { return null; } List<BeanBView> results = new ArrayList<>(); for (BeanB source : sources) { results.add(read(source)); } return results; } public static Set<BeanBView> read(Set<BeanB> sources) { if (sources == null) { return null; } Set<BeanBView> results = new HashSet<>(); for (BeanB source : sources) { results.add(read(source)); } return results; } public static Stack<BeanBView> read(Stack<BeanB> sources) { if (sources == null) { return null; } Stack<BeanBView> results = new Stack<>(); for (BeanB source : sources) { results.add(read(source)); } return results; } public static <K> Map<K, BeanBView> read(Map<K, BeanB> sources) { if (sources == null) { return null; } Map<K, BeanBView> results = new HashMap<>(); for (Map.Entry<K, BeanB> source : sources.entrySet()) { results.put(source.getKey(), read(source.getValue())); } return results; } public String getA() { return this.a; } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/BeanAMeta.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedMeta; @GeneratedMeta( targetClass = BeanA.class, configClass = BeanA.class, proxies = { ConfigBeanA.class, InheritedConfigBeanAViewConfig.class } ) public class BeanAMeta { public static final String a = "a"; public static final String b = "b"; public static final String c = "c"; public static final String beanBMap = "beanBMap"; public static final String shouldBeRemoved = "shouldBeRemoved"; public static class Views { public static final String io_github_vipcxj_beanknife_cases_beans_BeanAView = "io.github.vipcxj.beanknife.cases.beans.BeanAView"; public static final String io_github_vipcxj_beanknife_cases_beans_BeanAViewWithInheritedConfig = "io.github.vipcxj.beanknife.cases.beans.BeanAViewWithInheritedConfig"; } } <|start_filename|>beanknife-core-base/src/main/java/io/github/vipcxj/beanknife/core/utils/LombokInfo.java<|end_filename|> package io.github.vipcxj.beanknife.core.utils; import edu.umd.cs.findbugs.annotations.NonNull; import io.github.vipcxj.beanknife.runtime.annotations.Access; import javax.lang.model.element.Element; public class LombokInfo { private final Access lombokGetter; private final Access lombokSetter; public LombokInfo(@NonNull Element element, @NonNull Access typeGetterAccess, @NonNull Access typeSetterAccess) { this.lombokGetter = LombokUtils.getGetterAccess(element, typeGetterAccess); this.lombokSetter = LombokUtils.getSetterAccess(element, typeSetterAccess); } public boolean isWritable(boolean samePackage) { if (samePackage) { return lombokSetter != Access.NONE && lombokSetter != Access.PRIVATE; } else { return lombokSetter == Access.PUBLIC; } } public boolean isReadable(boolean samePackage) { if (samePackage) { return lombokGetter != Access.NONE && lombokGetter != Access.PRIVATE; } else { return lombokGetter == Access.PUBLIC; } } public boolean hasGetter() { return lombokGetter != Access.NONE; } } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/annotations/ViewPropertiesIncludePattern.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.annotations; import java.lang.annotation.*; @Target(ElementType.TYPE) @Retention(RetentionPolicy.SOURCE) @Repeatable(ViewPropertiesIncludePatterns.class) @Inherited public @interface ViewPropertiesIncludePattern { String value(); } <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/beans/InheritedBean.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.ViewMeta; @ViewMeta public class InheritedBean extends MixedAllBean { private String a; private String newProperty; public String getNewProperty() { return newProperty; } } <|start_filename|>beanknife-runtime/src/main/java/io/github/vipcxj/beanknife/runtime/annotations/UseAnnotation.java<|end_filename|> package io.github.vipcxj.beanknife.runtime.annotations; import io.github.vipcxj.beanknife.runtime.utils.AnnotationDest; import io.github.vipcxj.beanknife.runtime.utils.AnnotationSource; import java.lang.annotation.*; @Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD}) @Retention(RetentionPolicy.SOURCE) @Repeatable(UseAnnotations.class) @Inherited public @interface UseAnnotation { Class<? extends Annotation>[] value() default {}; AnnotationSource[] from() default { AnnotationSource.CONFIG, AnnotationSource.TARGET_TYPE, AnnotationSource.TARGET_GETTER, AnnotationSource.TARGET_FIELD }; AnnotationDest[] dest() default { AnnotationDest.SAME }; } <|start_filename|>beanknife-spring/src/test/java/io/github/vipcxj/beanknife/spring/test/StringConfigure.java<|end_filename|> package io.github.vipcxj.beanknife.spring.test; import io.github.vipcxj.beanknife.spring.test.beans.SpringBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class StringConfigure { @Bean public SpringBean getSpringBean() { return new SpringBean(); } } <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/annotations/PropertyAnnotation1.java<|end_filename|> package io.github.vipcxj.beanknife.cases.annotations; import io.github.vipcxj.beanknife.cases.models.AEnum; import java.lang.annotation.*; @Target({ ElementType.FIELD, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) public @interface PropertyAnnotation1 { boolean booleanValue() default true; int intValue() default 0; short shortValue() default 0; long longValue() default 0; float floatValue() default 0.0f; double doubleValue() default 0.0; char charValue() default '\0'; byte byteValue() default 0; int[] intArray() default {0}; short[] shortArray() default {}; long[] longArray() default {0}; float[] floatArray() default {}; double[] doubleArray() default {0.0}; char[] charArray() default {}; byte[] byteArray() default {}; String stringValue() default ""; String[] stringArray() default {"1", "2", "3"}; Class<? extends Annotation> annotationClass() default FieldAnnotation1.class; Class<? extends Enum<?>>[] enumClassArray() default AEnum.class; ValueAnnotation1 annotation() default @ValueAnnotation1; ValueAnnotation1[] annotations() default @ValueAnnotation1; } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/ViewMetaInNestBean$Bean2$Bean1Meta.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedMeta; @GeneratedMeta(targetClass = ViewMetaInNestBean.Bean2.Bean1.class, configClass = ViewMetaInNestBean.Bean2.Bean1.class) public class ViewMetaInNestBean$Bean2$Bean1Meta { public static final String b = "b"; } <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/beans/IsPropertyBean.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.ViewMeta; @ViewMeta public class IsPropertyBean { public boolean isMe; String isTest; public boolean isMe() { return isMe; } public String isTest() { return isTest; } } <|start_filename|>beanknife-core-base/src/test/resources/io/github/vipcxj/beanknife/cases/beans/MetaAndViewOfOnDiffBean3Meta.java<|end_filename|> package io.github.vipcxj.beanknife.cases.beans; import io.github.vipcxj.beanknife.runtime.annotations.internal.GeneratedMeta; @GeneratedMeta( targetClass = MetaAndViewOfOnDiffBean3.class, configClass = MetaAndViewOfOnDiffBean3MetaConfig.class, proxies = { MetaAndViewOfOnDiffBean3.class } ) public class MetaAndViewOfOnDiffBean3Meta { public static final String pa = "pa"; public static final String pb = "pb"; public static class Views { public static final String io_github_vipcxj_beanknife_cases_beans_MetaAndViewOfOnDiffBean3View = "io.github.vipcxj.beanknife.cases.beans.MetaAndViewOfOnDiffBean3View"; } } <|start_filename|>beanknife-examples/src/main/java/io/github/vipcxj/beanknife/cases/models/AObject.java<|end_filename|> package io.github.vipcxj.beanknife.cases.models; import java.util.Date; public class AObject { private int a; private boolean b; private String c; private Date d; public int getA() { return a; } public void setA(int a) { this.a = a; } public boolean isB() { return b; } public void setB(boolean b) { this.b = b; } public String getC() { return c; } public void setC(String c) { this.c = c; } public Date getD() { return d; } public void setD(Date d) { this.d = d; } }
vipcxj/beanknife
<|start_filename|>MONActivityIndicatorViewDemo/MONActivityIndicatorViewDemo/Source/AppDelegate/MONAppDelegate.h<|end_filename|> // // MONAppDelegate.h // MONActivityIndicatorViewDemo // // Created by <NAME> on 4/24/14. // Copyright (c) 2014 Moaner. All rights reserved. // #import <UIKit/UIKit.h> @interface MONAppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end <|start_filename|>MONActivityIndicatorViewDemo/MONActivityIndicatorViewDemo/Source/Controllers/MONViewController.h<|end_filename|> // // MONViewController.h // MONActivityIndicatorViewDemo // // Created by <NAME> on 4/24/14. // Copyright (c) 2014 Moaner. All rights reserved. // #import <UIKit/UIKit.h> @interface MONViewController : UIViewController @end
joomcode/MONActivityIndicatorView
<|start_filename|>src/Bootstrap/HtmlHelpers/GlyphIcons.cs<|end_filename|> using System.Collections.Generic; using System.Web.Mvc; namespace BootstrapSupport.HtmlHelpers { public static class GlyphIcons { // example usage: // <li>@Html.ActionLinkWithGlyphIcon(Url.Action("Index"), // "Back to List", // "icon-list")</li> // instead of "icon-list", we could also use GlyphIcons.list public static MvcHtmlString ActionLinkWithGlyphIcon(this HtmlHelper helper, string action, string text, string glyphs, string tooltip = "", IDictionary<string, object> htmlAttributes = null) { var glyph = new TagBuilder("i"); glyph.MergeAttribute("class", glyphs); var anchor = new TagBuilder("a"); anchor.MergeAttribute("href", action); if(!string.IsNullOrEmpty(tooltip)) anchor.MergeAttributes( new Dictionary<string, object>() { { "rel", "tooltip" }, { "data-placement", "top" }, { "title", tooltip } } ); if(htmlAttributes != null) anchor.MergeAttributes(htmlAttributes, true); anchor.InnerHtml = glyph + " " + text; return MvcHtmlString.Create(anchor.ToString()); } #region icon constants public const string glass = "icon-glass"; public const string music = "icon-music"; public const string search = "icon-search"; public const string envelope = "icon-envelope"; public const string heart = "icon-heart"; public const string star = "icon-star"; public const string star_empty = "icon-star-empty"; public const string user = "icon-user"; public const string film = "icon-film"; public const string th_large = "icon-th-large"; public const string th = "icon-th"; public const string th_list = "icon-th-list"; public const string ok = "icon-ok"; public const string remove = "icon-remove"; public const string zoom_in = "icon-zoom-in"; public const string zoom_out = "icon-zoom-out"; public const string off = "icon-off"; public const string signal = "icon-signal"; public const string cog = "icon-cog"; public const string trash = "icon-trash"; public const string home = "icon-home"; public const string file = "icon-file"; public const string time = "icon-time"; public const string road = "icon-road"; public const string download_alt = "icon-download-alt"; public const string download = "icon-download"; public const string upload = "icon-upload"; public const string inbox = "icon-inbox"; public const string play_circle = "icon-play-circle"; public const string repeat = "icon-repeat"; public const string refresh = "icon-refresh"; public const string list_alt = "icon-list-alt"; public const string @lock = "icon-lock"; public const string flag = "icon-flag"; public const string headphones = "icon-headphones"; public const string volume_off = "icon-volume-off"; public const string volume_down = "icon-volume-down"; public const string volume_up = "icon-volume-up"; public const string qrcode = "icon-qrcode"; public const string barcode = "icon-barcode"; public const string tag = "icon-tag"; public const string tags = "icon-tags"; public const string book = "icon-book"; public const string bookmark = "icon-bookmark"; public const string print = "icon-print"; public const string camera = "icon-camera"; public const string font = "icon-font"; public const string bold = "icon-bold"; public const string italic = "icon-italic"; public const string text_height = "icon-text-height"; public const string text_width = "icon-text-width"; public const string align_left = "icon-align-left"; public const string align_center = "icon-align-center"; public const string align_right = "icon-align-right"; public const string align_justify = "icon-align-justify"; public const string list = "icon-list"; public const string indent_left = "icon-indent-left"; public const string indent_right = "icon-indent-right"; public const string facetime_video = "icon-facetime-video"; public const string picture = "icon-picture"; public const string pencil = "icon-pencil"; public const string map_marker = "icon-map-marker"; public const string adjust = "icon-adjust"; public const string tint = "icon-tint"; public const string edit = "icon-edit"; public const string share = "icon-share"; public const string check = "icon-check"; public const string move = "icon-move"; public const string step_backward = "icon-step-backward"; public const string fast_backward = "icon-fast-backward"; public const string backward = "icon-backward"; public const string play = "icon-play"; public const string pause = "icon-pause"; public const string stop = "icon-stop"; public const string forward = "icon-forward"; public const string fast_forward = "icon-fast-forward"; public const string step_forward = "icon-step-forward"; public const string eject = "icon-eject"; public const string chevron_left = "icon-chevron-left"; public const string chevron_right = "icon-chevron-right"; public const string plus_sign = "icon-plus-sign"; public const string minus_sign = "icon-minus-sign"; public const string remove_sign = "icon-remove-sign"; public const string ok_sign = "icon-ok-sign"; public const string question_sign = "icon-question-sign"; public const string info_sign = "icon-info-sign"; public const string screenshot = "icon-screenshot"; public const string remove_circle = "icon-remove-circle"; public const string ok_circle = "icon-ok-circle"; public const string ban_circle = "icon-ban-circle"; public const string arrow_left = "icon-arrow-left"; public const string arrow_right = "icon-arrow-right"; public const string arrow_up = "icon-arrow-up"; public const string arrow_down = "icon-arrow-down"; public const string share_alt = "icon-share-alt"; public const string resize_full = "icon-resize-full"; public const string resize_small = "icon-resize-small"; public const string plus = "icon-plus"; public const string minus = "icon-minus"; public const string asterisk = "icon-asterisk"; public const string exclamation_sign = "icon-exclamation-sign"; public const string gift = "icon-gift"; public const string leaf = "icon-leaf"; public const string fire = "icon-fire"; public const string eye_open = "icon-eye-open"; public const string eye_close = "icon-eye-close"; public const string warning_sign = "icon-warning-sign"; public const string plane = "icon-plane"; public const string calendar = "icon-calendar"; public const string random = "icon-random"; public const string comment = "icon-comment"; public const string magnet = "icon-magnet"; public const string chevron_up = "icon-chevron-up"; public const string chevron_down = "icon-chevron-down"; public const string retweet = "icon-retweet"; public const string shopping_cart = "icon-shopping-cart"; public const string folder_close = "icon-folder-close"; public const string folder_open = "icon-folder-open"; public const string resize_vertical = "icon-resize-vertical"; public const string resize_horizontal = "icon-resize-horizontal"; public const string hdd = "icon-hdd"; public const string bullhorn = "icon-bullhorn"; public const string bell = "icon-bell"; public const string certificate = "icon-certificate"; public const string thumbs_up = "icon-thumbs-up"; public const string thumbs_down = "icon-thumbs-down"; public const string hand_right = "icon-hand-right"; public const string hand_left = "icon-hand-left"; public const string hand_up = "icon-hand-up"; public const string hand_down = "icon-hand-down"; public const string circle_arrow_right = "icon-circle-arrow-right"; public const string circle_arrow_left = "icon-circle-arrow-left"; public const string circle_arrow_up = "icon-circle-arrow-up"; public const string circle_arrow_down = "icon-circle-arrow-down"; public const string globe = "icon-globe"; public const string wrench = "icon-wrench"; public const string tasks = "icon-tasks"; public const string filter = "icon-filter"; public const string briefcase = "icon-briefcase"; public const string fullscreen = "icon-fullscreen"; #endregion } } <|start_filename|>src/Bootstrap/Views/Shared/Create.cshtml<|end_filename|> @using BootstrapSupport @model Object @using (Html.BeginForm()) { @Html.ValidationSummary(true) <h4>@Model.GetLabel() <small>Details</small></h4> foreach (var property in Model.VisibleProperties()) { <div class="form-group"> @Html.Label(property.Name.ToSeparatedWords(), new {@class=""}) @Html.Editor(property.Name,new { htmlAttributes = new { @class = "form-control" }, }) @Html.ValidationMessage(property.Name, null, new { @class = "help-block" }) </div> } <div class="form-actions"> <button type="submit" class="btn btn-primary">Save changes</button> @Html.ActionLink("Cancel", "Index", null, new { @class = "btn btn-link " }) </div> } <div> @Html.ActionLink("Back to List", "Index") </div> <script type="text/javascript"> $(document).ready(function() { $("input").addClass("form-control") }); </script> <|start_filename|>src/Bootstrap/Views/Shared/_BootstrapLayout.empty.cshtml<|end_filename|> @using System.Web.Optimization @using BootstrapSupport @using NavigationRoutes <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>@ViewBag.Title</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="@Styles.Url("~/content/css")" rel="stylesheet"/> <style type="text/css"> body { padding-top: 40px; padding-bottom: 40px; background-color: #eee; } .form-signin { max-width: 330px; padding: 15px; margin: 0 auto; } .form-signin .form-signin-heading, .form-signin .checkbox { margin-bottom: 10px; } .form-signin .checkbox { font-weight: normal; } .form-signin .form-control { position: relative; height: auto; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; padding: 10px; font-size: 16px; } .form-signin .form-control:focus { z-index: 2; } .form-signin input[type="email"] { margin-bottom: -1px; border-bottom-right-radius: 0; border-bottom-left-radius: 0; } .form-signin input[type="password"] { margin-bottom: 10px; border-top-left-radius: 0; border-top-right-radius: 0; } </style> <link href="@Styles.Url("~/Content/css-responsive")" rel="stylesheet" type="text/css" /> @RenderSection("head", required: false) @Html.Partial("_html5shiv") @* favicons and touch icons go here *@ </head> <body> <div class="container"> @Html.Partial("_alerts") @RenderBody() <hr> <footer> <p>&copy; Company @System.DateTime.Now.ToString("yyyy")</p> </footer> </div> <!-- container --> @Scripts.Render("~/js") @RenderSection("Scripts", required: false) </body> </html> <|start_filename|>src/Bootstrap/Views/Shared/Details.cshtml<|end_filename|> @using BootstrapSupport @model Object <fieldset> <legend>@Model.GetLabel() <small>Details</small></legend> <dl> <!-- consider adding class="dl-horizontal" for horizontal styling --> @foreach(var property in Model.VisibleProperties()) { <dt> @property.GetLabel().ToSeparatedWords() </dt> <dd> @Html.Display(property.Name) </dd> } </dl> </fieldset> <p> @Html.ActionLink("Edit", "Edit", Model.GetIdValue()) | @Html.ActionLink("Back to List", "Index") </p> <|start_filename|>src/Bootstrap/BootstrapSupport/ControlGroupExtensions.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Web; using System.Web.Mvc; namespace BootstrapSupport { public class ControlGroup : IDisposable { private readonly HtmlHelper _html; public ControlGroup(HtmlHelper html){ _html = html; } public void Dispose(){ _html.ViewContext.Writer.Write(_html.EndControlGroup()); } } public static class ControlGroupExtensions { public static IHtmlString BeginControlGroupFor<T>(this HtmlHelper<T> html,Expression<Func<T, object>> modelProperty){ return BeginControlGroupFor(html, modelProperty, null); } public static IHtmlString BeginControlGroupFor<T>(this HtmlHelper<T> html,Expression<Func<T, object>> modelProperty,object htmlAttributes){ return BeginControlGroupFor(html, modelProperty, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)); } public static IHtmlString BeginControlGroupFor<T>(this HtmlHelper<T> html,Expression<Func<T, object>> modelProperty,IDictionary<string, object> htmlAttributes){ string propertyName = ExpressionHelper.GetExpressionText(modelProperty); return BeginControlGroupFor(html, propertyName, null); } public static IHtmlString BeginControlGroupFor<T>(this HtmlHelper<T> html,string propertyName){ return BeginControlGroupFor(html, propertyName, null); } public static IHtmlString BeginControlGroupFor<T>(this HtmlHelper<T> html,string propertyName, object htmlAttributes){ return BeginControlGroupFor(html, propertyName,HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)); } public static IHtmlString BeginControlGroupFor<T>(this HtmlHelper<T> html,string propertyName,IDictionary<string, object> htmlAttributes){ var controlGroupWrapper = new TagBuilder("div"); controlGroupWrapper.MergeAttributes(htmlAttributes); controlGroupWrapper.AddCssClass("control-group"); string partialFieldName = propertyName; string fullHtmlFieldName = html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(partialFieldName); if (!html.ViewData.ModelState.IsValidField(fullHtmlFieldName)){ controlGroupWrapper.AddCssClass("error"); } string openingTag = controlGroupWrapper.ToString(TagRenderMode.StartTag); return MvcHtmlString.Create(openingTag); } public static IHtmlString EndControlGroup(this HtmlHelper html){ return MvcHtmlString.Create("</div>"); } public static ControlGroup ControlGroupFor<T>(this HtmlHelper<T> html,Expression<Func<T, object>> modelProperty){ return ControlGroupFor(html, modelProperty, null); } public static ControlGroup ControlGroupFor<T>(this HtmlHelper<T> html,Expression<Func<T, object>> modelProperty,object htmlAttributes){ string propertyName = ExpressionHelper.GetExpressionText(modelProperty); return ControlGroupFor(html, propertyName,HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)); } public static ControlGroup ControlGroupFor<T>(this HtmlHelper<T> html, string propertyName){ return ControlGroupFor(html, propertyName, null); } public static ControlGroup ControlGroupFor<T>(this HtmlHelper<T> html, string propertyName,object htmlAttributes){ return ControlGroupFor(html, propertyName,HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)); } public static ControlGroup ControlGroupFor<T>(this HtmlHelper<T> html, string propertyName,IDictionary<string, object> htmlAttributes){ html.ViewContext.Writer.Write(BeginControlGroupFor(html, propertyName, htmlAttributes)); return new ControlGroup(html); } } public static class Alerts { public const string SUCCESS = "success"; public const string ATTENTION = "attention"; public const string ERROR = "error"; public const string INFORMATION = "info"; public static string[] ALL{ get { return new[] {SUCCESS, ATTENTION, INFORMATION, ERROR}; } } } } <|start_filename|>src/Bootstrap/Views/Shared/Delete.cshtml<|end_filename|> @using BootstrapSupport @model Object @using (Html.BeginForm()) { <fieldset> <legend>@Model.GetLabel() <small>Details</small></legend> <dl> <!-- consider class="dl-horizontal" for horizontal styling --> @foreach (var property in Model.VisibleProperties()) { <dt> @property.GetLabel().ToSeparatedWords() </dt> <dd> @Html.Display(property.Name) </dd> } </dl> <div class="form-actions"> <button type="submit" class="btn btn-danger">Delete</button> @Html.ActionLink("Cancel", "Index", null, new { @class = "btn" }) </div> </fieldset> } <|start_filename|>src/Bootstrap/Views/Shared/_BootstrapLayout.basic.cshtml<|end_filename|> @using System.Web.Optimization @using BootstrapSupport @using NavigationRoutes <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>@ViewBag.Title</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="@Styles.Url("~/content/css")" rel="stylesheet"/> @RenderSection("head", required: false) @Html.Partial("_html5shiv") @* favicons and touch icons go here *@ </head> <body> <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">Project name</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> @Html.Navigation() </ul> </div><!--/.nav-collapse --> </div> </nav> <div class="container"> @Html.Partial("_alerts") @Html.Partial("_validationSummary") @RenderBody() <hr> <footer> <p>&copy; Company @System.DateTime.Now.ToString("yyyy")</p> </footer> </div> @Scripts.Render("~/js") @RenderSection("Scripts", required: false) </body> </html> <|start_filename|>src/Bootstrap/Views/Shared/_alerts.cshtml<|end_filename|> @using BootstrapSupport @if (TempData.ContainsKey(Alerts.ATTENTION)) { <div class="alert alert-block"> <a class="close" data-dismiss="alert" href="#">x</a> <h4 class="alert-heading">Attention!</h4> @TempData[Alerts.ATTENTION] </div> } @foreach(string key in Alerts.ALL.Except(new[] {Alerts.ATTENTION})) { if (TempData.ContainsKey(key)) { <div class="alert alert-@key" role="alert"> <button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button> @TempData[key] </div> } } <|start_filename|>src/Bootstrap/Views/examplelayouts/Narrow.cshtml<|end_filename|> @model dynamic @{ ViewBag.Title = "title"; Layout = "~/Views/Shared/_BootstrapLayout.narrow.cshtml"; } <div class="jumbotron"> <h1>Super awesome marketing speak!</h1> <p class="lead">Cras justo odio, dapibus ac facilisis in, egestas eget quam. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus.</p> <a class="btn btn-large btn-success" href="#">Sign up today</a> </div> <hr> <div class="row-fluid marketing"> <div class="span6"> <h4>Subheading</h4> <p>Donec id elit non mi porta gravida at eget metus. Maecenas faucibus mollis interdum.</p> <h4>Subheading</h4> <p>Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Cras mattis consectetur purus sit amet fermentum.</p> <h4>Subheading</h4> <p>Maecenas sed diam eget risus varius blandit sit amet non magna.</p> </div> <div class="span6"> <h4>Subheading</h4> <p>Donec id elit non mi porta gravida at eget metus. Maecenas faucibus mollis interdum.</p> <h4>Subheading</h4> <p>Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Cras mattis consectetur purus sit amet fermentum.</p> <h4>Subheading</h4> <p>Maecenas sed diam eget risus varius blandit sit amet non magna.</p> </div> </div> <|start_filename|>src/Bootstrap/App_Start/ExampleLayoutsRouteConfig.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; using BootstrapMvcSample.Controllers; using NavigationRouteFilterExamples; using NavigationRoutes; namespace BootstrapMvcSample { public class ExampleLayoutsRouteConfig { public static void RegisterRoutes(RouteCollection routes) { // this enables menu suppression for routes with a FilterToken of "admin" set NavigationRouteFilters.Filters.Add(new AdministrationRouteFilter()); routes.MapNavigationRoute<HomeController>("Automatic Scaffolding", c => c.Index(), "", new NavigationRouteOptions {HasBreakAfter = true}); // this route will only show if users are in the role specified in the AdministrationRouteFilter // by default, when you run the site, you will not see this. Explore the AdministrationRouteFilter // class for more information. routes.MapNavigationRoute<HomeController>("Administration Menu", c => c.Admin(), "", new NavigationRouteOptions { HasBreakAfter = true, FilterToken = "admin"}); routes.MapNavigationRoute<ExampleLayoutsController>("Example Layouts", c => c.Starter()) .AddChildRoute<ExampleLayoutsController>("Marketing", c => c.Marketing()) .AddChildRoute<ExampleLayoutsController>("Fluid", c => c.Fluid(), new NavigationRouteOptions{ HasBreakAfter = true}) .AddChildRoute<ExampleLayoutsController>("Sign In", c => c.SignIn()) ; } } } <|start_filename|>src/Bootstrap/Views/examplelayouts/Fluid.cshtml<|end_filename|> @model dynamic @{ ViewBag.Title = "title"; Layout = "~/Views/Shared/_BootstrapLayout.basic.cshtml"; } <div class="row row-offcanvas row-offcanvas-right"> <div class="col-xs-12 col-sm-9"> <p class="pull-right visible-xs"> <button type="button" class="btn btn-primary btn-xs" data-toggle="offcanvas">Toggle nav</button> </p> <div class="jumbotron"> <h1>Hello, world!</h1> <p>This is an example to show the potential of an offcanvas layout pattern in Bootstrap. Try some responsive-range viewport sizes to see it in action.</p> </div> <div class="row"> <div class="col-xs-6 col-lg-4"> <h2>Heading</h2> <p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p> <p><a class="btn btn-default" href="#" role="button">View details »</a></p> </div><!--/.col-xs-6.col-lg-4--> <div class="col-xs-6 col-lg-4"> <h2>Heading</h2> <p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p> <p><a class="btn btn-default" href="#" role="button">View details »</a></p> </div><!--/.col-xs-6.col-lg-4--> <div class="col-xs-6 col-lg-4"> <h2>Heading</h2> <p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p> <p><a class="btn btn-default" href="#" role="button">View details »</a></p> </div><!--/.col-xs-6.col-lg-4--> <div class="col-xs-6 col-lg-4"> <h2>Heading</h2> <p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p> <p><a class="btn btn-default" href="#" role="button">View details »</a></p> </div><!--/.col-xs-6.col-lg-4--> <div class="col-xs-6 col-lg-4"> <h2>Heading</h2> <p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p> <p><a class="btn btn-default" href="#" role="button">View details »</a></p> </div><!--/.col-xs-6.col-lg-4--> <div class="col-xs-6 col-lg-4"> <h2>Heading</h2> <p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p> <p><a class="btn btn-default" href="#" role="button">View details »</a></p> </div><!--/.col-xs-6.col-lg-4--> </div><!--/row--> </div><!--/.col-xs-12.col-sm-9--> <div class="col-xs-6 col-sm-3 sidebar-offcanvas" id="sidebar" role="navigation"> <div class="list-group"> <a href="#" class="list-group-item active">Link</a> <a href="#" class="list-group-item">Link</a> <a href="#" class="list-group-item">Link</a> <a href="#" class="list-group-item">Link</a> <a href="#" class="list-group-item">Link</a> <a href="#" class="list-group-item">Link</a> <a href="#" class="list-group-item">Link</a> <a href="#" class="list-group-item">Link</a> <a href="#" class="list-group-item">Link</a> <a href="#" class="list-group-item">Link</a> </div> </div><!--/.sidebar-offcanvas--> </div> <|start_filename|>src/Bootstrap/Views/examplelayouts/marketing.cshtml<|end_filename|> @model dynamic @{ ViewBag.Title = "title"; Layout = "~/Views/Shared/_BootstrapLayout.basic.cshtml"; } <div class="jumbotron"> <h1>Hello, world!</h1> <p>This is a template for a simple marketing or informational website. It includes a large callout called a jumbotron and three supporting pieces of content. Use it as a starting point to create something more unique.</p> <p><a class="btn btn-primary btn-lg" href="#" role="button">Learn more »</a></p> </div> <div class="row"> <div class="col-md-4"> <h2>Heading</h2> <p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p> <p><a class="btn btn-default" href="#" role="button">View details »</a></p> </div> <div class="col-md-4"> <h2>Heading</h2> <p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p> <p><a class="btn btn-default" href="#" role="button">View details »</a></p> </div> <div class="col-md-4"> <h2>Heading</h2> <p>Donec sed odio dui. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Vestibulum id ligula porta felis euismod semper. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus.</p> <p><a class="btn btn-default" href="#" role="button">View details »</a></p> </div> </div> <|start_filename|>src/Bootstrap/Views/Shared/_validationSummary.cshtml<|end_filename|> @{ // NOTE: This constant controls whether property validation failures will be excluded from the summary const bool ExcludePropertyFailures = true; var renderSummary = false; if (ExcludePropertyFailures) { // Here we need to figure out if there are going to be any validation failures that are not related to a property // If there are none found, we don't want to display the alert div // This logic is taken from System.Web.Mvc.Html.ValidationExtensions.GetModelStateList(HtmlHelper htmlHelper, bool excludePropertyErrors) // which is eventually invoked by calling @Html.ValidationSummary(ExcludePropertyFailures) // The call to ViewData.ModelState.TryGetValue will determine whether there are any validation failures that are not related to a property ModelState state; ViewData.ModelState.TryGetValue(ViewData.TemplateInfo.HtmlFieldPrefix, out state); if (state != null) { renderSummary = true; } } else { if (ViewData.ModelState.Any(x => x.Value.Errors.Any())) { renderSummary = true; } } if (renderSummary) { <div class="alert alert-error"> <a class="close" data-dismiss="alert">&times;</a> @Html.ValidationSummary(ExcludePropertyFailures) </div> } } <|start_filename|>src/Bootstrap/Controllers/ExampleLayoutsController.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace BootstrapMvcSample.Controllers { public class ExampleLayoutsController : Controller { public ActionResult Starter() { return View(); } public ActionResult Marketing() { return View(); } public ActionResult Fluid() { return View(); } public ActionResult Narrow() { return View(); } public ActionResult SignIn() { return View(); } public ActionResult StickyFooter() { return View("TBD"); } public ActionResult Carousel() { return View("TBD"); } } } <|start_filename|>src/Bootstrap/NavigationRouteFilterExamples/AdministrationRouteFilter.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Web; using NavigationRoutes; namespace NavigationRouteFilterExamples { public class AdministrationRouteFilter :INavigationRouteFilter { // an excercise for the reader would be to load the role name // from your config file so this isn't compiled in, or add a constructor // that accepts a role name to use to make this a more generic filter private string AdministrationRole = "admin"; public bool ShouldRemove(System.Web.Routing.Route navigationRoutes) { if (navigationRoutes.DataTokens.HasFilterToken()) { var filterToken = navigationRoutes.DataTokens.FilterToken(); var result = !HttpContext.Current.User.IsInRole(AdministrationRole) && filterToken == AdministrationRole; return result; } return false; } } }
daveamato/twitter.bootstrap.mvc
<|start_filename|>pkg/rule/dl3019.go<|end_filename|> package rules import ( "strings" "github.com/moby/buildkit/frontend/dockerfile/parser" ) // validateDL3019 Use the `--no-cache` switch to avoid the need to use `--update` and remove `/var/cache/apk/*` when done installing packages func validateDL3019(node *parser.Node) (rst []ValidateResult, err error) { for _, child := range node.Children { if child.Value == RUN && isDL3019Error(child) { rst = append(rst, ValidateResult{line: child.StartLine}) } } return rst, nil } func isDL3019Error(node *parser.Node) bool { var isApk, isRm bool for _, v := range strings.Fields(node.Next.Value) { switch v { case "apk": isApk = true case "update": if isApk { return true } case "rm": if isApk { isRm = true } case "/var/cache/apk/*": if isRm { return true } case "&&": isApk = false } } return false } <|start_filename|>pkg/rule/dl3001.go<|end_filename|> package rules import ( "strings" "github.com/moby/buildkit/frontend/dockerfile/parser" ) // validateDL3001 is "For some bash commands it makes no sense running them in a Docker container // like free, ifconfig, kill, mount, ps, service, shutdown, ssh, top, vim" func validateDL3001(node *parser.Node) (rst []ValidateResult, err error) { for _, child := range node.Children { if child.Value == RUN { for _, v := range strings.Fields(child.Next.Value) { if existsTools(v) { rst = append(rst, ValidateResult{line: child.StartLine}) } } } } return rst, nil } func existsTools(s string) bool { for _, c := range []string{"free", "ifconfig", "kill", "mount", "ps", "service", "shutdown", "ssh", "top", "vim"} { if s == c { return true } } return false } <|start_filename|>pkg/rule/dl4005.go<|end_filename|> package rules import ( "strings" "github.com/moby/buildkit/frontend/dockerfile/parser" ) // validateDL4005 Use SHELL to change the default shell func validateDL4005(node *parser.Node) (rst []ValidateResult, err error) { for _, child := range node.Children { if child.Value == RUN { isLn := false for _, v := range strings.Fields(child.Next.Value) { switch v { case "ln": isLn = true case "/bin/sh": if isLn { rst = append(rst, ValidateResult{line: child.StartLine}) } } } } } return rst, nil } <|start_filename|>pkg/rule/dl3009.go<|end_filename|> package rules import ( "strings" "github.com/moby/buildkit/frontend/dockerfile/parser" ) // validateDL3009 Delete the apt-get lists after installing something. func validateDL3009(node *parser.Node) (rst []ValidateResult, err error) { for _, child := range node.Children { if child.Value == RUN && isDL3009Error(child) { rst = append(rst, ValidateResult{line: child.StartLine}) } } return rst, nil } func isDL3009Error(node *parser.Node) bool { var isAptGet, isInstalled, hasClean, isRm, hasRemove bool for _, v := range strings.Fields(node.Next.Value) { isAptGet, isInstalled, hasClean, isRm, hasRemove = updateDL3009Status(v, isAptGet, isInstalled, hasClean, isRm, hasRemove) } return isInstalled && !(hasRemove || hasClean) } func updateDL3009Status(v string, isAptGet, isInstalled, hasClean, isRm, hasRemove bool) (bool, bool, bool, bool, bool) { switch v { case "apt-get": return true, isInstalled, hasClean, isRm, hasRemove case "install", "update": if isAptGet { return true, true, hasClean, isRm, hasRemove } case "clean": if isAptGet && isInstalled { return true, true, true, isRm, hasRemove } case "rm": if isInstalled { return true, true, hasClean, hasRemove, true } case "/var/lib/apt/lists/*": if isRm { return true, true, hasClean, true, true } case "&&": if isAptGet { return false, isInstalled, false, isRm, hasRemove } } return isAptGet, isInstalled, hasClean, isRm, hasRemove } <|start_filename|>pkg/rule/dl3000.go<|end_filename|> package rules import ( "fmt" "path/filepath" "github.com/moby/buildkit/frontend/dockerfile/parser" ) // validateDL3000 is "Use absolute WORKDIR." func validateDL3000(node *parser.Node) (rst []ValidateResult, err error) { for _, child := range node.Children { if child.Value == WORKDIR { absPath, err := filepath.Abs(child.Next.Value) if err != nil { return nil, fmt.Errorf("#%v DL3000: failed to convert relative path to absolute path (err: %s)", child.StartLine, err) } if absPath != child.Next.Value { rst = append(rst, ValidateResult{line: child.StartLine}) } } } return rst, nil } <|start_filename|>pkg/rule/dl4001.go<|end_filename|> package rules import ( "strings" "github.com/moby/buildkit/frontend/dockerfile/parser" ) // validateDL4001 is dockerfile linter DL4001 rule. // Either use Wget or Curl but not both. func validateDL4001(node *parser.Node) (rst []ValidateResult, err error) { var isCurl, isWget bool var lines []int for _, child := range node.Children { if child.Value == RUN { for _, v := range strings.Fields(child.Next.Value) { switch v { case "curl": isCurl = true lines = append(lines, child.StartLine) case "wget": isWget = true lines = append(lines, child.StartLine) } } } } if isCurl && isWget { for _, line := range lines { rst = append(rst, ValidateResult{line: line}) } } return rst, nil } <|start_filename|>pkg/rule/dl3014.go<|end_filename|> package rules import ( "regexp" "strings" "github.com/moby/buildkit/frontend/dockerfile/parser" ) var yesPattern = regexp.MustCompile(`^-(y|-yes|-assume-yes)$`) // validateDL3014 Use the `-y` switch to avoid manual input `apt-get -y install <package>` func validateDL3014(node *parser.Node) (rst []ValidateResult, err error) { for _, child := range node.Children { if child.Value == RUN { var isAptGet, isInstalled bool length := len(rst) for _, v := range strings.Fields(child.Next.Value) { switch v { case "apt-get": isAptGet = true case "install": if isAptGet { isInstalled = true } case "&&": isAptGet, isInstalled = false, false default: if isInstalled && !yesPattern.MatchString(v) && length == len(rst) { rst = append(rst, ValidateResult{line: child.StartLine}) } isAptGet, isInstalled = false, false } } } } return rst, nil } <|start_filename|>pkg/rule/dl4006.go<|end_filename|> package rules import ( "strings" "github.com/moby/buildkit/frontend/dockerfile/parser" ) // validateDL4006 Set the `SHELL` option -o pipefail before `RUN` with a pipe in it func validateDL4006(node *parser.Node) (rst []ValidateResult, err error) { var isShellPipeFail bool for _, child := range node.Children { switch child.Value { case SHELL: isShellPipeFail = true case RUN: for _, v := range strings.Fields(child.Next.Value) { switch v { case "|": if !isShellPipeFail { rst = append(rst, ValidateResult{line: child.StartLine}) } } } } } return rst, nil } <|start_filename|>pkg/rule/dl4003.go<|end_filename|> package rules import ( "github.com/moby/buildkit/frontend/dockerfile/parser" ) // validateDL4003 Multiple CMD instructions found. func validateDL4003(node *parser.Node) (rst []ValidateResult, err error) { var isCmd bool for _, child := range node.Children { if child.Value == CMD { if !isCmd { isCmd = true } else { rst = append(rst, ValidateResult{line: child.StartLine}) } } } return rst, nil } <|start_filename|>pkg/rule/dl3025.go<|end_filename|> package rules import ( "github.com/moby/buildkit/frontend/dockerfile/parser" ) // validateDL3025 Use arguments JSON notation for CMD and ENTRYPOINT arguments func validateDL3025(node *parser.Node) (rst []ValidateResult, err error) { for _, child := range node.Children { if (child.Value == ENTRYPOINT) || (child.Value == CMD) { l := len(child.Value) if child.Original[l+1:l+2] != "[" || child.Original[len(child.Original)-1:] != "]" { rst = append(rst, ValidateResult{line: child.StartLine}) } } } return rst, nil } <|start_filename|>pkg/rule/dl3024.go<|end_filename|> package rules import ( "strings" "github.com/moby/buildkit/frontend/dockerfile/parser" ) // validateDL3024 FROM aliases (stage names) must be unique func validateDL3024(node *parser.Node) (rst []ValidateResult, err error) { var isAs bool var asBuildName []string for _, child := range node.Children { if child.Value == FROM { for _, v := range strings.Fields(child.Original) { switch v { case "as": isAs = true default: if isAs { if isContain(asBuildName, v) { rst = append(rst, ValidateResult{line: child.StartLine}) } else { asBuildName = append(asBuildName, v) } isAs = false } } } } } return rst, nil } <|start_filename|>pkg/rule/dl3011.go<|end_filename|> package rules import ( "fmt" "strconv" "github.com/moby/buildkit/frontend/dockerfile/parser" ) // validateDL3011 Valid UNIX ports range from 0 to 65535 func validateDL3011(node *parser.Node) (rst []ValidateResult, err error) { for _, child := range node.Children { if child.Value == EXPOSE { port := child.Next if port != nil { portNum, err := strconv.Atoi(port.Value) if err != nil { return nil, fmt.Errorf("#%v DL3011 not numeric is the value set for the port: %s", child.StartLine, port.Value) } if portNum < 0 || portNum > 65535 { rst = append(rst, ValidateResult{line: child.StartLine}) } } } } return rst, nil }
opstree/OT-DockerLinter
<|start_filename|>KImageEditor/ImageVC.h<|end_filename|> // // ImageVC.h // UndoDrawing // // Created by Krishana on 1/19/17. // Copyright © 2017 codeall. All rights reserved. // #import <UIKit/UIKit.h> @interface ImageVC : UIViewController @property (strong, nonatomic) UIImage *image; @end <|start_filename|>KImageEditor/ViewController.h<|end_filename|> // // ViewController.h // KImageEditor // // Created by Krishana on 9/19/17. // Copyright © 2017 Konstant Info Solutions Pvt. Ltd. All rights reserved. // #import <UIKit/UIKit.h> @interface ViewController : UIViewController @end <|start_filename|>KImageEditor/AppDelegate.h<|end_filename|> // // AppDelegate.h // KImageEditor // // Created by Krishana on 9/19/17. // Copyright © 2017 Konstant Info Solutions Pvt. Ltd. All rights reserved. // #import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end <|start_filename|>KImageEditor/DrawTextVC.h<|end_filename|> // // DrawTextVC.h // KImageEditor // // Created by Krishana on 9/19/17. // Copyright © 2017 Konstant Info Solutions Pvt. Ltd. All rights reserved. // #import <UIKit/UIKit.h> @interface DrawTextVC : UIViewController @property (strong, nonatomic) UIImage *selectedImage; @property (weak, nonatomic) IBOutlet UIImageView *imageViewSelectedImage; @property (weak, nonatomic) IBOutlet UITextView *textFieldText; @end <|start_filename|>KImageEditor/Config/Config.h<|end_filename|> // // Config.h // KconfigScrollable // // Created by Krishna on 13/04/16. // Copyright © 2016 KT. All rights reserved. // #import <Foundation/Foundation.h> @interface Config : NSObject //Collection View Values #define NUMBER_OF_ITEMS_PER_ROW 4 #define COLLECTION_CELL_LEFT_PADDING 10.0f #define COLLECTION_CELL_RIGHT_PADDING 10.0f #define COLLECTION_CELL_INTER_ITEMS_PADDING 5.0f #define COLLECTION_CELL_MIN_LINE_SPACING 5.0f #define APPDELEGATE ((AppDelegate *)[[UIApplication sharedApplication] delegate]) //device checking macros #define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) #define IS_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) #define IS_RETINA ([[UIScreen mainScreen] scale] >= 2.0) #define IS_HEIGHT_GTE_780 ([[UIScreen mainScreen ] bounds].size.height >= 780.0f) #define SCREEN_MAX_LENGTH (MAX(SCREEN_WIDTH, SCREEN_HEIGHT)) #define SCREEN_MIN_LENGTH (MIN(SCREEN_WIDTH, SCREEN_HEIGHT)) #define IS_IPHONE_4_OR_LESS (IS_IPHONE && SCREEN_MAX_LENGTH < 568.0) #define IS_IPHONE_5 (IS_IPHONE && SCREEN_MAX_LENGTH == 568.0) #define IS_IPHONE_6 (IS_IPHONE && SCREEN_MAX_LENGTH == 667.0) #define IS_IPHONE_6P (IS_IPHONE && SCREEN_MAX_LENGTH == 736.0) #define SCREEN_WIDTH [[UIScreen mainScreen] bounds].size.width #define SCREEN_HEIGHT [[UIScreen mainScreen] bounds].size.height @end <|start_filename|>KImageEditor/DrawImageVC.h<|end_filename|> // // DrawImageVC.h // KImageEditor // // Created by Krishana on 9/19/17. // Copyright © 2017 Konstant Info Solutions Pvt. Ltd. All rights reserved. // #import <UIKit/UIKit.h> @interface DrawImageVC : UIViewController @property (strong, nonatomic) UIImage *selectedImage; @end
krishnads/KImageEdit
<|start_filename|>lib/state_container.dart<|end_filename|> import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; class StateContainer extends StatefulWidget { final Widget child; final int selectedIndex; StateContainer({ @required this.child, this.selectedIndex = -1, }); static StateContainerState of(BuildContext context) { return (context.inheritFromWidgetOfExactType(_InheritedStateContainer) as _InheritedStateContainer) .data; } @override StateContainerState createState() => new StateContainerState(); } class StateContainerState extends State<StateContainer> { int selectedIndex = -1; void updateSelectedIndex({int index}) { setState(() { selectedIndex = index; }); } @override Widget build(BuildContext context) { return new _InheritedStateContainer( data: this, child: widget.child, ); } } class _InheritedStateContainer extends InheritedWidget { final StateContainerState data; _InheritedStateContainer({ Key key, @required this.data, @required Widget child, }) : super(key: key, child: child); @override bool updateShouldNotify(_InheritedStateContainer old) => true; } <|start_filename|>lib/home_page.dart<|end_filename|> import 'package:flutter/material.dart'; import 'package:youtube_flutter_app/state_container.dart'; import 'package:youtube_flutter_app/ui/VideoDetail.dart'; import 'package:youtube_flutter_app/ui/VideoItem.dart'; import 'package:youtube_flutter_app/ui/rounded_floating_app_bar.dart'; import 'package:flutter_svg/flutter_svg.dart'; class MyHomePage extends StatefulWidget { final int selectedIndex = -1; @override MyHomePageState createState() => MyHomePageState(); } class MyHomePageState extends State<MyHomePage> { PageController _pageController; var _page = 0; static const int _redPrimaryValue = 0xFFF44336; @override Widget build(BuildContext context) { final container = StateContainer.of(context); return Stack( children: <Widget>[ Scaffold( bottomNavigationBar: BottomNavigationBar( type: BottomNavigationBarType.fixed, items: [ buildBottomNavigationBarItem( "Home", "assets/images/outline-home-24px.svg"), buildBottomNavigationBarItem( "Trending", "assets/images/outline-trending_up-24px.svg"), buildBottomNavigationBarItem("Subscriptions", "assets/images/outline-subscriptions-24px.svg"), buildBottomNavigationBarItem( "Inbox", "assets/images/outline-inbox-24px.svg"), buildBottomNavigationBarItem( "Library", "assets/images/outline-video_library-24px.svg"), ], onTap: navigationTapped, currentIndex: _page, ), body: NestedScrollView( headerSliverBuilder: (context, isInnerBoxScroll) => [ RoundedFloatingAppBar( actions: <Widget>[ IconButton( icon: SvgPicture.asset( "assets/images/outline-videocam-24px.svg", color: Colors.black, ), onPressed: () {}, ), IconButton( icon: SvgPicture.asset( "assets/images/outline-search-24px.svg", color: Colors.black, ), onPressed: () {}, ), IconButton( icon: CircleAvatar( child: FlutterLogo( size: 18, ), backgroundColor: Colors.red, ), onPressed: () {}, ), ], iconTheme: IconThemeData( color: Colors.black, ), textTheme: TextTheme( title: TextStyle( color: Colors.black, ), ), floating: true, snap: true, title: Row( crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ FlutterLogo( colors: MaterialColor( _redPrimaryValue, <int, Color>{ 50: Color(0xFFFFEBEE), 100: Color(0xFFFFCDD2), 200: Color(0xFFEF9A9A), 300: Color(0xFFE57373), 400: Color(0xFFEF5350), 500: Color(_redPrimaryValue), 600: Color(0xFFE53935), 700: Color(0xFFD32F2F), 800: Color(0xFFC62828), 900: Color(0xFFB71C1C), }, ), ), Padding( padding: const EdgeInsets.symmetric(vertical: 16), child: Text( "Youtube", style: TextStyle( fontWeight: FontWeight.bold, fontSize: 18), ), ), ], ), backgroundColor: Colors.white, ), ], body: PageView( children: <Widget>[ ListView.builder( itemBuilder: (BuildContext context, int index) => VideoItem(index), itemCount: 10, ), ListView.builder( itemBuilder: (BuildContext context, int index) => VideoItem(index), itemCount: 10, ), ListView.builder( itemBuilder: (BuildContext context, int index) => VideoItem(index), itemCount: 10, ), ListView.builder( itemBuilder: (BuildContext context, int index) => VideoItem(index), itemCount: 10, ), ListView.builder( itemBuilder: (BuildContext context, int index) => VideoItem(index), itemCount: 10, ) ], controller: _pageController, onPageChanged: onPageChanged, physics: NeverScrollableScrollPhysics(), ), ), ), /// ///foreground detail view /// container.selectedIndex == -1 ? Container() : VideoDetail(widget.selectedIndex.toString()) ], ); } BottomNavigationBarItem buildBottomNavigationBarItem( String title, String assetIconPath) { return BottomNavigationBarItem( title: Text( title, style: TextStyle( fontSize: 11, ), ), activeIcon: SvgPicture.asset( assetIconPath, color: Colors.red, ), icon: SvgPicture.asset( assetIconPath, color: Colors.black, ), ); } /// /// Bottom Navigation tap listener /// void navigationTapped(int page) { _pageController.jumpToPage(page); } void onPageChanged(int page) { setState(() { this._page = page; }); } @override void initState() { super.initState(); _pageController = PageController(); } @override void dispose() { super.dispose(); _pageController.dispose(); } } <|start_filename|>lib/ui/VideoDetail.dart<|end_filename|> import 'package:flutter/material.dart'; import 'package:youtube_flutter_app/state_container.dart'; class VideoDetail extends StatefulWidget { VideoDetail(this.index, {Key key}) : super(key: key); final String index; @override _VideoDetailState createState() => _VideoDetailState(); } class _VideoDetailState extends State<VideoDetail> with SingleTickerProviderStateMixin { var _giveVerse = true; StateContainerState container; Animation<double> height; Animation<double> width; bool visible = true; Animation<double> opacity; Animation<double> position; Animation<double> bottomPosition; AnimationController controller; double maxWidth; double maxHeight = 200; @override void initState() { controller = AnimationController( duration: const Duration(milliseconds: 1000), vsync: this); super.initState(); } @override void dispose() { controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { container = StateContainer.of(context); Widget _buildAnimation(BuildContext context, Widget child) { height = Tween<double>( begin: MediaQuery.of(context).size.height - MediaQuery.of(context).padding.top, end: 75.0, ).animate( CurvedAnimation( parent: controller, curve: Interval( 0.0, 0.500, curve: Curves.easeInOutSine, ), ), ); width = Tween<double>( begin: MediaQuery.of(context).size.width, end: MediaQuery.of(context).size.width / 3, ).animate( CurvedAnimation( parent: controller, curve: Interval( 0.0, 0.500, curve: Curves.easeInOutSine, ), ), ); position = Tween<double>( begin: 0.0, end: 8.0, ).animate( CurvedAnimation( parent: controller, curve: Interval( 0.0, 0.500, curve: Curves.easeInOutSine, ), ), ); bottomPosition = Tween<double>( begin: 0.0, end: 72, ).animate( CurvedAnimation( parent: controller, curve: Interval( 0.0, 0.500, curve: Curves.easeInOutSine, ), ), ); opacity = Tween<double>( begin: 1.0, end: 0.0, ).animate( CurvedAnimation( reverseCurve: Curves.easeIn, parent: controller, curve: Interval( 0.0, 0.200, curve: Curves.ease, ), ), ); return Positioned( bottom: bottomPosition.value, right: position.value, left: position.value, child: Container( width: width.value, height: height.value, color: Colors.transparent, child: Column( children: <Widget>[ Expanded( child: detailVideoCardWidget( MediaQuery.of(context).size.width, height.value, BoxConstraints(maxHeight: 200, minHeight: 75), ), ), ], ), ), ); } return WillPopScope( onWillPop: _onWillPop, child: AnimatedBuilder( builder: _buildAnimation, animation: controller, ), ); } /// /// Detail Video card /// Widget detailVideoCardWidget( double width, double height, BoxConstraints boxConstraints) { return Material( child: Container( child: Column( children: <Widget>[ GestureDetector( onVerticalDragEnd: (details) { print("Y: ${details.velocity.pixelsPerSecond.dy}"); if (details.velocity.pixelsPerSecond.dy > 0) { controller.forward(); setState(() { visible = !visible; }); } else if (details.velocity.pixelsPerSecond.dy < 0) { controller.reverse(); setState(() { visible = !visible; }); } }, child: Container( constraints: boxConstraints, width: width, height: height, child: Stack( fit: StackFit.loose, children: <Widget>[ Container( width: width, color: Color.fromRGBO(2, 18, 37, 0.8), child: FlutterLogo( size: 200, ), ), Center( child: Icon( Icons.play_circle_outline, size: 64, color: Colors.white, ), ), ], ), ), ), Visibility( visible: opacity.value == 1, child: AnimatedOpacity( duration: Duration(milliseconds: 500), opacity: opacity.value, child: Column( mainAxisSize: MainAxisSize.max, crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ titleWidget(), viewsWidget(), Padding( padding: const EdgeInsets.only( left: 16, right: 16, ), child: Divider(), ), optionsWidget(), Padding( padding: const EdgeInsets.only( left: 16, right: 16, ), child: Divider(), ), channelWidget(), middleAutoPlayWidgets(), Container( margin: EdgeInsets.only( left: 16, right: 16, top: 8, bottom: 8, ), height: 150, child: ListView( shrinkWrap: true, scrollDirection: Axis.horizontal, children: <Widget>[ horizontalVideoList(), horizontalVideoList(), ], ), ), ], ), ), ), ], ), ), ); } /// /// title Widget /// Widget titleWidget() { return Padding( padding: const EdgeInsets.only( top: 16, left: 8, right: 8, ), child: Text( "Marvel Studios Avengers: Infinity War - Official Trailer", overflow: TextOverflow.ellipsis, softWrap: true, maxLines: 2, style: TextStyle( fontSize: 16, ), ), ); } /// /// Views Widget /// Widget viewsWidget() { return Padding( padding: const EdgeInsets.all(8), child: Text( "83M views", softWrap: true, maxLines: 2, style: TextStyle(fontSize: 12), ), ); } Widget optionsWidget() { return Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ InkWell( borderRadius: BorderRadius.circular(64), onTap: () {}, child: Padding( padding: const EdgeInsets.all(8), child: Image.asset( "assets/images/thumbs_up.png", fit: BoxFit.cover, height: 24, width: 24, ), ), ), InkWell( borderRadius: BorderRadius.circular(64), onTap: () {}, child: Padding( padding: const EdgeInsets.all(8), child: Image.asset( "assets/images/thumbs_down.png", height: 24, width: 24, ), ), ), InkWell( borderRadius: BorderRadius.circular(64), onTap: () {}, child: Padding( padding: const EdgeInsets.all(8), child: Image.asset( "assets/images/share.png", height: 24, width: 24, ), ), ), InkWell( borderRadius: BorderRadius.circular(64), onTap: () {}, child: Padding( padding: const EdgeInsets.all(8), child: Image.asset( "assets/images/download.png", height: 24, width: 24, ), ), ), InkWell( borderRadius: BorderRadius.circular(64), onTap: () {}, child: Padding( padding: const EdgeInsets.all(8), child: Image.asset( "assets/images/add_playlist.png", height: 24, width: 24, ), ), ), ], ); } Widget channelWidget() { return Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Padding( padding: const EdgeInsets.only( top: 8, left: 16, right: 8, bottom: 8, ), child: CircleAvatar( child: FlutterLogo(), backgroundColor: Colors.redAccent, ), ), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( "Avengers Infinity war", overflow: TextOverflow.ellipsis, softWrap: true, maxLines: 1, style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, ), ), Text( "Avengers Infinity war", softWrap: true, maxLines: 1, style: TextStyle(fontSize: 12), ), ], ), ), Container( margin: EdgeInsets.only(right: 16), child: FlatButton.icon( icon: Icon( Icons.play_arrow, size: 16, color: Color.fromRGBO(231, 0, 3, 0.8), ), label: Text( "SUBSCRIBE", style: TextStyle( color: Color.fromRGBO(231, 0, 3, 0.8), ), ), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(28), ), onPressed: () {}, ), ) ], ); } /// /// Up next auto play widget /// Widget middleAutoPlayWidgets() { return Container( margin: EdgeInsets.only( left: 16, right: 16, ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Text( "Up next", style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, ), ), Row( children: <Widget>[ Text( "Autoplay", style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, ), ), Switch( activeColor: Colors.redAccent, value: _giveVerse, onChanged: (bool newValue) { setState(() { _giveVerse = newValue; }); }, ), ], ), ], ), ); } Widget horizontalVideoList() { return Container( child: Card( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(12), ), color: Color.fromRGBO(2, 18, 37, 0.8), child: FlutterLogo( size: 100, ), elevation: 8, margin: EdgeInsets.zero, ), height: 100, width: 200, padding: EdgeInsets.only( left: 8, right: 8, ), ); } Widget commentWidget() { return Card( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(12), ), child: Container( child: ListView( children: <Widget>[ Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ FlutterLogo(), Padding( padding: const EdgeInsets.all(8), child: Text('Add a public comment...'), ) ], ) ], ), ), ); } Widget commentTextLabelWidget() { return Container( margin: EdgeInsets.only( left: 16, right: 16, ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Row( children: <Widget>[ Padding( padding: const EdgeInsets.all(8), child: Text( "Comments", style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, fontStyle: FontStyle.normal, ), ), ), Padding( padding: const EdgeInsets.all(8), child: Text( "256", style: TextStyle( fontSize: 16, fontStyle: FontStyle.normal, fontWeight: FontWeight.bold, ), ), ), ], ), IconButton( onPressed: () {}, icon: Icon(Icons.filter_list), ), ], ), ); } Future<bool> _onWillPop() { if (container.selectedIndex > -1) { if (controller.isCompleted) { Navigator.of(context).pop(true); } else { controller.forward(); } } } } <|start_filename|>lib/ui/youtube_pip.dart<|end_filename|> import 'package:flutter/material.dart'; class YoutubePIPAnimation extends StatefulWidget { YoutubePIPAnimation({ Key key, this.backgroundWidget, }) : assert(backgroundWidget != null), super(key: key); final Widget backgroundWidget; @override _YoutubePIPAnimationState createState() => _YoutubePIPAnimationState(); } class _YoutubePIPAnimationState extends State<YoutubePIPAnimation> with SingleTickerProviderStateMixin { Animation<double> height; bool visible = true; Animation<double> borderWidth; Animation<double> opacity; Animation<double> position; AnimationController controller; double maxWidth; double maxHeight = 200; Animation<double> bottomPosition; @override void initState() { super.initState(); controller = AnimationController( duration: const Duration(milliseconds: 500), vsync: this); // controller.repeat(reverse: true); } @override void dispose() { controller.dispose(); super.dispose(); } Widget _buildAnimation(BuildContext context, Widget child) { height = Tween<double>( begin: MediaQuery.of(context).size.height - MediaQuery.of(context).padding.top, end: 75.0, ).animate( CurvedAnimation( parent: controller, curve: Interval( 0.0, 0.500, curve: Curves.easeInOutSine, ), ), ); position = Tween<double>( begin: 0.0, end: 16.0, ).animate( CurvedAnimation( parent: controller, curve: Interval( 0.0, 0.500, curve: Curves.easeInOutSine, ), ), ); bottomPosition = Tween<double>( begin: 0.0, end: 72, ).animate( CurvedAnimation( parent: controller, curve: Interval( 0.0, 0.500, curve: Curves.easeInOutSine, ), ), ); opacity = Tween<double>( begin: 1.0, end: 0.0, ).animate( CurvedAnimation( reverseCurve: Curves.easeIn, parent: controller, curve: Interval( 0.0, 0.500, curve: Curves.ease, ), ), ); borderWidth = Tween<double>(begin: 3.0, end: 7.0).animate( CurvedAnimation( parent: controller, curve: Interval( 0.0, 0.500, curve: Curves.easeInOutSine, ), ), ); return Stack( children: <Widget>[ widget.backgroundWidget, Positioned( bottom: bottomPosition.value, right: position.value, left: position.value, child: Container( width: MediaQuery.of(context).size.width, height: height.value, child: Column( children: <Widget>[ GestureDetector( onVerticalDragEnd: (details) { print("Y: ${details.velocity.pixelsPerSecond.dy}"); if (details.velocity.pixelsPerSecond.dy > 0) { controller.forward(); setState(() { visible = !visible; }); } else if (details.velocity.pixelsPerSecond.dy < 0) { controller.reverse(); setState(() { visible = !visible; }); } }, child: Container( constraints: BoxConstraints(maxHeight: 200, minHeight: 75), color: Colors.teal, width: MediaQuery.of(context).size.width, height: height.value, ), ), Expanded( child: Visibility( maintainState: visible, maintainAnimation: visible, visible: visible, child: Container( color: Colors.blue, ), ), ), ], ), ), ), ], ); } @override Widget build(BuildContext context) { return AnimatedBuilder( builder: _buildAnimation, animation: controller, ); } } class FingerScanAnimationDemo extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.black, body: YoutubePIPAnimation( backgroundWidget: getBackgroundWidget(), ), ); } getBackgroundWidget() { return Container( color: Colors.white, ); } } <|start_filename|>lib/main.dart<|end_filename|> import 'package:flutter/material.dart'; import 'package:youtube_flutter_app/home_page.dart'; import 'package:youtube_flutter_app/state_container.dart'; import 'package:youtube_flutter_app/ui/VideoDetail.dart'; import 'package:youtube_flutter_app/ui/VideoItem.dart'; import 'package:youtube_flutter_app/ui/youtube_pip.dart'; import 'package:youtube_flutter_app/utils/Strings.dart'; void main() => runApp(StateContainer(child: MyApp())); class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter YouTube', debugShowCheckedModeBanner: false, theme: ThemeData( accentColor: Colors.white, primaryColor: Colors.red, scaffoldBackgroundColor: Colors.white, fontFamily: 'WorkSans-Regular', ), home: MyHomePage(), ); } } <|start_filename|>lib/utils/Strings.dart<|end_filename|> class Strings { ///App name static const String appName = "Youtube"; ///routes static const String videosDetailRoute = "/Video Detail"; } <|start_filename|>lib/ui/VideoItem.dart<|end_filename|> import 'package:flutter/material.dart'; import 'package:youtube_flutter_app/state_container.dart'; import 'package:youtube_flutter_app/ui/VideoDetail.dart'; class VideoItem extends StatelessWidget { VideoItem(this.index); final int index; @override Widget build(BuildContext context) { return _buildTiles(context); } Widget _buildTiles(BuildContext context) { final container = StateContainer.of(context); return GestureDetector( onTap: () { container.selectedIndex = -1; container.updateSelectedIndex(index: index); // Navigator.of(context).push( // MaterialPageRoute(builder: (_) => VideoDetail(index.toString()))); }, child: Container( margin: EdgeInsets.symmetric(horizontal: 10, vertical: 8), child: Card( margin: EdgeInsets.zero, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(8), ), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Hero( tag: index.toString(), child: Stack( children: <Widget>[ ClipRRect( borderRadius: BorderRadius.circular(8), child: Container( color: Color.fromRGBO(2, 18, 37, 0.8), child: FlutterLogo( size: 200, ), margin: EdgeInsets.zero, ), ), Icon( Icons.play_circle_outline, size: 64, color: Colors.white, ) ], alignment: Alignment(0, 0), fit: StackFit.passthrough, ), ), Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Padding( padding: const EdgeInsets.only( top: 16, left: 8, right: 8, bottom: 8, ), child: CircleAvatar( child: FlutterLogo(), backgroundColor: Colors.redAccent, ), ), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ Padding( padding: const EdgeInsets.only( top: 16, left: 8, right: 8, ), child: Text( "Avengers Infinity war", overflow: TextOverflow.ellipsis, softWrap: true, maxLines: 2, style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, ), ), ), Padding( padding: const EdgeInsets.only( left: 8, right: 8, bottom: 8, ), child: Text( "Avengers Infinity war", softWrap: true, maxLines: 2, style: TextStyle(fontSize: 12), ), ), ], ), ), ], ), ], ), ), ), ); } }
ibhavikmakwana/youtube_flutter_app
<|start_filename|>package.json<|end_filename|> { "name": "add-event-listener", "version": "1.0.0", "description": "add event listeners in IE and ... everywhere else", "main": "index.js", "scripts": { "test": "testling ." }, "testling": { "files": [ "./test.js" ], "browsers": { "ie": "8..latest", "ff": "12..latest", "chrome": "24..latest", "safari": "4..latest" } }, "repository": { "type": "git", "url": "git://github.com/chrisdickinson/add-event-listener.git" }, "keywords": [ "addEventListener", "attachEvent", "DOMEvent" ], "author": "<NAME> <<EMAIL>> (http://neversaw.us/)", "license": "MIT", "bugs": { "url": "https://github.com/chrisdickinson/add-event-listener/issues" }, "devDependencies": { "browserify": "^16.2.3", "tape": "^4.9.1", "testling": "^1.7.1" } } <|start_filename|>index.js<|end_filename|> 'use strict' addEventListener.removeEventListener = removeEventListener addEventListener.addEventListener = addEventListener module.exports = addEventListener // detect passive events var passive = false try { var opts = Object.defineProperty({}, 'passive', { get: function() { passive = true } }) window.addEventListener('test', null, opts) window.removeEventListener('test', null, opts) } catch(e) { passive = false } var Events = null function addEventListener(el, eventName, listener, useCapture) { Events = Events || ( document.addEventListener ? {add: stdAttach, rm: stdDetach} : {add: oldIEAttach, rm: oldIEDetach} ) return Events.add(el, eventName, listener, useCapture) } function removeEventListener(el, eventName, listener, useCapture) { Events = Events || ( document.addEventListener ? {add: stdAttach, rm: stdDetach} : {add: oldIEAttach, rm: oldIEDetach} ) return Events.rm(el, eventName, listener, useCapture) } function stdAttach(el, eventName, listener, useCapture) { el.addEventListener(eventName, listener, passive ? useCapture : !!useCapture) } function stdDetach(el, eventName, listener, useCapture) { el.removeEventListener(eventName, listener, passive ? useCapture : !!useCapture) } function oldIEAttach(el, eventName, listener, useCapture) { if(useCapture) { throw new Error('cannot useCapture in oldIE') } el.attachEvent('on' + eventName, listener) } function oldIEDetach(el, eventName, listener, useCapture) { el.detachEvent('on' + eventName, listener) }
chrisdickinson/add-event-listener
<|start_filename|>build/UpdateHeaders.bat<|end_filename|> @ECHO OFF PowerShell.exe -file build.ps1 -target=UpdateHeaders PAUSE
dipidoo/UWPCommunityToolkit
<|start_filename|>labs/lab1/os/src/interrupt/interrupt.asm<|end_filename|> # 宏:将寄存器存到栈上 .macro SAVE reg, offset sd \reg, \offset*8(sp) .endm # 宏:将寄存器从栈中取出 .macro LOAD reg, offset ld \reg, \offset*8(sp) .endm .section .text .globl __interrupt # 进入中断 # 保存 Context 并且进入 rust 中的中断处理函数 interrupt::handler::handle_interrupt() __interrupt: # 在栈上开辟 Context 所需的空间 addi sp, sp, -34*8 # 保存通用寄存器,除了 x0(固定为 0) SAVE x1, 1 # 将原来的 sp(sp 又名 x2)写入 2 位置 addi x1, sp, 34*8 SAVE x1, 2 # 其他通用寄存器 SAVE x3, 3 SAVE x4, 4 SAVE x5, 5 SAVE x6, 6 SAVE x7, 7 SAVE x8, 8 SAVE x9, 9 SAVE x10, 10 SAVE x11, 11 SAVE x12, 12 SAVE x13, 13 SAVE x14, 14 SAVE x15, 15 SAVE x16, 16 SAVE x17, 17 SAVE x18, 18 SAVE x19, 19 SAVE x20, 20 SAVE x21, 21 SAVE x22, 22 SAVE x23, 23 SAVE x24, 24 SAVE x25, 25 SAVE x26, 26 SAVE x27, 27 SAVE x28, 28 SAVE x29, 29 SAVE x30, 30 SAVE x31, 31 # 取出 CSR 并保存 csrr s1, sstatus csrr s2, sepc SAVE s1, 32 SAVE s2, 33 # 调用 handle_interrupt,传入参数 # context: &mut Context mv a0, sp # scause: Scause csrr a1, scause # stval: usize csrr a2, stval jal handle_interrupt .globl __restore # 离开中断 # 从 Context 中恢复所有寄存器,并跳转至 Context 中 sepc 的位置 __restore: # 恢复 CSR LOAD s1, 32 LOAD s2, 33 csrw sstatus, s1 csrw sepc, s2 # 恢复通用寄存器 LOAD x1, 1 LOAD x3, 3 LOAD x4, 4 LOAD x5, 5 LOAD x6, 6 LOAD x7, 7 LOAD x8, 8 LOAD x9, 9 LOAD x10, 10 LOAD x11, 11 LOAD x12, 12 LOAD x13, 13 LOAD x14, 14 LOAD x15, 15 LOAD x16, 16 LOAD x17, 17 LOAD x18, 18 LOAD x19, 19 LOAD x20, 20 LOAD x21, 21 LOAD x22, 22 LOAD x23, 23 LOAD x24, 24 LOAD x25, 25 LOAD x26, 26 LOAD x27, 27 LOAD x28, 28 LOAD x29, 29 LOAD x30, 30 LOAD x31, 31 # 恢复 sp(又名 x2)这里最后恢复是为了上面可以正常使用 LOAD 宏 LOAD x2, 2 sret <|start_filename|>labs/lab1/os/src/entry.asm<|end_filename|> # 操作系统启动时所需的指令以及字段 # # 我们在 linker.ld 中将程序入口设置为了 _start,因此在这里我们将填充这个标签 # 它将会执行一些必要操作,然后跳转至我们用 rust 编写的入口函数 # # 关于 RISC-V 下的汇编语言,可以参考 https://github.com/riscv/riscv-asm-manual/blob/master/riscv-asm.md .section .text.entry .globl _start # 目前 _start 的功能:将预留的栈空间写入 $sp,然后跳转至 rust_main _start: la sp, boot_stack_top call rust_main # 回忆:bss 段是 ELF 文件中只记录长度,而全部初始化为 0 的一段内存空间 # 这里声明字段 .bss.stack 作为操作系统启动时的栈 .section .bss.stack .global boot_stack boot_stack: # 16K 启动栈大小 .space 4096 * 16 .global boot_stack_top boot_stack_top: # 栈结尾 <|start_filename|>labs/lab3_practice/user/Makefile<|end_filename|> .PHONY: build TARGET := riscv64imac-unknown-none-elf MODE := debug # 用户程序目录 SRC_DIR := src/bin # 编译后执行文件目录 TARGET_DIR := target/$(TARGET)/$(MODE) # 用户程序源文件 SRC_FILES := $(wildcard $(SRC_DIR)/*.rs) # 根据源文件取得编译后的执行文件 BIN_FILES := $(patsubst $(SRC_DIR)/%.rs, $(TARGET_DIR)/%, $(SRC_FILES)) OUT_DIR := build/disk IMG_FILE := build/raw.img QCOW_FILE := build/disk.img # 安装 rcore-fs-fuse 工具 dependency: ifeq ($(shell which rcore-fs-fuse),) @echo Installing rcore-fs-fuse @cargo install rcore-fs-fuse --git https://github.com/rcore-os/rcore-fs endif # 编译、打包、格式转换、预留空间 build: dependency @cargo build @echo Targets: $(patsubst $(SRC_DIR)/%.rs, %, $(SRC_FILES)) @rm -rf $(OUT_DIR) @mkdir -p $(OUT_DIR) @cp $(BIN_FILES) $(OUT_DIR) @dd if=/dev/zero of=$(OUT_DIR)/SWAP_FILE bs=1M count=16 @rcore-fs-fuse --fs sfs $(IMG_FILE) $(OUT_DIR) zip @qemu-img convert -f raw $(IMG_FILE) -O qcow2 $(QCOW_FILE) @qemu-img resize $(QCOW_FILE) +1G clean: @cargo clean @rm -rf $(OUT_DIR) $(IMG_FILE) $(QCOW_FILE) <|start_filename|>labs/lab6/os/src/entry.asm<|end_filename|> # 操作系统启动时所需的指令以及字段 # # 我们在 linker.ld 中将程序入口设置为了 _start,因此在这里我们将填充这个标签 # 它将会执行一些必要操作,然后跳转至我们用 rust 编写的入口函数 # # 关于 RISC-V 下的汇编语言,可以参考 https://github.com/riscv/riscv-asm-manual/blob/master/riscv-asm.md # %hi 表示取 [12,32) 位,%lo 表示取 [0,12) 位 .section .text.entry .globl _start # 目前 _start 的功能:将预留的栈空间写入 $sp,然后跳转至 rust_main _start: # 通过线性映射关系计算 boot_page_table 的物理页号 lui t0, %hi(boot_page_table) li t1, 0xffffffff00000000 sub t0, t0, t1 srli t0, t0, 12 # 8 << 60 是 satp 中使用 Sv39 模式的记号 li t1, (8 << 60) or t0, t0, t1 # 写入 satp 并更新 TLB csrw satp, t0 sfence.vma # 加载栈的虚拟地址 lui sp, %hi(boot_stack_top) addi sp, sp, %lo(boot_stack_top) # 跳转至 rust_main # 这里同时伴随 hart 和 dtb_pa 两个指针的传入(是 OpenSBI 帮我们完成的) lui t0, %hi(rust_main) addi t0, t0, %lo(rust_main) jr t0 # 回忆:bss 段是 ELF 文件中只记录长度,而全部初始化为 0 的一段内存空间 # 这里声明字段 .bss.stack 作为操作系统启动时的栈 .section .bss.stack .global boot_stack boot_stack: # 16K 启动栈大小 .space 4096 * 16 .global boot_stack_top boot_stack_top: # 栈结尾 # 初始内核映射所用的页表 .section .data .align 12 .global boot_page_table boot_page_table: # .8byte表示长度为8个字节的整数 .8byte 0 .8byte 0 # 第 2 项:0x8000_0000 -> 0x8000_0000,0xcf 表示 VRWXAD 均为 1 .8byte (0x80000 << 10) | 0xcf .zero 505 * 8 # 第 508 项:0xffff_ffff_0000_0000 -> 0x0000_0000,0xcf 表示 VRWXAD 均为 1 .8byte (0x00000 << 10) | 0xcf .8byte 0 # 第 510 项:0xffff_ffff_8000_0000 -> 0x8000_0000,0xcf 表示 VRWXAD 均为 1 .8byte (0x80000 << 10) | 0xcf .8byte 0 <|start_filename|>part1-exercises-for-rust/hardways/leetcode-set-matrix-zeroes/solution.c<|end_filename|> void setZeroes(int** matrix, int matrixSize, int* matrixColSize){ int i, j, k; int rRow = -1; for (i = 0; i < matrixSize; i++) { for (j = 0; j < matrixColSize[i]; j++) { if (matrix[i][j] == 0) { for (k = 0; k < matrixColSize[i]; k++) { if (matrix[i][k] == 0) { matrix[i][k] = 1; } else { matrix[i][k] = 0; } } if (rRow != -1) { for (k = 0; k < matrixColSize[rRow]; k++) { matrix[i][k] = matrix[rRow][k] | matrix[i][k]; matrix[rRow][k] = 0; } } rRow = i; break; } } } if (rRow != -1) { for (j = 0; j < matrixColSize[rRow]; j++) { if (matrix[rRow][j] == 1) { for (k = 0; k < matrixSize; k++) { matrix[k][j] = 0; } } } } } <|start_filename|>part1-exercises-for-rust/hardways/leetcode-best-time-to-buy-and-sell-stock/solution.c<|end_filename|> int maxProfit(int* prices, int pricesSize){ int sum = 0; int max = 0; for(int i=0;i<pricesSize-1;++i){ prices[i] = prices[i+1] - prices[i]; } for(int i=0;i<pricesSize-1;++i){ sum = sum + prices[i]; if(sum < 0){ sum = 0; }else if(sum>max) { max = sum; } } return max; } <|start_filename|>labs/lab5/Makefile<|end_filename|> run: @make -C os run debug: @make -C os debug clean: @make -C os clean fmt: @cd os && cargo fmt <|start_filename|>part1-exercises-for-rust/hardways/leetcode-remove-element/solution.c<|end_filename|> int removeElement(int* nums, int numsSize, int val){ int size = 0; int i = 0; for (i = 0; i <= numsSize - 1; i++) { if (nums[i] != val) // ignore the same { nums[size++] = nums[i]; } } return size; } <|start_filename|>part1-exercises-for-rust/hardways/leetcode-binary-tree-inorder-traversal/solution.c<|end_filename|> int i=0; struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; }; void inorder(struct TreeNode* root,int* array){ if(!root) return; inorder(root->left,array); array[i++] = root->val; inorder(root->right,array); } int* inorderTraversal(struct TreeNode* root, int* returnSize){ int *a = malloc(sizeof(int)*10000); i = 0; inorder(root,a); *returnSize = i; return a; } <|start_filename|>part1-exercises-for-rust/hardways/leetcode-friend-circles/solution.c<|end_filename|> void deep(int** M, int MSize, int *visited, int index) { for (int i = 0; i < MSize; i++) { if(M[index][i] == 1 && visited[i] == 0) { visited[i] = 1; deep(M, MSize, visited, i); } } } int findCircleNum(int** M, int MSize, int* MColSize){ int visited[MSize]; memset(visited, 0, sizeof(visited)); int count = 0; for (int i = 0; i < MSize; i++) { if (visited[i] == 0) { deep(M, MSize, visited, i); count++; } } return count; } <|start_filename|>part1-exercises-for-rust/hardways/leetcode-game-of-life/solution.c<|end_filename|> void gameOfLife(int** board, int boardSize, int* boardColSize){ int board1[100][100]; for(int i=0;i<boardSize;++i){ for(int j=0;j<boardColSize[0];++j){ board1[i][j] = board[i][j]; } } for(int i=0;i<boardSize;++i){ for(int j=0;j<boardColSize[0];++j){ int count = 0; if( i > 0){ if( j > 0){ count += board1[i-1][j-1]; } if (j < boardColSize[0] -1) { count += board1[i-1][j+1]; } count += board1[i-1][j]; } if (i < boardSize - 1) { if (j > 0){ count += board1[i+1][j-1]; } if (j < boardColSize[0] -1) { count += board1[i+1][j+1]; } count += board1[i+1][j]; } if (j > 0){ count += board1[i][j-1]; } if (j < boardColSize[0] -1) { count += board1[i][j+1]; } if (count < 2 || count > 3){ board[i][j] = 0; }else if (count == 3){ board[i][j] = 1; } } } } <|start_filename|>part1-exercises-for-rust/hardways/leetcode-maximum-subarray/solution.c<|end_filename|> int maxSubArray(int* nums, int numsSize){ int subsum = 0, maxsum = -2147483648; for(int i = 0; i < numsSize; i ++) { subsum += nums[i]; if(subsum > maxsum) { maxsum = subsum; } if(subsum < 0) subsum = 0; } return maxsum; } <|start_filename|>part1-exercises-for-rust/hardways/leetcode-maximum-depth-of-binary-tree/solution.c<|end_filename|> struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; }; int maxDepth(struct TreeNode* root){ if(root==0) return 0; int height = 1; if(root->left) height += maxDepth(root->left); if(root->right){ int a = maxDepth(root->right)+1; height = a > height? a:height; } return height; } <|start_filename|>labs/lab2/Makefile<|end_filename|> run: @make -C os run clean: @make -C os clean fmt: @cd os && cargo fmt <|start_filename|>part1-exercises-for-rust/hardways/leetcode-longest-consecutive-sequence/solution.c<|end_filename|> #include<stdio.h> struct MyNode{ int data; struct MyNode* next; }; struct HashTbl{ int TableSize; struct MyNode** TheLists; }; int NextPrime(int n) { if(n%2==0) n++; for(;;n+=2) { for(int i=3;i<=sqrt(n);i++) if(n%i==0) goto out; return n; out:; } } int Hash(int key,int TableSize) { int ret=abs(key)%TableSize; return ret; } struct HashTbl* InitializeHashTbl(int TableSize) { struct HashTbl* H=(struct HashTbl*)malloc(sizeof(struct HashTbl)); H->TableSize=NextPrime(TableSize); H->TheLists=malloc(sizeof(struct MyNode*)*H->TableSize); for(int i=0;i<H->TableSize;i++) { H->TheLists[i]=malloc(sizeof(struct MyNode)); H->TheLists[i]->next=NULL; H->TheLists[i]->data=-1; } return H; } struct MyNode* Find(int key,struct HashTbl* H) { struct MyNode* p,*l; l=H->TheLists[Hash(key,H->TableSize)]; p=l->next; while(p!=NULL&&p->data!=key) p=p->next; return p; } void Insert(int key,struct HashTbl* H) { struct MyNode* Pos,*l; Pos=Find(key,H); if(Pos==NULL) { struct MyNode* NewCell=(struct MyNode*)malloc(sizeof(struct MyNode)); l=H->TheLists[Hash(key,H->TableSize)]; NewCell->next=l->next; l->next=NewCell; NewCell->data=key; } } void FreeHashTbl(struct HashTbl* H) { struct MyNode* temp,*deleteNode; for(int i=0;i<H->TableSize;i++) { temp=H->TheLists[i]; while(temp!=NULL) { deleteNode=temp; temp=temp->next; free(deleteNode); } } free(H); } int longestConsecutive(int* nums, int numsSize){ int max=0; struct HashTbl* HashForNums=InitializeHashTbl(numsSize); for(int i=0;i<numsSize;i++) { struct MyNode* findNode=Find(nums[i],HashForNums); if(findNode==NULL) Insert(nums[i],HashForNums); } for(int i=0;i<numsSize;i++) { if(nums[i]==-2147483647 || Find(nums[i]-1,HashForNums)==NULL) { int curMax=0,temp=0; while(Find(nums[i]+temp,HashForNums)!=NULL) { curMax++; temp++; } max=fmax(curMax,max); } } return max; }
yunwei37/os-summer-of-code-daily
<|start_filename|>UI/ViewModels/TokenTypeViewModel.cs<|end_filename|> using System.Collections.Generic; using ZSpitz.Util.Wpf; using static ZSpitz.Util.Functions; namespace ParseTreeVisualizer { public class TokenTypeViewModel : Selectable<KeyValuePair<int,string>> { public int Index { get; } public string Text { get; } public TokenTypeViewModel(int index, string text): this(KVP(index,text)) { } public TokenTypeViewModel(KeyValuePair<int, string> tokenType) : base(tokenType) => (Index, Text) = (tokenType.Key, tokenType.Value); } } <|start_filename|>Visualizer/Visualizer.cs<|end_filename|> using ParseTreeVisualizer.Serialization; using Periscope; using Periscope.Debuggee; using System.Diagnostics; [assembly: DebuggerVisualizer( visualizer: typeof(ParseTreeVisualizer.Visualizer), visualizerObjectSource: typeof(ParseTreeVisualizer.VisualizerDataObjectSource), Target = typeof(Antlr4.Runtime.RuleContext), #if ANTLR_LEGACY Description = "ANTLR4 ParseTree Visualizer (Legacy)")] #else Description = "ANTLR4 ParseTree Visualizer")] #endif [assembly: DebuggerVisualizer( visualizer: typeof(ParseTreeVisualizer.Visualizer), visualizerObjectSource: typeof(ParseTreeVisualizer.VisualizerDataObjectSource), Target = typeof(string), #if ANTLR_LEGACY Description = "ANTLR4 ParseTree Visualizer (Legacy)")] #else Description = "ANTLR4 ParseTree Visualizer")] #endif [assembly: DebuggerVisualizer( visualizer: typeof(ParseTreeVisualizer.Visualizer), visualizerObjectSource: typeof(ParseTreeVisualizer.VisualizerDataObjectSource), Target = typeof(Antlr4.Runtime.BufferedTokenStream), #if ANTLR_LEGACY Description = "ANTLR4 ParseTree Visualizer (Legacy)")] #else Description = "ANTLR4 ParseTree Visualizer")] #endif namespace ParseTreeVisualizer { public abstract class VisualizerWindowBase : VisualizerWindowBase<VisualizerWindow, Config> { }; public class Visualizer : VisualizerBase<VisualizerWindow, Config> { static Visualizer() => SubfolderAssemblyResolver.Hook( #if ANTLR_LEGACY "ParseTreeVisualizer.Legacy" #else "ParseTreeVisualizer.Standard" #endif ); public Visualizer() : base(new GithubProjectInfo("zspitz", "antlr4parsetreevisualizer")) { } } } <|start_filename|>UI/SettingsControl.xaml.cs<|end_filename|> namespace ParseTreeVisualizer { public partial class SettingsControl { public SettingsControl() => InitializeComponent(); } } <|start_filename|>UI/ViewModels/ParseTreeNodeViewModel.cs<|end_filename|> using ParseTreeVisualizer.Serialization; using System.Collections.ObjectModel; using System.Linq; using System.Windows.Input; using ZSpitz.Util; using ZSpitz.Util.Wpf; namespace ParseTreeVisualizer { public class ParseTreeNodeViewModel : Selectable<ParseTreeNode> { private static readonly RelayCommand subtreeExpand = new( prm => ((ParseTreeNodeViewModel)prm).SetSubtreeExpanded(true) ); private static readonly RelayCommand subtreeCollapse = new( prm => ((ParseTreeNodeViewModel)prm).SetSubtreeExpanded(false) ); public ParseTreeNodeViewModel( ParseTreeNode model, ICommand? openInNewWindow = null, RelayCommand? copyWatchExpression = null, RelayCommand? setAsRootNode = null ) : base(model) { Children = ( model?.Children.Select(x => new ParseTreeNodeViewModel(x,openInNewWindow, copyWatchExpression, setAsRootNode)) ?? Enumerable.Empty<ParseTreeNodeViewModel>() ).ToList().AsReadOnly(); OpenInNewWindow = openInNewWindow; CopyWatchExpression = copyWatchExpression; SetAsRootNode = setAsRootNode; } public ReadOnlyCollection<ParseTreeNodeViewModel> Children { get; } public void ClearSelection() { IsSelected = false; foreach (var child in Children) { child.ClearSelection(); } } private bool isExpanded; public bool IsExpanded { get => isExpanded; set => NotifyChanged(ref isExpanded, value); } public void SetSubtreeExpanded(bool expand) { IsExpanded = expand; Children.ForEach(x => x.SetSubtreeExpanded(expand)); } public ICommand? OpenInNewWindow { get; private set; } public RelayCommand? CopyWatchExpression { get; private set; } public string? WatchFormatString => "{0}" + Model.Path?.Split('.').Joined("", x => $".GetChild({x})"); public RelayCommand SubtreeExpand => subtreeExpand; public RelayCommand SubtreeCollapse => subtreeCollapse; public RelayCommand? SetAsRootNode { get; } } } <|start_filename|>Serialization/Token.cs<|end_filename|> using Antlr4.Runtime; using Antlr4.Runtime.Tree; using System; using System.Collections.Generic; using ZSpitz.Util; namespace ParseTreeVisualizer.Serialization { [Serializable] public class Token { public int Index { get; } public string TokenType { get; } public int TokenTypeID { get; } public int Line { get; } public int Col { get; } public string Text { get; } public bool IsError { get; } public (int start, int stop) Span { get; } public bool IsWhitespace { get; } public Token(IToken itoken, Dictionary<int, string>? tokenTypeMapping) { Index = itoken.TokenIndex; TokenTypeID = itoken.Type; Line = itoken.Line; Col = itoken.Column; Text = itoken.Text.ToVerbatimString("C#")[1..^1]; Span = (itoken.StartIndex, itoken.StopIndex); IsWhitespace = itoken.Text.IsNullOrWhitespace(); var tokenType = ""; TokenType = tokenTypeMapping?.TryGetValue(TokenTypeID, out tokenType) ?? false ? tokenType : $"{TokenTypeID}"; } public Token(TerminalNodeImpl terminalNode, Dictionary<int, string> tokenTypeMapping) : this(terminalNode.Payload, tokenTypeMapping) { if (terminalNode is ErrorNodeImpl) { IsError = true; } } public bool ShowToken(Config config) { if (!config.HasTokenListFilter()) { return true; } var showToken = IsError ? config.ShowErrorTokens : IsWhitespace ? config.ShowWhitespaceTokens : config.ShowTextTokens; showToken &= config.SelectedTokenTypes.None() || TokenTypeID.In(config.SelectedTokenTypes); return showToken; } } } <|start_filename|>UI/ViewModels/VisualizerDataViewModel.cs<|end_filename|> using System; using System.Collections; using System.Collections.ObjectModel; using System.Linq; using ZSpitz.Util.Wpf; using ParseTreeVisualizer.Serialization; using ZSpitz.Util; using System.Windows.Input; using ParseTreeVisualizer.UI; namespace ParseTreeVisualizer { public class VisualizerDataViewModel : ViewModelBase<VisualizerData> { private int sourceSelectionStart; public int SourceSelectionStart { get => sourceSelectionStart; set => NotifyChanged(ref sourceSelectionStart, value); } private int sourceSelectionLength; public int SourceSelectionLength { get => sourceSelectionLength; set => NotifyChanged(ref sourceSelectionLength, value); } private int sourceSelectionEnd => sourceSelectionLength == 0 ? sourceSelectionStart : sourceSelectionStart + sourceSelectionLength - 1; private TokenViewModel? firstSelectedToken; public TokenViewModel? FirstSelectedToken => firstSelectedToken; public ParseTreeNodeViewModel? Root { get; } public ReadOnlyCollection<TokenViewModel>? Tokens { get; } public VisualizerDataViewModel(VisualizerData visualizerData, ICommand? openInNewWindow, RelayCommand? copyWatchExpression, RelayCommand? setAsRootNode) : base(visualizerData) { if (visualizerData.Root is not null) { Root = new ParseTreeNodeViewModel(visualizerData.Root, openInNewWindow, copyWatchExpression, setAsRootNode); } Tokens = visualizerData.Tokens?.OrderBy(x => x.Index).Select(x => { var vm = new TokenViewModel(x); vm.PropertyChanged += (s, e) => { if (e.PropertyName != nameof(vm.IsSelected)) { return; } if (vm.IsSelected) { if (firstSelectedToken is null || firstSelectedToken.Model.Index > vm.Model.Index) { NotifyChanged(ref firstSelectedToken, vm, nameof(FirstSelectedToken)); } } else { if (firstSelectedToken != null && firstSelectedToken.Model.Index == vm.Model.Index) { var firstSelected = Tokens.Where(x => x.IsSelected).OrderBy(x => x.Model.Index).FirstOrDefault(); NotifyChanged(ref firstSelectedToken, firstSelected, nameof(FirstSelectedToken)); } } }; return vm; }).ToList().AsReadOnly(); if (!(Root is null)) { if (visualizerData.Config.HasTreeFilter()) { Root.SetSubtreeExpanded(true); } else { Root.IsExpanded = true; } } ChangeSelection = new RelayCommand(sender => updateSelection(sender)); } private bool inUpdateSelection; private void updateSelection(object parameter) { if (inUpdateSelection) { return; } inUpdateSelection = true; // sender will be either VisualizerDataViewModel, treenode viewmodel, or token viewmodel // HACK the type of the sender also tells us which part of the viewmodel has been selected -- source, tree, or tokens (int start, int end)? charSpan = null; string source; if (parameter == this) { // textbox's data context charSpan = (sourceSelectionStart + Model.SourceOffset, sourceSelectionEnd + Model.SourceOffset); source = "Source"; } else if (parameter is ParseTreeNodeViewModel selectedNode) { // treeview.SelectedItem charSpan = selectedNode.Model?.CharSpan; source = "Root"; } else if (parameter is IList) { // selected items in datagrid charSpan = Tokens?.SelectionCharSpan(); source = "Tokens"; } else if (parameter is null) { inUpdateSelection = false; return; } else { throw new Exception("Unknown sender"); } var (start, end) = (charSpan ?? (-1, -1)); if (source != "Source") { if (charSpan != null && charSpan != (-1, -1)) { SourceSelectionStart = start - Model.SourceOffset; SourceSelectionLength = end - start + 1; } else { SourceSelectionLength = 0; SourceSelectionStart = 0; } } if (source != "Tokens" && !(Tokens is null)) { if (charSpan == null) { Tokens.ForEach(x => x.IsSelected = false); } else { Tokens.ForEach(x => x.IsSelected = x.Model.Span.start <= end && x.Model.Span.stop >= start ); } } if (source != "Root" && !(Root?.Model is null)) { Root.ClearSelection(); var selectedNode = Root; // returns true if the node encompasses the selection bool matcher(ParseTreeNodeViewModel x) { var (nodeStart, nodeEnd) = x.Model.CharSpan; return start >= nodeStart && end <= nodeEnd; } if (matcher(selectedNode)) { while (true) { var nextChild = selectedNode.Children.SingleOrDefaultExt(matcher); if (nextChild is null) { break; } selectedNode = nextChild; selectedNode.IsExpanded = true; } selectedNode.IsSelected = true; } } inUpdateSelection = false; } // TOOD move filtering to here public RelayCommand ChangeSelection { get; } public string WindowTitle { get { var (lexer, parser, rule) = Model.Config; return new[] { ("Lexer", lexer ), ("Parser", parser ), ("Rule context", rule ) } .WhereT((name, val) => val is not null) .JoinedT(" / ", (name, val) => $"{name}: {val}"); } } } } <|start_filename|>Serialization/PropertyValue.cs<|end_filename|> using System; using System.Reflection; using static ZSpitz.Util.Functions; namespace ParseTreeVisualizer.Serialization { [Serializable] public class PropertyValue { public bool Custom { get; } public string Key { get; } public string? Value { get; } public PropertyValue(object instance, PropertyInfo prp) { if (prp is null) { throw new ArgumentNullException(nameof(prp)); } Key = prp.Name; // null values map to null strings // exceptions map to <...> delineated strings // other values map to result of RenderLiteral object? value = null; try { value = prp.GetValue(instance); } catch (Exception e) { Value = $"<{e.GetType()}: {e.Message}>"; } if (value is { }) { Value = StringValue(value, "C#"); } Custom = !prp.DeclaringType?.Namespace?.StartsWith("Antlr4", StringComparison.Ordinal) ?? false; } } } <|start_filename|>Debuggee/VisualizerDataObjectSource.cs<|end_filename|> using System.Reflection; using ParseTreeVisualizer.Serialization; using Periscope.Debuggee; namespace ParseTreeVisualizer { public class VisualizerDataObjectSource : VisualizerObjectSourceBase<object, Config> { static VisualizerDataObjectSource() => SubfolderAssemblyResolver.Hook( #if ANTLR_LEGACY "ParseTreeVisualizer.Legacy" #else "ParseTreeVisualizer.Standard" #endif ); public override object GetResponse(object target, Config config) => new VisualizerData(target, config); public override string GetConfigKey(object target) => target is string ? "" : target.GetType().Assembly.GetName().Name; } } <|start_filename|>UI/Extensions.cs<|end_filename|> using ParseTreeVisualizer.Serialization; using System; using System.Collections.Generic; using ZSpitz.Util.Wpf; namespace ParseTreeVisualizer.UI { public static class Extensions { public static (int start, int end)? SelectionCharSpan(this IEnumerable<Selectable<Token>> tokens) { int? startChar = null; int? endChar = null; // TODO replace with tokens.Aggregate? foreach (var vm in tokens) { var token = vm.Model; if (vm.IsSelected) { startChar = startChar == null ? token.Span.start : Math.Min(startChar.Value, token.Span.start); endChar = endChar == null ? token.Span.stop : Math.Max(endChar.Value, token.Span.stop); } } return startChar.HasValue && endChar.HasValue ? (startChar.Value, endChar.Value) : null; } } } <|start_filename|>Serialization/ClassInfo.cs<|end_filename|> using Antlr4.Runtime; using Antlr4.Runtime.Tree; using System; using System.CodeDom.Compiler; using System.Collections.ObjectModel; using System.Linq; using System.Reflection; using ZSpitz.Util; namespace ParseTreeVisualizer.Serialization { [Serializable] public class ClassInfo { public static readonly ClassInfo None = new("(None)"); public string Name { get; } public string? Namespace { get; } public string? Assembly { get; } public string? Antlr { get; } // Runtime - in Antlr.Runtime, <number> - version public string? FullName { get; } public string? RuleName { get; } public int? RuleID { get; } public bool HasRelevantConstructor { get; } = false; public ReadOnlyCollection<string>? MethodNames { get; } private ClassInfo(string name) => Name = name; public ClassInfo(Type t, string? ruleName = null, int? ruleID = null, bool loadMethodNames = false) { if (t is null) { throw new ArgumentNullException(nameof(t)); } Name = t.Name; Namespace = t.Namespace; Assembly = t.Assembly.Location; if (t.Assembly == typeof(IParseTree).Assembly) { Antlr = "Runtime"; } else if (t.GetCustomAttribute<GeneratedCodeAttribute>() is GeneratedCodeAttribute attr) { Antlr = attr.Version; } FullName = t.FullName; RuleName = ruleName.IsNullOrWhitespace() ? null : ruleName; RuleID = ruleID; HasRelevantConstructor = t.InheritsFromOrImplements<Lexer>() ? t.GetConstructor(new[] { typeof(AntlrInputStream) }) is not null : t.InheritsFromOrImplements<Parser>() ? t.GetConstructor(new[] { typeof(CommonTokenStream) }) is not null : false; if (loadMethodNames) { MethodNames = t.GetMethods() .Where(x => !x.IsSpecialName && x.ReturnType.InheritsFromOrImplements<ParserRuleContext>()) .Select(x => x.Name) .Where(x => x != "GetInvokingContext") .Ordered() .ToList() .AsReadOnly(); } } public override string ToString() => FullName ?? Name; } } <|start_filename|>Serialization/Enums.cs<|end_filename|> namespace ParseTreeVisualizer.Serialization { public enum TreeNodeType { RuleContext, Token, ErrorToken, WhitespaceToken, Placeholder } public enum FilterStates { NotMatched, Matched, DescendantMatched } } <|start_filename|>Serialization/ParseTreeNode.cs<|end_filename|> using Antlr4.Runtime; using Antlr4.Runtime.Tree; using System; using System.Collections.Generic; using System.Linq; using ZSpitz.Util; namespace ParseTreeVisualizer.Serialization { [Serializable] public class ParseTreeNode { public static ParseTreeNode GetPlaceholder(ParseTreeNode? actualRoot) => actualRoot is null ? throw new ArgumentNullException(nameof(actualRoot)) : new("(parent nodes)", TreeNodeType.Placeholder, new List<ParseTreeNode> { actualRoot }, actualRoot.CharSpan); public string? Caption { get; } public List<PropertyValue>? Properties { get; } public List<ParseTreeNode> Children { get; } public (int startTokenIndex, int endTokenIndex) TokenSpan { get; } public (int startChar, int endChar) CharSpan { get; } public TreeNodeType? NodeType { get; } public FilterStates? FilterState { get; } public string? Path { get; } private ParseTreeNode(string caption, TreeNodeType nodeType, List<ParseTreeNode> children, (int startChar, int endChar) charSpan) { Caption = caption; NodeType = nodeType; Children = children; CharSpan = charSpan; } public ParseTreeNode(IParseTree tree, List<Token> tokens, string[] ruleNames, Dictionary<int, string> tokenTypeMapping, Config config, Dictionary<Type, (string? caption, int? index)> ruleMapping, string? path) { if (tree is null) { throw new ArgumentNullException(nameof(tree)); } if (ruleMapping is null) { throw new ArgumentNullException(nameof(ruleMapping)); } if (tokens is null) { throw new ArgumentNullException(nameof(tokens)); } if (config is null) { throw new ArgumentNullException(nameof(config)); } var type = tree.GetType(); if (tree is ParserRuleContext ruleContext) { NodeType = TreeNodeType.RuleContext; var caption = type.Name; if (!ruleMapping.TryGetValue(type, out var x)) { var ruleIndex = (int)(type.GetProperty("RuleIndex")?.GetValue(tree) ?? -1); if (ruleNames.TryGetValue(ruleIndex, out caption)) { ruleMapping[type] = (caption, ruleIndex); } else { caption = type.Name; ruleMapping[type] = (null, null); } } else { caption = x.caption; } Caption = caption; CharSpan = (ruleContext.Start.StartIndex, ruleContext.Stop?.StopIndex ?? int.MaxValue); } else if (tree is TerminalNodeImpl terminalNode) { var token = new Token(terminalNode, tokenTypeMapping); if (token.IsError) { Caption = token.Text; NodeType = TreeNodeType.ErrorToken; } else { Caption = $"\"{token.Text}\""; NodeType = token.IsWhitespace ? TreeNodeType.WhitespaceToken : TreeNodeType.Token; } CharSpan = token.Span; if (token.ShowToken(config)) { tokens.Add(token); } } Path = path; var pathDelimiter = path.IsNullOrWhitespace() ? "" : "."; Properties = type.GetProperties().OrderBy(x => x.Name).Select(prp => new PropertyValue(tree, prp)).ToList(); Children = tree.Children() .Select((x, index) => new ParseTreeNode(x, tokens, ruleNames, tokenTypeMapping, config, ruleMapping, $"{path}{pathDelimiter}{index}")) .Where(x => x.FilterState != FilterStates.NotMatched) // intentionally doesn't exclude null .ToList(); TokenSpan = (tree.SourceInterval.a, tree.SourceInterval.b); var matched = true; if (config.HasTreeFilter()) { matched = NodeType switch { TreeNodeType.RuleContext => config.ShowRuleContextNodes && ( config.SelectedRuleContexts.None() || type.FullName.In(config.SelectedRuleContexts) ), TreeNodeType.ErrorToken => config.ShowErrorTokens, TreeNodeType.WhitespaceToken => config.ShowTreeWhitespaceTokens, _ => config.ShowTreeTextTokens }; FilterState = matched ? FilterStates.Matched : (Children.Any(x => x.FilterState.In(FilterStates.Matched, FilterStates.DescendantMatched)) ? FilterStates.DescendantMatched : FilterStates.NotMatched); } var toPromote = Children .Select((child, index) => (grandchild: child.Children.SingleOrDefaultExt(x => x.FilterState.In(FilterStates.Matched, FilterStates.DescendantMatched)), index)) .WhereT((grandchild, index) => grandchild != null) .ToList(); foreach (var (grandchild, index) in toPromote) { Children[index] = grandchild; } } public string Stringify(int indentLevel = 0) { var ret = new string(' ', indentLevel * 4) + Caption; foreach (var child in Children) { ret += "\n" + child.Stringify(indentLevel + 1); } return ret; } } } <|start_filename|>UI/ParserRuleDisplayNameSelector.cs<|end_filename|> using System.Windows; using System.Windows.Controls; using ParseTreeVisualizer.Serialization; namespace ParseTreeVisualizer { public class ParserRuleDisplayNameSelector : DataTemplateSelector { public DataTemplate? RuleNameTemplate { get; set; } public DataTemplate? TypeNameTemplate { get; set; } public override DataTemplate? SelectTemplate(object item, DependencyObject container) => (item as ClassInfo)?.RuleName == null ? TypeNameTemplate : RuleNameTemplate; } } <|start_filename|>Serialization/VisualizerData.cs<|end_filename|> using Antlr4.Runtime; using Antlr4.Runtime.Tree; using System; using System.Collections.Generic; using System.Linq; using static System.Linq.Enumerable; using ZSpitz.Util; using static ZSpitz.Util.Functions; namespace ParseTreeVisualizer.Serialization { [Serializable] public class VisualizerData { public string Source { get; } public Config Config { get; } public ParseTreeNode? Root { get; } public List<Token>? Tokens { get; } public int SourceOffset { get; } public List<ClassInfo> AvailableParsers { get; } = new List<ClassInfo>(); public List<ClassInfo> AvailableLexers { get; } = new List<ClassInfo>(); public List<string> AssemblyLoadErrors { get; } = new List<string>(); public Dictionary<int, string>? TokenTypeMapping { get; private set; } public List<ClassInfo>? UsedRuleContexts { get; } public bool CanSelectLexer { get; } public bool CanSelectParser { get; } public VisualizerData(object o, Config config) { if (config is null) { throw new ArgumentNullException(nameof(config)); } Config = config; Type[] types; T createInstance<T>(string typename, object[]? args = null) => types.Single(x => x.FullName == typename).CreateInstance<T>(args); { var baseTypes = new[] { typeof(Parser), typeof(Lexer) }; types = AppDomain.CurrentDomain.GetAssemblies() .Where(x => x != GetType().Assembly) .SelectMany(x => { var ret = Empty<Type>(); try { ret = x.GetTypes(); } catch { AssemblyLoadErrors.Add(x.FullName); } return ret; }) .Where(x => !x.IsAbstract) .ToArray(); foreach (var t in types) { if (t.InheritsFromOrImplements<Parser>()) { AvailableParsers.Add(new ClassInfo(t, null, null, true)); } else if (t.InheritsFromOrImplements<Lexer>()) { AvailableLexers.Add(new ClassInfo(t)); } } Config.SelectedLexerName = checkSelection(AvailableLexers, Config.SelectedLexerName); Config.SelectedParserName = checkSelection(AvailableParsers, Config.SelectedParserName); if (!Config.SelectedParserName.IsNullOrWhitespace()) { var parserInfo = AvailableParsers.SingleOrDefaultExt(x => x.FullName == Config.SelectedParserName); if (parserInfo is null) { Config.ParseTokensWithRule = null; } else if (parserInfo.MethodNames is not null) { if (Config.ParseTokensWithRule.NotIn(parserInfo.MethodNames)) { Config.ParseTokensWithRule = null; } if (Config.ParseTokensWithRule is null) { Config.ParseTokensWithRule = parserInfo.MethodNames.SingleOrDefaultExt(); } } } } string? source = null; BufferedTokenStream? tokenStream = null; IParseTree? tree = null; IVocabulary? vocabulary = null; // these three are mutually exclusive switch (o) { case string source1: source = source1; CanSelectLexer = true; CanSelectParser = true; Source = source; break; case BufferedTokenStream tokenStream1: tokenStream = tokenStream1; CanSelectParser = true; Source = tokenStream.TokenSource.InputStream.ToString(); break; case IParseTree tree1: tree = tree1; Source = tree.GetPositionedText(); break; default: throw new ArgumentException("Unhandled type"); } if (source != null && !Config.SelectedLexerName.IsNullOrWhitespace()) { var input = new AntlrInputStream(source); var lexer = createInstance<Lexer>(Config.SelectedLexerName!, new[] { input }); tokenStream = new CommonTokenStream(lexer); vocabulary = lexer.Vocabulary; } if ( tokenStream != null && !Config.SelectedParserName.IsNullOrWhitespace() && !Config.ParseTokensWithRule.IsNullOrWhitespace() ) { var parser = createInstance<Parser>(Config.SelectedParserName, new[] { tokenStream }); tree = (IParseTree)parser.GetType().GetMethod(Config.ParseTokensWithRule)!.Invoke(parser, EmptyArray<object>())!; vocabulary = parser.Vocabulary; } if (tree is null && tokenStream is null) { return; } if (tree is null) { tokenStream!.Fill(); Tokens = tokenStream.GetTokens() .Select(token => new Token(token, getTokenTypeMapping())) .Where(token => token.ShowToken(config)) .ToList(); return; } if (!config.RootNodePath.IsNullOrWhitespace()) { var pathParts = config.RootNodePath.Split('.').Select(x => int.TryParse(x, out var ret) ? ret : -1 ).ToArray(); foreach (var pathPart in pathParts) { var nextTree = tree.GetChild(pathPart); if (nextTree == null) { break; } tree = tree.GetChild(pathPart); } } var parserType = tree.GetType().DeclaringType; Config.SelectedParserName = parserType.FullName; if (vocabulary is null) { vocabulary = parserType.GetField("DefaultVocabulary").GetValue(null) as IVocabulary; } var tokenTypeMapping = getTokenTypeMapping()!; var ruleNames = (parserType.GetField("ruleNames").GetValue(null) as string[])!; var rulenameMapping = new Dictionary<Type, (string? name, int? index)>(); Tokens = new List<Token>(); var actualRoot = new ParseTreeNode(tree, Tokens, ruleNames, tokenTypeMapping, config, rulenameMapping, Config.RootNodePath); if (config.RootNodePath.IsNullOrWhitespace()) { Root = actualRoot; } else { Root = ParseTreeNode.GetPlaceholder(actualRoot); SourceOffset = actualRoot.CharSpan.startChar; Source = Source[actualRoot.CharSpan.startChar..actualRoot.CharSpan.endChar]; } UsedRuleContexts = rulenameMapping.Keys .Select(x => { rulenameMapping.TryGetValue(x, out var y); return new ClassInfo(x, y.name, y.index); }) .OrderBy(x => x.Name) .ToList(); Dictionary<int, string>? getTokenTypeMapping() { if (vocabulary is null) { return null; } #if ANTLR_LEGACY var maxTokenType = vocabulary.MaxTokenType; #else var maxTokenType = (vocabulary as Vocabulary)!.getMaxTokenType(); #endif TokenTypeMapping = Range(1, maxTokenType).Select(x => (x, vocabulary.GetSymbolicName(x))).ToDictionary(); return TokenTypeMapping; } } private string? checkSelection(List<ClassInfo> lst, string? selected) { if (lst.None(x => x.FullName == selected)) { selected = null; } if (selected.IsNullOrWhitespace()) { selected = ( lst.SingleOrDefaultExt(x => x.Antlr != "Runtime" && x.HasRelevantConstructor) ?? lst.SingleOrDefaultExt(x => x.HasRelevantConstructor) )?.FullName; } return selected; } } } <|start_filename|>UI/VisualizerControl.xaml.cs<|end_filename|> using System.ComponentModel; using System.Linq; using System.Windows; using System.Windows.Controls; using ParseTreeVisualizer.Serialization; using ZSpitz.Util; using ZSpitz.Util.Wpf; using static System.Windows.SystemColors; namespace ParseTreeVisualizer { public partial class VisualizerControl { public VisualizerControl() { InitializeComponent(); // When a control loses focus, it should look no different from when it had the focus (e.g. selection color) Resources[InactiveSelectionHighlightBrushKey] = HighlightBrush; Resources[InactiveSelectionHighlightTextBrushKey] = HighlightTextBrush; tokens.AutoGeneratingColumn += (s, e) => { if (e.PropertyName.In( nameof(ViewModelBase<string>.Model), nameof(Selectable<Token>.IsSelected) )) { e.Cancel = true; } if (e.PropertyName == nameof(TokenViewModel.Text)) { e.Column.Width = 150; (e.Column as DataGridTextColumn)!.ElementStyle = FindResource("TextTrimmedTextbox") as Style; } }; // scrolls the tree view item into view when selected AddHandler(TreeViewItem.SelectedEvent, (RoutedEventHandler)((s, e) => ((TreeViewItem)e.OriginalSource).BringIntoView())); Loaded += (s, e) => { source.LostFocus += (s1, e1) => e1.Handled = true; source.Focus(); source.SelectAll(); }; void handler(object s1, PropertyChangedEventArgs e1) { var vm = (VisualizerDataViewModel)s1; if (e1.PropertyName != nameof(VisualizerDataViewModel.FirstSelectedToken)) { return; } if (vm.FirstSelectedToken is null) { return; } tokens.ScrollIntoView(vm.FirstSelectedToken); } DataContextChanged += (s, e) => { if (e.OldValue is VisualizerDataViewModel vm) { vm.PropertyChanged -= handler; } if (e.NewValue is VisualizerDataViewModel vm1) { vm1.PropertyChanged += handler; } var assemblyLoadErrors = data.Model.AssemblyLoadErrors; if (assemblyLoadErrors.Any()) { MessageBox.Show($"Error loading the following assemblies:\n\n{assemblyLoadErrors.Joined("\n")}"); } }; } private VisualizerDataViewModel data => (VisualizerDataViewModel)DataContext; } } <|start_filename|>Serialization/Config.cs<|end_filename|> #if VISUALIZER_DEBUGGEE using Periscope.Debuggee; #endif using System; using System.Collections.Generic; using ZSpitz.Util; namespace ParseTreeVisualizer.Serialization { [Serializable] #if VISUALIZER_DEBUGGEE public class Config : ConfigBase<Config> { #else public class Config { #endif public string? SelectedParserName { get; set; } public string? ParseTokensWithRule { get; set; } public string? SelectedLexerName { get; set; } public bool ShowTextTokens { get; set; } = true; public bool ShowWhitespaceTokens { get; set; } = true; public bool ShowErrorTokens { get; set; } = true; public HashSet<int> SelectedTokenTypes { get; } = new HashSet<int>(); public bool ShowTreeTextTokens { get; set; } = true; public bool ShowTreeWhitespaceTokens { get; set; } = true; public bool ShowTreeErrorTokens { get; set; } = true; public bool ShowRuleContextNodes { get; set; } = true; public HashSet<string?> SelectedRuleContexts { get; } = new HashSet<string?>(); public string? RootNodePath { get; set; } public bool HasTreeFilter() => !(ShowTreeErrorTokens && ShowTreeWhitespaceTokens && ShowTreeTextTokens && ShowRuleContextNodes && SelectedRuleContexts.None()); public bool HasTokenListFilter() => !(ShowTextTokens && ShowErrorTokens && ShowWhitespaceTokens && SelectedTokenTypes.None()); #if VISUALIZER_DEBUGGEE // TODO should any parts of the config return ConfigDiffStates.NeedsWrite? public override ConfigDiffStates Diff(Config baseline) => ( baseline.SelectedParserName == SelectedParserName && baseline.SelectedLexerName == SelectedLexerName && baseline.ShowTextTokens == ShowTextTokens && baseline.ShowErrorTokens == ShowErrorTokens && baseline.ShowWhitespaceTokens == ShowWhitespaceTokens && baseline.ShowTreeTextTokens == ShowTreeTextTokens && baseline.ShowTreeErrorTokens == ShowTreeErrorTokens && baseline.ShowTreeWhitespaceTokens == ShowTreeWhitespaceTokens && baseline.ShowRuleContextNodes == ShowRuleContextNodes && baseline.ParseTokensWithRule == ParseTokensWithRule && baseline.SelectedTokenTypes.SetEquals(SelectedTokenTypes) && baseline.SelectedRuleContexts.SetEquals(SelectedRuleContexts) ) ? ConfigDiffStates.NoAction : ConfigDiffStates.NeedsTransfer; public override Config Clone() { #else public Config Clone() { #endif var ret = new Config { SelectedParserName = SelectedParserName, SelectedLexerName = SelectedLexerName, ShowTextTokens = ShowTextTokens, ShowErrorTokens = ShowErrorTokens, ShowWhitespaceTokens = ShowWhitespaceTokens, ShowTreeTextTokens = ShowTreeTextTokens, ShowTreeErrorTokens = ShowTreeErrorTokens, ShowTreeWhitespaceTokens = ShowTreeWhitespaceTokens, ShowRuleContextNodes = ShowRuleContextNodes, ParseTokensWithRule = ParseTokensWithRule }; SelectedTokenTypes.AddRangeTo(ret.SelectedTokenTypes); SelectedRuleContexts.AddRangeTo(ret.SelectedRuleContexts); return ret; } public void Deconstruct(out string? lexer, out string? parser, out string? ruleContext) { lexer = SelectedLexerName; parser = SelectedParserName; ruleContext = ParseTokensWithRule; } } } <|start_filename|>UI/ViewModels/ConfigViewModel.cs<|end_filename|> using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using ZSpitz.Util.Wpf; using ParseTreeVisualizer.Serialization; using ZSpitz.Util; namespace ParseTreeVisualizer { public class ConfigViewModel : ViewModelBase<Config> { public ConfigViewModel(VisualizerData vd) : this(vd.Config, vd.TokenTypeMapping, vd.UsedRuleContexts, vd.AvailableLexers, vd.AvailableParsers, vd.CanSelectLexer, vd.CanSelectParser) { } public ConfigViewModel( Config config, Dictionary<int, string>? tokenTypeMapping, List<ClassInfo>? ruleContexts, List<ClassInfo> lexers, List<ClassInfo> parsers, bool canSelectLexer, bool canSelectParser ) : base(config) { TokenTypes = tokenTypeMapping?.SelectKVP((index, text) => { var ret = new TokenTypeViewModel(index, text) { IsSelected = index.In(Model.SelectedTokenTypes) }; ret.PropertyChanged += (s, e) => { if (e.PropertyName == "IsSelected") { Model.SelectedTokenTypes.AddRemove(ret.IsSelected, ret.Index); } }; return ret; }).OrderBy(x => x.Text).ToList().AsReadOnly(); RuleContexts = ruleContexts?.Select(x => { var ret = new Selectable<ClassInfo>(x) { IsSelected = x.FullName.In(Model.SelectedRuleContexts) }; ret.PropertyChanged += (s, e) => { if (e.PropertyName == "IsSelected") { Model.SelectedRuleContexts.AddRemove(ret.IsSelected, x.FullName); } }; return ret; }).ToList().AsReadOnly(); AvailableLexers = getVMList(lexers); AvailableParsers = getVMList(parsers); CanSelectLexer = canSelectLexer; CanSelectParser = canSelectParser; } private ReadOnlyCollection<ClassInfo> getVMList(List<ClassInfo> models) { var lst = models.OrderBy(x => x.Name).ToList(); lst.Insert(0, ClassInfo.None); return lst.AsReadOnly(); } public ReadOnlyCollection<TokenTypeViewModel>? TokenTypes { get; } public ReadOnlyCollection<Selectable<ClassInfo>>? RuleContexts { get; } public ReadOnlyCollection<ClassInfo> AvailableParsers { get; } public ReadOnlyCollection<ClassInfo> AvailableLexers { get; } public bool CanSelectLexer { get; private set; } public bool CanSelectParser { get; private set; } } } <|start_filename|>UI/ViewModels/TokenViewModel.cs<|end_filename|> using ZSpitz.Util.Wpf; using ParseTreeVisualizer.Serialization; namespace ParseTreeVisualizer { public class TokenViewModel : Selectable<Token> { // we're deliberately not including IsError and TokenTypeID in the ViewModel; we don't want to display it in the autogenerated columns of the DataGrid public int Index => Model.Index; public string TokenType => Model.TokenType; public int Line => Model.Line; public int Col => Model.Col; public string Text => Model.Text; public (int start, int stop) Span => Model.Span; public bool IsWhitespace => Model.IsWhitespace; public TokenViewModel(Token model) : base(model) { } } } <|start_filename|>Visualizer/VisualizerWindow.xaml.cs<|end_filename|> using ParseTreeVisualizer.Serialization; using System.Windows; using System.Windows.Controls.Primitives; using System.Windows.Input; using System; using ZSpitz.Util.Wpf; namespace ParseTreeVisualizer { public partial class VisualizerWindow { public VisualizerWindow() { InitializeComponent(); setAsRootNode = new( o => { if (Config is null) { return; } var newConfig = Config.Clone(); newConfig.RootNodePath = ((ParseTreeNodeViewModel)o).Model.Path; Initialize(newConfig); } ); } protected override (object windowContext, object optionsContext, Config config) GetViewState(object response, ICommand? OpenInNewWindow) => response is not VisualizerData vd ? throw new InvalidOperationException("Unrecognized response type; expected VisualizerData.") : ( new VisualizerDataViewModel(vd, OpenInNewWindow, Periscope.Visualizer.CopyWatchExpression, setAsRootNode), new ConfigViewModel(vd), vd.Config ); protected override void TransformConfig(Config config, object parameter) { if (parameter is ParseTreeNode ptn) { config.RootNodePath = ptn.Path; return; } throw new NotImplementedException(); } private readonly RelayCommand setAsRootNode; } } <|start_filename|>Serialization/Extensions.cs<|end_filename|> using Antlr4.Runtime.Tree; using System.Collections.Generic; using System.Linq; using System.Text; namespace ParseTreeVisualizer { public static class Extensions { public static IEnumerable<IParseTree> Children(this IParseTree tree) { for (var i = 0; i < tree.ChildCount; i++) { yield return tree.GetChild(i); } } public static IEnumerable<IParseTree> Descendants(this IParseTree tree) { for (var i = 0; i < tree.ChildCount; i++) { var child = tree.GetChild(i); yield return child; foreach (var descendant in child.Descendants()) { yield return descendant; } } } public static string GetPositionedText(this IParseTree tree, char filler = ' ') { var sb = new StringBuilder(); foreach (var descendant in tree.Descendants().OfType<TerminalNodeImpl>()) { var fillerCharCount = descendant.Payload.StartIndex - sb.Length; if (fillerCharCount > 0) { sb.Append(filler, fillerCharCount); } sb.Append(descendant.Payload.Text); } return sb.ToString(); } } } <|start_filename|>Test/Test.Shared/TestContainer.cs<|end_filename|> using System; using System.Linq; using Xunit; using static ZSpitz.Util.Functions; using Antlr4.Runtime; using ZSpitz.Util; using Antlr4.Runtime.Tree; using ParseTreeVisualizer.Serialization; using static System.IO.File; namespace ParseTreeVisualizer.Test { public class TestContainer { public static readonly (string lexer, string parser, string rule) InvalidSelection = ( "Invalid lexer", "Invalid parser", "Invalid rule" ); public static readonly TheoryData<object, Config> TestData = IIFE(() => { var java = ( lexer: typeof(Java8Lexer), parser: typeof(Java8Parser), parseMethod: typeof(Java8Parser).GetMethod(nameof(Java8Parser.compilationUnit))! ); var filesLexersParsers = new[] { ( "WindowsFunctionsForSqLite.sql", typeof(SQLiteLexer), typeof(SQLiteParser), typeof(SQLiteParser).GetMethod(nameof(SQLiteParser.parse))! ), ( "Simple.java", java.lexer, java.parser, java.parseMethod ) }; var sources = filesLexersParsers.SelectManyT((filename, lexerType, parserType, parseMethod) => { var source = ReadAllText($"Files/{filename}"); var input = new AntlrInputStream(source); var lexer = lexerType.CreateInstance<Lexer>(new[] { input }); var tokens = new CommonTokenStream(lexer); var parser = parserType.CreateInstance<Parser>(new[] { tokens }); var tree = (IParseTree)parseMethod.Invoke(parser, Array.Empty<object>())!; return new object[] { source, tokens, tree }.Select(x => ( source: x, lexerName: lexerType.Name, parserName: parserType.Name, parseMethodName: parseMethod.Name )); }).ToList(); return sources.SelectManyT((source, lexerName, parserName, parseMethodName) => { var configs = Enumerable.Range(0, 5).Select(x => new Config()).ToArray(); configs.Skip(1).ForEach(x => x.SelectedLexerName = lexerName); configs.Skip(2).ForEach(x => x.SelectedParserName = parserName); configs.Skip(3).ForEach(x => x.ParseTokensWithRule = parseMethodName); var invalid = configs[3]; invalid.SelectedLexerName = InvalidSelection.lexer; invalid.SelectedParserName = InvalidSelection.parser; invalid.ParseTokensWithRule = InvalidSelection.rule; return configs.Select(config => (source, config)); }).ToTheoryData(); }); [Theory] [MemberData(nameof(TestData))] public void TestMethod(object source, Config config) { var vd = new VisualizerData(source, config); _ = new ConfigViewModel(vd); _ = new VisualizerDataViewModel(vd, null, null, null); if (config.SelectedLexerName == InvalidSelection.lexer) { Assert.NotEqual(InvalidSelection.lexer, vd.Config.SelectedLexerName); Assert.NotEqual(InvalidSelection.parser, vd.Config.SelectedParserName); Assert.NotEqual(InvalidSelection.rule, vd.Config.ParseTokensWithRule); } } } } <|start_filename|>UI/Converters.cs<|end_filename|> using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using static System.Windows.Media.Brushes; using System.Windows.Media; using System.Windows; using ZSpitz.Util; using ZSpitz.Util.Wpf; using ParseTreeVisualizer.Serialization; using static ParseTreeVisualizer.Serialization.TreeNodeType; namespace ParseTreeVisualizer { public class RootConverter : ReadOnlyConverterBase { public override object Convert(object value, Type targetType, object parameter, CultureInfo culture) => new[] { value }; } public class NullConverter : ReadOnlyConverterBase { public override object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value != null) { return UnsetValue; } if (targetType == typeof(Brush)) { return DarkGray; } else if (targetType == typeof(FontStyle)) { return FontStyles.Italic; } throw new InvalidOperationException("Converter only valid for Brush and FontStyle."); } } public class ErrorColorConverter : ReadOnlyConverterBase { public override object Convert(object value, Type targetType, object parameter, CultureInfo culture) => ((bool)value) ? Red : UnsetValue; } public class NodeForegroundConverter : ReadOnlyMultiConverterBase { public override object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) => // values[0] should be TreeNodeType; values[1] should be a Serialization.FilterStates values is null ? throw new ArgumentNullException(nameof(values)) : values[0] == UnsetValue || values[1] == UnsetValue ? UnsetValue : (values[0], values[1]) switch { (RuleContext or TreeNodeType.Token, null or Serialization.FilterStates.Matched) => Black, (RuleContext or TreeNodeType.Token, _) => LightGray, (ErrorToken, _) => Red, (WhitespaceToken, _) => UnsetValue, (Placeholder, _) => DarkGray, _ => throw new InvalidOperationException("Unmatched node type / filter state combination.") }; } public class NodeFontWeightConverter : ReadOnlyConverterBase { public override object Convert(object value, Type targetType, object parameter, CultureInfo culture) => ((TreeNodeType)value) == RuleContext ? FontWeights.Bold : UnsetValue; } public class NonEmptyListConverter : ReadOnlyMultiConverterBase { public override object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) => values.OfType<IEnumerable<object>>().FirstOrDefault(x => x != null && x.Any()); } }
zspitz/ANTLR4ParseTreeVisualizer
<|start_filename|>angular-local-storage/src/app/app.component.html<|end_filename|> <input type="text" (input)="persist('test', $event.target.value)"> <div *ngIf=" localStorageChanges$ | async as localStorageChanges"> {{ localStorageChanges.type }} {{ localStorageChanges.key }} {{ localStorageChanges.value }} </div>
vikobg/first-class-js
<|start_filename|>crackme/crackme.c<|end_filename|> #include <stdio.h> int func(int x, int y) { int a = x; int b = y; return a ^ b; } int main(void) { int x, y; printf("x: "); scanf("%d", &x); printf("y: "); scanf("%d", &y); printf("result: %d\n", func(x, y)); return 0; } <|start_filename|>src/rcl.c<|end_filename|> #include "vm.h" void v_rcl(v_registers* v_regs, int size) { long rip = 0; unsigned char operand_info = 0; unsigned int op1_reg_bit = 0; unsigned int op1_ref_bit = 0; unsigned int op1_size_bit = 0; unsigned int op2_reg_bit = 0; unsigned int op2_ref_bit = 0; unsigned int op2_size_bit = 0; long reg_address = 0; long operand1 = 0; long operand2 = 0; rip = v_regs->v_rip; operand_info = *(char *)rip; rip += 1; op1_reg_bit = operand_info & 0x80; // 1 0 0 0 0 0 0 0 op1_ref_bit = operand_info & 0x40; // 0 1 0 0 0 0 0 0 op1_size_bit = operand_info & 0x30; // 0 0 1 1 0 0 0 0 op1_size_bit >>= 4; op2_reg_bit = operand_info & 0x8; // 0 0 0 0 1 0 0 0 op2_ref_bit = operand_info & 0x4; // 0 0 0 0 0 1 0 0 op2_size_bit = operand_info & 0x3; // 0 0 0 0 0 0 1 1 // REG // if (op1_reg_bit) { reg_address = (long *)v_regs + *(char *)rip; if (op1_size_bit == 0) { operand1 = *(char *)reg_address; // al } else if (op1_size_bit == 1) { operand1 = *(short *)reg_address; // ax } else if (op1_size_bit == 2) { operand1 = *(int *)reg_address; // eax } else if (op1_size_bit == 3) { operand1 = *(long *)reg_address; // rax } else { exit(-1); } rip += 1; } // IMM // else { if (op1_size_bit == 0) { operand1 = *(char *)rip; rip += 1; } else if (op1_size_bit == 1) { operand1 = *(short *)rip; rip += 2; } else if (op1_size_bit == 2) { operand1 = *(int *)rip; rip += 4; } else if (op1_size_bit == 3) { operand1 = *(long *)rip; rip += 8; } else { exit(-1); } } // REF // if (op1_ref_bit) { if (size == 1) { operand1 = *(char *)operand1; } else if (size == 2) { operand1 = *(short *)operand1; } else if (size == 4) { operand1 = *(int *)operand1; } else if (size == 8) { operand1 = *(long *)operand1; } else { exit(-1); } } // REG // if (op2_reg_bit) { reg_address = (long *)v_regs + *(unsigned char *)rip; operand2 = reg_address; rip += 1; } // IMM // else { if (op2_size_bit == 0) { operand2 = *(char *)rip; rip += 1; } else if (op2_size_bit == 1) { operand2 = *(short *)rip; rip += 2; } else if (op2_size_bit == 2) { operand2 = *(int *)rip; rip += 4; } else if (op2_size_bit == 3) { operand2 = *(long *)rip; rip += 8; } else { exit(-1); // operand size error } } // REF // if (op2_ref_bit) { operand2 = *(long *)operand2; } // XOR // if (size == 1) { *(char *)operand2 ^= operand1; } else if (size == 2) { *(short *)operand2 ^= operand1; } else if (size == 4) { *(int *)operand2 ^= operand1; } else if (size == 8) { *(long *)operand2 ^= operand1; } else { exit(-1); } v_regs->v_rip = rip; } void v_rclb(v_registers* v_regs) { v_rcl(v_regs, 1); } void v_rclw(v_registers* v_regs) { v_rcl(v_regs, 2); } void v_rcll(v_registers* v_regs) { v_rcl(v_regs, 4); } void v_rclq(v_registers* v_regs) { v_rcl(v_regs, 8); } <|start_filename|>src/Makefile<|end_filename|> CC = clang CFLAGS = -fno-stack-protector TARGET = virtualife OBJECTS = main.o zero.o lea.o mov.o add.o sub.o syscall.o cmp.o jmp.o xor.o all : $(TARGET) $(TARGET) : $(OBJECTS) $(CC) $(CFLAGS) -o $@ $^ rm *.o <|start_filename|>src/zero.c<|end_filename|> #include "vm.h" void v_zero(v_registers* v_regs) { int i=0; unsigned char *v_sp = v_regs->v_rbp; for (i=0; i<0x60; i++) { --v_sp; *v_sp = 0; } } <|start_filename|>src/syscall.c<|end_filename|> #include "vm.h" void v_syscall(v_registers* v_regs) { __asm__ ( "movq %0, %%rax;" "movq %1, %%rdi;" "movq %2, %%rsi;" "movq %3, %%rdx;" "syscall;" : : "m" (v_regs->v_rax), "m" (v_regs->v_rdi), "m" (v_regs->v_rsi), "m" (v_regs->v_rdx) : "rax", "rdi", "rsi", "rdx" ); } <|start_filename|>src/main.c<|end_filename|> #include "vm.h" /* Instruction Format * * AA BC DD EE * * AA: opcode * BC: operand info ( 0 0 0 0 a b a b) * a: reference bit * b: register bit * DD: operand1 (Register: 1 byte, Immediate: 8 bytes) * EE: operand2 (Register: 1 byte, Immediate: 8 bytes) */ /* Stack Layout * __________ * [ ] * [ ret ] * _[ sfp ]_rbp * VM Data <-| [ v_tmp ]_rbp-0x08 * | [ v_rflags ]_rbp-0x10 * | [ v_rip ]_rbp-0x18 * | [ v_r15 ]_rbp-0x20 * | [ v_r14 ]_rbp-0x28 * | [ v_r13 ]_rbp-0x30 * | [ v_r12 ]_rbp-0x38 * | [ v_r11 ]_rbp-0x40 * | [ v_r10 ]_rbp-0x48 * | [ v_r9 ]_rbp-0x50 * | [ v_r8 ]_rbp-0x58 * | [ v_rsp ]_rbp-0x60 * | [ v_rbp ]_rbp-0x68 * | [ v_rdi ]_rbp-0x70 * | [ v_rsi ]_rbp-0x78 * | [ v_rdx ]_rbp-0x80 * | [ v_rcx ]_rbp-0x88 * | [ v_rbx ]_rbp-0x90 * |_[ v_rax ]_rbp-0x98, v_rbp, v_rsp * [ vstack ] * [ (0x60) ]_rbp-0xf8 * [__________] */ void (*v_table[])(v_registers *v_regs) = { v_zero, v_leaq, v_movb, v_movw, v_movl, v_movq, v_movabsq, v_addb, v_addw, v_addl, v_addq, v_subb, v_subw, v_subl, v_subq, v_syscall, v_cmpb, v_cmpw, v_cmpl, v_cmpq, v_jmp, v_je, v_jne, v_xorb, v_xorw, v_xorl, v_xorq /* v_rcrb, v_rcrw, v_rcrl, v_rcrq, v_rclb, v_rclw, v_rcll, v_rclq */ }; char v_code[] = {'\xd0', '\xd5', '\xbb', '\x06', '\x12', '\xda', '\x0b', '\xec', '\x12', '\xd4', '\xaf', '\x05', '\x12', '\xd5', '\xbb', '\x06', '\x12', '\xda', '\x0b', '\xe8', '\x12', '\xd4', '\xaf', '\x04', '\x12', '\xd5', '\xbb', '\x06', '\x12', '\xda', '\x0b', '\xec', '\x12', '\xd4', '\xfa', '\x12', '\x00', '\xd5', '\xbb', '\x06', '\x12', '\xda', '\x0b', '\xfc', '\x12', '\xd4', '\xaf', '\x00', '\x12', '\xd5', '\xbb', '\x06', '\x12', '\xda', '\x0b', '\xe8', '\x12', '\xd4', '\xfa', '\x12', '\x00', '\xd5', '\xbb', '\x06', '\x12', '\xda', '\x0b', '\xf8', '\x12', '\xd4', '\xaf', '\x00', '\x12', '\xd5', '\xbb', '\x06', '\x12', '\xda', '\x0b', '\xfc', '\x12', '\xd4', '\xfa', '\x12', '\x00', '\xd5', '\xbb', '\x06', '\x12', '\xda', '\x0b', '\xf8', '\x12', '\xe9', '\xfa', '\x12', '\x00', '\x00'}; int volatile func(int x, int y) { __asm__ ( "construct:;" " sub $0x150, %%rsp;" " leaq -0x98(%%rbp), %%rax;" " movq %%rax, -0x68(%%rbp);" // Set v_rbp " movq %%rax, -0x60(%%rbp);" // Set v_rsp " leaq %0, %%rax;" " movq %%rax, -0x18(%%rbp);" // Set v_rip " movq %2, %%rax;" " movq %%rax, -0x70(%%rbp);" // set v_rdi (argv[0]) " movq %3, %%rax;" " movq %%rax, -0x78(%%rbp);" // set v_rsi (argv[1]) "fetch:;" " xor %%rax, %%rax;" " movq -0x18(%%rbp), %%rbx;" " movb (%%rbx), %%al;" " incq -0x18(%%rbp);" " test %%al, %%al;" " je destruct;" "execute:;" " leaq -0x98(%%rbp), %%rdi;" " sub $0xd0, %%rax;" " imul $8, %%rax;" " leaq %1, %%rbx;" " addq %%rax, %%rbx;" " call *(%%rbx);" " jmp fetch;" "destruct:;" " movq -0x98(%%rbp), %%rax;" " mov %%rbp, %%rsp;" " pop %%rbp;" " retn;" : : "m" (v_code), "m" (v_table), "m" (x), "m" (y) : ); } int main(void) { int x, y; printf("x: "); scanf("%d", &x); printf("y: "); scanf("%d", &y); printf("result: %d\n", func(x, y)); return 0; } <|start_filename|>src/jmp.c<|end_filename|> #include "vm.h" void v_jmp(v_registers* v_regs) { long rip = 0; unsigned char operand_info = 0; unsigned int op1_reg_bit = 0; unsigned int op1_ref_bit = 0; unsigned int op1_size_bit = 0; long reg_address = 0; long operand1 = 0; rip = v_regs->v_rip; operand_info = *(char *)rip; rip += 1; op1_reg_bit = operand_info & 0x80; // 1 0 0 0 0 0 0 0 op1_ref_bit = operand_info & 0x40; // 0 1 0 0 0 0 0 0 op1_size_bit = operand_info & 0x30; // 0 0 1 1 0 0 0 0 op1_size_bit >>= 4; // REG // if (op1_reg_bit) { reg_address = (long *)v_regs + *(char *)rip; if (op1_size_bit == 0) { operand1 = *(char *)reg_address; // al } else if (op1_size_bit == 1) { operand1 = *(short *)reg_address; // ax } else if (op1_size_bit == 2) { operand1 = *(int *)reg_address; // eax } else if (op1_size_bit == 3) { operand1 = *(long *)reg_address; // rax } else { exit(-1); } rip += 1; } // IMM // else { if (op1_size_bit == 0) { operand1 = *(char *)rip; rip += 1; } else if (op1_size_bit == 1) { operand1 = *(short *)rip; rip += 2; } else if (op1_size_bit == 2) { operand1 = *(int *)rip; rip += 4; } else if (op1_size_bit == 3) { operand1 = *(long *)rip; rip += 8; } else { exit(-1); } } // REF // if (op1_ref_bit) { if (op1_size_bit == 0) { operand1 = *(char *)operand1; } else if (op1_size_bit == 1) { operand1 = *(short *)operand1; } else if (op1_size_bit == 2) { operand1 = *(int *)operand1; } else if (op1_size_bit == 3) { operand1 = *(long *)operand1; } else { exit(-1); } } // JMP // rip += operand1; v_regs->v_rip = rip; } void v_je(v_registers* v_regs) { long rip = 0; unsigned char operand_info = 0; unsigned int op1_reg_bit = 0; unsigned int op1_size_bit = 0; unsigned char zf = 0; zf = v_regs->v_rflags & 0b1000000; if (zf != 0) { v_jmp(v_regs); } // fetch operands to skip rip // else { rip = v_regs->v_rip; operand_info = *(char *)rip; rip += 1; op1_reg_bit = operand_info & 0x80; // 1 0 0 0 0 0 0 0 op1_size_bit = operand_info & 0x30; // 0 0 1 1 0 0 0 0 op1_size_bit >>= 4; // REG // if (op1_reg_bit) { rip += 1; } // IMM // else { if (op1_size_bit == 0) { rip += 1; } else if (op1_size_bit == 1) { rip += 2; } else if (op1_size_bit == 2) { rip += 4; } else if (op1_size_bit == 3) { rip += 8; } else { exit(-1); } } v_regs->v_rip = rip; } } void v_jne(v_registers* v_regs) { long rip = 0; unsigned char operand_info = 0; unsigned int op1_reg_bit = 0; unsigned int op1_size_bit = 0; unsigned char zf = 0; zf = v_regs->v_rflags & 0b1000000; if (zf == 0) { v_jmp(v_regs); } // fetch operands to skip rip // else { rip = v_regs->v_rip; operand_info = *(char *)rip; rip += 1; op1_reg_bit = operand_info & 0x80; // 1 0 0 0 0 0 0 0 op1_size_bit = operand_info & 0x30; // 0 0 1 1 0 0 0 0 op1_size_bit >>= 4; // REG // if (op1_reg_bit) { rip += 1; } // IMM // else { if (op1_size_bit == 0) { rip += 1; } else if (op1_size_bit == 1) { rip += 2; } else if (op1_size_bit == 2) { rip += 4; } else if (op1_size_bit == 3) { rip += 8; } else { exit(-1); } } v_regs->v_rip = rip; } } <|start_filename|>src/vm.h<|end_filename|> #include <stdio.h> #include <unistd.h> #include <string.h> typedef struct v_registers { long v_rax; long v_rbx; long v_rcx; long v_rdx; long v_rsi; long v_rdi; long v_rbp; long v_rsp; long v_r8; long v_r9; long v_r10; long v_r11; long v_r12; long v_r13; long v_r14; long v_r15; long v_rip; long v_rflags; long v_tmp; }v_registers; void v_zero(v_registers* v_regs); void v_leaq(v_registers* v_regs); void v_mov(v_registers* v_regs, int size); void v_movb(v_registers* v_regs); void v_movw(v_registers* v_regs); void v_movl(v_registers* v_regs); void v_movq(v_registers* v_regs); void v_movabsq(v_registers* v_regs); void v_add(v_registers* v_regs, int size); void v_addb(v_registers* v_regs); void v_addw(v_registers* v_regs); void v_addl(v_registers* v_regs); void v_addq(v_registers* v_regs); void v_sub(v_registers* v_regs, int size); void v_subb(v_registers* v_regs); void v_subw(v_registers* v_regs); void v_subl(v_registers* v_regs); void v_subq(v_registers* v_regs); void v_syscall(v_registers* v_regs); void v_cmp(v_registers* v_regs, int size); void v_cmpb(v_registers* v_regs); void v_cmpw(v_registers* v_regs); void v_cmpl(v_registers* v_regs); void v_cmpq(v_registers* v_regs); void v_jmp(v_registers* v_regs); void v_je(v_registers* v_regs); void v_jne(v_registers* v_regs); void v_xor(v_registers* v_regs, int size); void v_xorb(v_registers* v_regs); void v_xorw(v_registers* v_regs); void v_xorl(v_registers* v_regs); void v_xorq(v_registers* v_regs); /* void v_rcr(v_registers* v_regs); void v_rcrb(v_registers* v_regs); void v_rcrw(v_registers* v_regs); void v_rcrl(v_registers* v_regs); void v_rcrq(v_registers* v_regs); void v_rcl(v_registers* v_regs); void v_rclb(v_registers* v_regs); void v_rclw(v_registers* v_regs); void v_rcll(v_registers* v_regs); void v_rclq(v_registers* v_regs); */ <|start_filename|>src/debug.c<|end_filename|> #include "vm.h" void v_debug(v_registers* v_regs) { int i=0, j=0; unsigned char *v_sp = v_regs->v_rbp; v_sp -= 0x60; printf("\n\nREGISTER SET\n"); printf("\tv_rax : 0x%lx\n", v_regs->v_rax); printf("\tv_rbx : 0x%lx\n", v_regs->v_rbx); printf("\tv_rcx : 0x%lx\n", v_regs->v_rcx); printf("\tv_rdx : 0x%lx\n", v_regs->v_rdx); printf("\tv_rsi : 0x%lx\n", v_regs->v_rsi); printf("\tv_rdi : 0x%lx\n", v_regs->v_rdi); printf("\tv_rbp : 0x%lx\n", v_regs->v_rbp); printf("\tv_rsp : 0x%lx\n", v_regs->v_rsp); printf("\tv_r8 : 0x%lx\n", v_regs->v_r8 ); printf("\tv_r9 : 0x%lx\n", v_regs->v_r9 ); printf("\tv_r10 : 0x%lx\n", v_regs->v_r10); printf("\tv_r11 : 0x%lx\n", v_regs->v_r11); printf("\tv_r12 : 0x%lx\n", v_regs->v_r12); printf("\tv_r13 : 0x%lx\n", v_regs->v_r13); printf("\tv_r14 : 0x%lx\n", v_regs->v_r14); printf("\tv_r15 : 0x%lx\n", v_regs->v_r15); printf("\tv_rip : 0x%lx\n", v_regs->v_rip); printf("\tv_rflags: 0x%lx\n", v_regs->v_rflags); printf("\tv_tmp : 0x%lx\n\n", v_regs->v_tmp); printf("STACK LATOUT --------------------------------------------------\n"); for (i=6; i>0; --i) { printf("0x%lx [ ", v_sp); for (j=0; j<0x10; ++j) { if (j==8) { printf(" "); } printf("%02x ", *v_sp); ++v_sp; } printf("]\n"); } printf(" --------------------------------------------------\n"); }
juhajong/vm-obfuscator
<|start_filename|>Algorithms.Tests/Strings/PrefixFunctionTests.fs<|end_filename|> namespace Algorithms.Tests.Strings open Microsoft.VisualStudio.TestTools.UnitTesting open Algorithms.Strings [<TestClass>] type PrefixFunctionTests () = [<TestMethod>] [<DataRow("aabcdaabc", 4)>] [<DataRow("asdasdad", 4)>] [<DataRow("abcab", 2)>] member this.longestPrefix (input:string, expected:int) = let actual = PrefixFunction.longestPrefix(input) Assert.AreEqual(expected, actual) [<TestMethod>] member this.prefixFunction () = let expected = [0; 1; 0; 0; 0; 1; 2; 3; 4] let actual = PrefixFunction.prefixFunction("aabcdaabc") Assert.AreEqual(expected, actual) <|start_filename|>Algorithms.Tests/Strings/SplitTests.fs<|end_filename|> namespace Algorithms.Tests.Strings open Microsoft.VisualStudio.TestTools.UnitTesting open Algorithms.Strings [<TestClass>] type SplitTests () = [<TestMethod>] member this.Split () = let expected = ["apple"; "banana"; "cherry"; "orange"] let actual = Split.Split("apple#banana#cherry#orange", '#') Assert.AreEqual(expected, actual) <|start_filename|>Algorithms.Tests/Strings/NaiveStringSearchTests.fs<|end_filename|> namespace Algorithms.Tests.Strings open Microsoft.VisualStudio.TestTools.UnitTesting open Algorithms.Strings [<TestClass>] type NaiveStringSearchTests () = [<TestMethod>] member this.naivePatternSearch () = let actual = NaiveStringSearch.naivePatternSearch("ABAAABCDBBABCDDEBCABC", "ABC") let expected = [4; 10; 18] Assert.AreEqual(expected, actual) <|start_filename|>Algorithms/Math/AbsMax.fs<|end_filename|> namespace Algorithms.Math module AbsMax = let absMax (x: int list) = let mutable j = x.[0] for i in x do if abs i > abs j then j <- i j <|start_filename|>Algorithms.Tests/Strings/ReverseWordsTests.fs<|end_filename|> namespace Algorithms.Tests.Strings open Microsoft.VisualStudio.TestTools.UnitTesting open Algorithms.Strings [<TestClass>] type ReverseWordsTests () = [<TestMethod>] [<DataRow("I love F#", "F# love I")>] [<DataRow("I Love F#", "F# Love I")>] member this.reverseWords (input:string, expected:string) = let actual = ReverseWords.reverseWords(input) Assert.AreEqual(expected, actual) <|start_filename|>Algorithms/Sort/Merge_Sort.fs<|end_filename|> namespace Algorithms.Sort module MergeSort = let split list = let rec aux l acc1 acc2 = match l with | [] -> (acc1, acc2) | [ x ] -> (x :: acc1, acc2) | x :: y :: tail -> aux tail (x :: acc1) (y :: acc2) aux list [] [] let rec merge l1 l2 = match (l1, l2) with | (x, []) -> x | ([], y) -> y | (x :: tx, y :: ty) -> if x <= y then x :: merge tx l2 else y :: merge l1 ty let rec sort list = match list with | [] -> [] | [ x ] -> [ x ] | _ -> let (l1, l2) = split list merge (sort l1) (sort l2) <|start_filename|>Algorithms.Tests/Strings/UpperTests.fs<|end_filename|> namespace Algorithms.Tests.Strings open Microsoft.VisualStudio.TestTools.UnitTesting open Algorithms.Strings [<TestClass>] type UpperTests () = [<TestMethod>] [<DataRow("wow", "WOW")>] [<DataRow("Hello", "HELLO")>] [<DataRow("WHAT", "WHAT")>] [<DataRow("wh[]32", "WH[]32")>] member this.upper (input:string, expected:string) = let actual = Upper.upper(input) Assert.AreEqual(expected, actual) <|start_filename|>Algorithms.Tests/Strings/IsPalindromeTests.fs<|end_filename|> namespace Algorithms.Tests.Strings open Microsoft.VisualStudio.TestTools.UnitTesting open Algorithms.Strings [<TestClass>] type IsPalindromeTests () = [<TestMethod>] [<DataRow("amanaplanacanalpanama", true)>] [<DataRow("Hello", false)>] [<DataRow("Able was I ere I saw Elba", true)>] [<DataRow("racecar", true)>] [<DataRow("Mr. Owl ate my metal worm?", true)>] member this.isPalindrome (str:string, expected:bool) = let actual = IsPalindrome.isPalindrome str Assert.AreEqual(expected, actual) <|start_filename|>Algorithms/Strings/Lower.fs<|end_filename|> namespace Algorithms.Strings module Lower = /// <summary> /// Will convert the entire string to lowercase letters /// </summary> /// <example> /// <code> /// lower("wow") /// 'wow' /// /// lower("HellZo") /// hellzo' /// /// lower("WHAT") /// 'what' /// /// lower("wh[]32") /// 'wh[]32' /// /// lower("whAT") /// 'what' /// </code> /// </example> /// <param name="input"></param> /// <returns></returns> let lower (input: string): string = input.Split() |> Array.map (fun word -> word.ToCharArray() |> Array.map (fun character -> if character >= 'A' && character <= 'Z' then char (int character + 32) else character) |> (fun characters -> System.String.Concat(characters))) |> String.concat " " <|start_filename|>Algorithms/Strings/NaiveStringSearch.fs<|end_filename|> namespace Algorithms.Strings /// <summary> /// https://en.wikipedia.org/wiki/String-searching_algorithm#Na%C3%AFve_string_search /// /// This algorithm tries to find the pattern from every position of /// the mainString if pattern is found from position i it add it to /// the answer and does the same for position i+1 /// </summary> /// /// <remarks> /// Complexity : O(n*m) /// n=length of main string /// m=length of pattern string /// </remarks> module NaiveStringSearch = /// <summary> /// </summary> /// <example> /// <code> /// naive_pattern_search("ABAAABCDBBABCDDEBCABC", "ABC") /// [4, 10, 18] /// /// naive_pattern_search("ABC", "ABAAABCDBBABCDDEBCABC") /// [] /// /// naive_pattern_search("", "ABC") /// [] /// /// naive_pattern_search("TEST", "TEST") /// [0] /// /// naive_pattern_search("ABCDEGFTEST", "TEST") /// [7] /// </code> /// </example> /// <param name="s"></param> /// <param name="pattern"></param> /// <returns>List of positions</returns> let naivePatternSearch (s: string, pattern: string): int list = s.ToCharArray() |> Seq.mapi (fun i x -> let myv = pattern.[0] if x = pattern.[0] then (i, s.[i..(i + (pattern.Length - 1))]) else (i, "")) |> Seq.where (fun (i, x) -> pattern = x) |> Seq.map (fun (i, x) -> i) |> List.ofSeq <|start_filename|>Algorithms.Tests/Strings/CheckPangramTests.fs<|end_filename|> namespace Algorithms.Tests.Strings open Microsoft.VisualStudio.TestTools.UnitTesting open Algorithms.Strings [<TestClass>] type CheckPangramTests () = [<TestMethod>] [<DataRow("The quick brown fox jumps over the lazy dog", true)>] [<DataRow("Waltz, bad nymph, for quick jigs vex.", true)>] [<DataRow("Jived fox nymph grabs quick waltz.", true)>] [<DataRow("My name is Unknown", false)>] [<DataRow("The quick brown fox jumps over the la_y do", false)>] [<DataRow("", true)>] member this.CheckPangram (sentence:string, expected:bool) = let actual = CheckPangram.checkPangram sentence Assert.AreEqual(expected, actual) [<TestMethod>] [<DataRow("The quick brown fox jumps over the lazy dog", true)>] [<DataRow("Waltz, bad nymph, for quick jigs vex.", false)>] [<DataRow("Jived fox nymph grabs quick waltz.", false)>] [<DataRow("The quick brown fox jumps over the la_y do", false)>] [<DataRow("", false)>] member this.CheckPangramFaster (sentence:string, expected:bool) = let actual = CheckPangram.checkPangramFaster sentence Assert.AreEqual(expected, actual) <|start_filename|>Algorithms/Strings/LevenshteinDistance.fs<|end_filename|> namespace Algorithms.Strings module LevenshteinDistance = /// <summary> /// Implementation of the levenshtein distance in F#. /// </summary> /// <param name="firstWord">The first word to measure the difference.</param> /// <param name="secondWord">The second word to measure the difference.</param> /// <returns></returns> let rec levenshteinDistance (firstWord: string, secondWord: string): int = // The longer word should come first match secondWord.Length with | s when s > firstWord.Length -> levenshteinDistance (secondWord, firstWord) | 0 -> firstWord.Length | _ -> let mutable previousRow = [ 0 .. secondWord.Length ] firstWord |> Seq.iteri (fun i c1 -> let mutable currentRow = [ i + 1 ] secondWord |> Seq.iteri (fun j c2 -> let insertions = previousRow.[j + 1] + 1 let deletions = currentRow.[j] + 1 let substitutions = previousRow.[j] + (if c1 <> c2 then 1 else 0) // Get the minimum to append to the current row currentRow <- currentRow |> List.append [ (min insertions (min deletions substitutions)) ]) previousRow <- currentRow |> List.rev) previousRow |> List.rev |> List.item 0 <|start_filename|>Algorithms/Sort/Pancake_Sort.fs<|end_filename|> namespace Algorithms.Sort module PancakeSort = let show data = data |> Array.iter (printf "%d ") printfn "" let split (data: int []) pos = data.[0..pos], data.[(pos + 1)..] let flip items pos = let lower, upper = split items pos Array.append (Array.rev lower) upper let sort items = let rec loop data limit = if limit <= 0 then data else let lower, upper = split data limit let indexOfMax = lower |> Array.findIndex ((=) (Array.max lower)) let partialSort = Array.append (flip lower indexOfMax |> Array.rev) upper loop partialSort (limit - 1) loop items ((Array.length items) - 1) <|start_filename|>Algorithms/Sort/Cycle_Sort.fs<|end_filename|> namespace Algorithms.Sort module CycleSort = let Sort list: 'T [] = let mutable list = list |> Array.copy let mutable writes = 0 for index in 0 .. list.Length - 1 do let mutable value = list.[index] let mutable pos = index for i in index + 1 .. list.Length - 1 do if list.[i] < value then pos <- pos + 1 if pos <> index then while value = list.[pos] do pos <- pos + 1 let mutable tmp = list.[pos] list.[pos] <- value value <- tmp writes <- writes + 1 while pos <> index do pos <- index for i in index + 1 .. list.Length - 1 do if list.[i] < value then pos <- pos + 1 while value = list.[pos] do pos <- pos + 1 tmp <- list.[pos] list.[pos] <- value value <- tmp writes <- writes + 1 list <|start_filename|>Algorithms.Tests/Strings/ReverseLettersTests.fs<|end_filename|> namespace Algorithms.Tests.Strings open Microsoft.VisualStudio.TestTools.UnitTesting open Algorithms.Strings [<TestClass>] type ReverseLettersTests () = [<TestMethod>] [<DataRow("The cat in the hat", "ehT tac ni eht tah")>] [<DataRow("The quick brown fox jumped over the lazy dog.", "ehT kciuq nworb xof depmuj revo eht yzal .god")>] [<DataRow("Is this true?", "sI siht ?eurt")>] [<DataRow("I love F#", "I evol #F")>] member this.reverseLetters (input:string, expected:string) = let actual = ReverseLetters.reverseLetters(input) Assert.AreEqual(expected, actual) <|start_filename|>Algorithms/Math/AbsMin.fs<|end_filename|> namespace Algorithms.Math module AbsMin = let absMin (x: int list) = let mutable j = x.[0] for i in x do if abs i < abs j then j <- i j <|start_filename|>Algorithms/Strings/SwapCase.fs<|end_filename|> namespace Algorithms.Strings module SwapCase = type System.Char with member this.IsUpper(): bool = match this with | c when c >= 'A' && c <= 'Z' -> true | _ -> false member this.IsLower(): bool = match this with | c when c >= 'a' && c <= 'z' -> true | _ -> false member this.Lower(): char = match this with | c when c >= 'A' && c <= 'Z' -> (char) ((int) this + 32) | _ -> this member this.Upper(): char = match this with | c when c >= 'a' && c <= 'z' -> (char) ((int) this - 32) | _ -> this /// <summary> /// This function will convert all lowercase letters to uppercase letters and vice versa /// </summary> let swapCase (sentence: string): string = let mutable newString = "" for character in sentence do match character with | c when c.IsUpper() -> newString <- newString + (string) (character.Lower()) | c when c.IsLower() -> newString <- newString + (string) (character.Upper()) | _ -> newString <- newString + (string) character newString <|start_filename|>Algorithms/Math/Fibonacci.fs<|end_filename|> namespace Algorithms.Math module Fibonacci = let rec PrintSerie (one: int) (two: int) = let fibo = one + two System.Console.WriteLine fibo PrintSerie two fibo <|start_filename|>Algorithms.Tests/Strings/CheckAnagramsTests.fs<|end_filename|> namespace Algorithms.Tests.Strings open Microsoft.VisualStudio.TestTools.UnitTesting open Algorithms.Strings [<TestClass>] type CheckAnagramsTests () = [<TestMethod>] [<DataRow("Silent", "Listen", true)>] [<DataRow("This is a string", "Is this a string", true)>] [<DataRow("This is a string", "Is this a string", true)>] [<DataRow("There", "Their", false)>] member this.isAnagram (string1:string, string2:string, expected:bool) = let actual = CheckAnagrams.isAnagram (string1, string2) Assert.AreEqual(expected, actual) <|start_filename|>Algorithms.Tests/Strings/KnuthMorrisPrattTests.fs<|end_filename|> namespace Algorithms.Tests.Strings open Microsoft.VisualStudio.TestTools.UnitTesting open Algorithms.Strings [<TestClass>] type KnuthMorrisPrattTests () = [<TestMethod>] member this.getFailureArray () = let actual = KnuthMorrisPratt.getFailureArray("aabaabaaa") let expected = [0; 1; 0; 1; 2; 3; 4; 5; 2] Assert.AreEqual(expected, actual) [<TestMethod>] [<DataRow("abc1abc12", "alskfjaldsabc1abc1abc12k23adsfabcabc")>] [<DataRow("ABABX", "ABABZABABYABABX")>] [<DataRow("AAAB", "ABAAAAAB")>] [<DataRow("abcdabcy", "abcxabcdabxabcdabcdabcy")>] member this.kmp (pattern:string, text:string) = let actual = KnuthMorrisPratt.kmp(pattern, text) Assert.IsTrue(actual) <|start_filename|>Algorithms.Tests/Strings/LowerTests.fs<|end_filename|> namespace Algorithms.Tests.Strings open Microsoft.VisualStudio.TestTools.UnitTesting open Algorithms.Strings [<TestClass>] type LowerTests () = [<TestMethod>] [<DataRow("wow", "wow")>] [<DataRow("HellZo", "hellzo")>] [<DataRow("WHAT", "what")>] [<DataRow("wh[]32", "wh[]32")>] [<DataRow("whAT", "what")>] member this.lower (input:string, expected:string) = let actual = Lower.lower(input) Assert.AreEqual(expected, actual) <|start_filename|>Algorithms/Strings/RabinKarp.fs<|end_filename|> namespace Algorithms.Strings module RabinKarp = /// Numbers of alphabet which we call base let alphabetSize = 256L /// Modulus to hash a string let modulus = 1000003L let nfmod (a: int64, b: int64) = let aD = double a let bD = double b int64 (aD - bD * floor (aD / bD)) /// <summary> /// The Rabin-Karp Algorithm for finding a pattern within a piece of text /// with complexity O(nm), most efficient when it is used with multiple patterns /// as it is able to check if any of a set of patterns match a section of text in o(1) /// given the precomputed hashes. /// </summary> /// <remarks> /// This will be the simple version which only assumes one pattern is being searched /// for but it's not hard to modify /// /// 1) Calculate pattern hash /// /// 2) Step through the text one character at a time passing a window with the same /// length as the pattern /// calculating the hash of the text within the window compare it with the hash /// of the pattern. Only testing equality if the hashes match /// </remarks> /// <param name="pattern"></param> /// <param name="text"></param> /// <returns></returns> let rabinKarp (pattern: string, text: string): bool = let mutable result = false let patLen = pattern.Length let textLen = text.Length match patLen with | p when p > textLen -> false | _ -> let mutable patternHash = 0L let mutable textHash = 0L let mutable modulusPower = 1L // Calculating the hash of pattern and substring of text for i in 0 .. (patLen - 1) do patternHash <- (int64 (pattern.[i]) + patternHash * alphabetSize) % modulus textHash <- (int64 (text.[i]) + textHash * alphabetSize) % modulus if i <> (patLen - 1) then modulusPower <- (modulusPower * alphabetSize) % modulus for i in 0 .. (textLen - patLen + 1) do if textHash = patternHash && text.[i..i + (patLen - 1)] = pattern then result <- true if not result then if i <> (textLen - patLen) then let first = (textHash - int64 (text.[i]) * modulusPower) * alphabetSize let second = int64 (text.[i + patLen]) let third = (first + second) % modulus textHash <- ((((textHash - int64 (text.[i]) * modulusPower) * alphabetSize) + int64 (text.[i + patLen])) % modulus) + modulus result <|start_filename|>Algorithms.Tests/Strings/RabinKarpTests.fs<|end_filename|> namespace Algorithms.Tests.Strings open Microsoft.VisualStudio.TestTools.UnitTesting open Algorithms.Strings [<TestClass>] type RabinKarpTests () = [<TestMethod>] [<DataRow("ABABX", "ABABZABABYABABX")>] [<DataRow("AAAB", "ABAAAAAB")>] [<DataRow("abcdabcy","abcxabcdabxabcdabcdabcy")>] [<DataRow("Lü","Lüsai")>] member this.rabinKarp (pattern:string, text:string) = let actual = RabinKarp.rabinKarp(pattern, text) Assert.IsTrue(actual) <|start_filename|>Algorithms.Tests/Strings/WordOccurrenceTests.fs<|end_filename|> namespace Algorithms.Tests.Strings open Microsoft.VisualStudio.TestTools.UnitTesting open Algorithms.Strings [<TestClass>] type WordOccurrenceTests () = [<TestMethod>] member this.wordOccurrence () = let mutable expected : Map<string,int> = Map.empty expected <- expected.Add("Two",1) expected <- expected.Add("spaces",1) let actual = WordOccurrence.wordOccurrence("Two spaces") Assert.AreEqual(expected, actual) <|start_filename|>Algorithms/Strings/PrefixFunction.fs<|end_filename|> namespace Algorithms.Strings /// https://cp-algorithms.com/string/prefix-function.html /// /// Prefix function Knuth–Morris–Pratt algorithm /// /// Different algorithm than Knuth-Morris-Pratt pattern finding /// /// E.x. Finding longest prefix which is also suffix /// Time Complexity: O(n) - where n is the length of the string module PrefixFunction = /// <summary> /// For the given string this function computes value for each <c>index(i)</c>, /// which represents the longest coincidence of prefix and suffix /// for given substring <c>inputString[0...i]</c>. /// For the value of the first element the algorithm always returns 0 /// </summary> /// <example> /// <code> /// prefix_function "aabcdaabc" /// [0, 1, 0, 0, 0, 1, 2, 3, 4] /// /// prefix_function("asdasdad") /// [0, 0, 0, 1, 2, 3, 4, 0] /// </code> /// </example> /// <param name="inputString"></param> /// <returns>A string of <c>int</c></returns> let prefixFunction (inputString: string): list<int> = // List for the result values let mutable prefixResult = [| for i in 0 .. (inputString.Length - 1) -> 0 |] for i = 1 to (inputString.Length - 1) do // Use last results for better performance - dynamic programming let mutable j = prefixResult.[i - 1] while j > 0 && inputString.[i] <> inputString.[j] do j <- prefixResult.[j - 1] if inputString.[i] = inputString.[j] then j <- j + 1 prefixResult.SetValue(j, i) prefixResult |> List.ofArray /// <summary> /// Prefix-function use case /// Finding longest prefix which is suffix as well /// </summary> /// <example> /// <code> /// longest_prefix "aabcdaabc" /// 4 /// longest_prefix "asdasdad" /// 4 /// longest_prefix "abcab" /// 2 /// </code> /// </example> /// <param name="inputString"></param> /// <returns>Returns <c>int</c></returns> let longestPrefix (inputString: string): int = // Just returning maximum value of the array gives us answer prefixFunction (inputString) |> System.Linq.Enumerable.Max <|start_filename|>Algorithms/Strings/KnuthMorrisPratt.fs<|end_filename|> namespace Algorithms.Strings module KnuthMorrisPratt = let getFailureArray (pattern: string): list<int> = let mutable failure = [ 0 ] let mutable i = 0 let mutable j = 1 while j < pattern.Length do if pattern.[i] = pattern.[j] then i <- i + 1 elif i > 0 then i <- failure.[i - 1] j <- j + 1 failure <- failure |> List.append [ i ] failure /// <summary> /// The Knuth-Morris-Pratt Algorithm for finding a pattern within a piece of text /// with complexity O(n + m) /// </summary> /// <param name="pattern"></param> /// <param name="text"></param> /// <returns></returns> let kmp (pattern: string, text: string): bool = // 1) Construct the failure array let failure = getFailureArray pattern let mutable result = false // 2) Step through text searching for pattern let mutable i, j = 0, 0 // Index into text, pattern while i < text.Length do if pattern.[j] = text.[i] then if j = pattern.Length - 1 && (not result) then result <- true j <- j + 1 // If this is a prefix in our pattern // just go back far enough to continue elif j > 0 && (not result) then j <- failure.[j - 1] i <- i + 1 result <|start_filename|>Algorithms/Sort/Heap_Sort.fs<|end_filename|> namespace Algorithms.Sort module HeapSort = let inline swap (a: 'T []) i j = let temp = a.[i] a.[i] <- a.[j] a.[j] <- temp let inline sift cmp (a: 'T []) start count = let rec loop root child = if root * 2 + 1 < count then let p = child < count - 1 && cmp a.[child] a.[child + 1] < 0 let child = if p then child + 1 else child if cmp a.[root] a.[child] < 0 then swap a root child loop child (child * 2 + 1) loop start (start * 2 + 1) let inline heapsort cmp (a: 'T []) = let n = a.Length for start = n / 2 - 1 downto 0 do sift cmp a start n for term = n - 1 downto 1 do swap a term 0 sift cmp a 0 term <|start_filename|>Algorithms.Tests/Strings/RemoveDuplicatesTests.fs<|end_filename|> namespace Algorithms.Tests.Strings open Microsoft.VisualStudio.TestTools.UnitTesting open Algorithms.Strings [<TestClass>] type RemoveDuplicatesTests () = [<TestMethod>] [<DataRow("Python is great and Java is also great", "Python is great and Java also")>] [<DataRow("Python is great and Java is also great", "Python is great and Java also")>] member this.removeDuplicates (str:string, expected:string) = let actual = RemoveDuplicates.removeDuplicates(str) Assert.AreEqual(expected, actual) <|start_filename|>Algorithms/Sort/Gnome_Sort.fs<|end_filename|> namespace Algorithms.Sort module GnomeSort = let Sort list: 'T [] = let mutable list = list |> Array.copy let mutable first = 1 let mutable second = 2 while first < list.Length do if list.[first - 1] <= list.[first] then first <- second second <- second + 1 else let tmp = list.[first - 1] list.[first - 1] <- list.[first] list.[first] <- tmp first <- first - 1 if first = 0 then first <- 1 second <- 2 list <|start_filename|>Algorithms.Tests/Strings/JaroWinklerTests.fs<|end_filename|> namespace Algorithms.Tests.Strings open Microsoft.VisualStudio.TestTools.UnitTesting open Algorithms.Strings [<TestClass>] type JaroWinklerTests () = [<TestMethod>] [<DataRow("martha", "marhta", 0.9611111111111111)>] [<DataRow("CRATE", "TRACE", 0.7333333333333334)>] [<DataRow("test", "dbdbdbdb", 0.0)>] [<DataRow("test", "test", 1.0)>] [<DataRow("hello world", "HeLLo W0rlD", 0.6363636363636364)>] [<DataRow("test", "", 0.0)>] [<DataRow("hello", "world", 0.4666666666666666)>] [<DataRow("hell**o", "*world", 0.4365079365079365)>] member this.jaroWinkler (str1:string, str2:string, expected:float) = let actual = JaroWinkler.jaroWinkler(str1, str2) Assert.AreEqual(expected, actual) <|start_filename|>Algorithms.Tests/Strings/ZFunctionTests.fs<|end_filename|> namespace Algorithms.Tests.Strings open Microsoft.VisualStudio.TestTools.UnitTesting open Algorithms.Strings [<TestClass>] type ZFunctionTests () = [<TestMethod>] [<DataRow("abr", "abracadabra",2)>] [<DataRow("a", "aaaa", 4)>] [<DataRow("xz", "zxxzxxz", 2)>] member this.findPattern (pattern:string, inputString:string, expected:int) = let actual = ZFunction.findPattern(pattern, inputString) Assert.AreEqual(expected, actual) [<TestMethod>] member this.zFunction () = let expected = [0; 0; 0; 1; 0; 1; 0; 4; 0; 0; 1] let actual = ZFunction.zFunction("abracadabra") Assert.AreEqual(expected, actual) <|start_filename|>Algorithms.Tests/Strings/MinCostStringConversionTests.fs<|end_filename|> namespace Algorithms.Tests.Strings open Microsoft.VisualStudio.TestTools.UnitTesting open Algorithms.Strings [<TestClass>] type MinCostStringConversionTests () = [<TestMethod>] [<DataRow("abbbaba", "abbba")>] [<DataRow("ababa", "ababa")>] member this.assembleTransformation (ops:string list, i:int, j:int, expected:string list) = let actual = MinCostStringConversion.assembleTransformation(ops, i, j) Assert.AreEqual(expected, actual) [<TestMethod>] [<DataRow("abbbaba", "abbba")>] [<DataRow("ababa", "ababa")>] member this.assembleTransformation (sourceString:string, destinationString:string, copyCost:int, replaceCost:int, deleteCost:int, insertCost:int, expected:int list * string list) = let actual = MinCostStringConversion.computeTransformTables(sourceString,destinationString,copyCost,replaceCost,deleteCost,insertCost) Assert.AreEqual(expected, actual) <|start_filename|>Algorithms/Strings/CheckPangram.fs<|end_filename|> namespace Algorithms.Strings /// wiki: https://en.wikipedia.org/wiki/Pangram module CheckPangram = type System.Char with member this.IsUpper(): bool = match this with | c when c >= 'A' && c <= 'Z' -> true | _ -> false member this.IsLower(): bool = match this with | c when c >= 'a' && c <= 'z' -> true | _ -> false member this.Lower(): char = match this with | c when c >= 'A' && c <= 'Z' -> (char) ((int) this + 32) | _ -> this member this.Upper(): char = match this with | c when c >= 'a' && c <= 'z' -> (char) ((int) this - 32) | _ -> this let checkPangram (inputString: string): bool = let mutable frequency = Set.empty let inputStr = inputString.Replace(" ", "") // Replacing all the whitespace in our sentence for alpha in inputStr do if 'a' <= alpha.Lower() && alpha.Lower() <= 'z' then frequency <- frequency.Add(alpha.Lower()) match frequency.Count with | 26 -> true | _ -> if inputStr = "" then true else false let checkPangramFaster (inputString: string): bool = let mutable flag = [| for i in 1 .. 26 -> false |] for char in inputString do if char.IsLower() then flag.SetValue(true, (int) char - (int) 'a') flag |> Array.forall (id) <|start_filename|>Algorithms/Math/Abs.fs<|end_filename|> namespace Algorithms.Math module Abs = let absVal num = if num < 0 then -num else num <|start_filename|>Algorithms.Tests/Strings/ManacherTests.fs<|end_filename|> namespace Algorithms.Tests.Strings open Microsoft.VisualStudio.TestTools.UnitTesting open Algorithms.Strings [<TestClass>] type ManacherTests () = [<TestMethod>] [<DataRow("abbbaba", "abbba")>] [<DataRow("ababa", "ababa")>] member this.palindromicString (input:string, expected:string) = let actual = Manacher.palindromicString(input) Assert.AreEqual(expected, actual) <|start_filename|>Algorithms/Strings/CheckAnagrams.fs<|end_filename|> namespace Algorithms.Strings /// wiki: https://en.wikipedia.org/wiki/Anagram module CheckAnagrams = /// <summary> /// Two strings are anagrams if they are made of the same letters /// arranged differently (ignoring the case). /// </summary> /// <example> /// <code> /// check_anagrams('Silent', 'Listen') /// True /// /// check_anagrams('This is a string', 'Is this a string') /// True /// /// check_anagrams('This is a string', 'Is this a string') /// True /// /// check_anagrams('There', 'Their') /// False /// </code> /// </example> /// <param name="string1">First string</param> /// <param name="string2">Second string</param> /// <returns>Boolean</returns> let isAnagram (string1: string, string2: string): bool = let a = string1.ToLower().ToCharArray() |> Array.filter (fun chars -> chars <> ' ') |> Array.sort |> System.String.Concat let b = string2.ToLower().ToCharArray() |> Array.filter (fun chars -> chars <> ' ') |> Array.sort |> System.String.Concat a = b <|start_filename|>Algorithms/Sort/Comb_Sort.fs<|end_filename|> namespace Algorithms.Sort module CombSort = let Sort list: 'T [] = let mutable list = list |> Array.copy let mutable gap = double list.Length let mutable swaps = true while gap > 1.0 || swaps do gap <- gap / 1.247330950103979 if gap < 1.0 then gap <- 1.0 let mutable i = 0 swaps <- false while i + int gap < list.Length do let igap = i + int gap if list.[i] > list.[igap] then let swap = list.[i] list.[i] <- list.[igap] list.[igap] <- swap swaps <- true i <- i + 1 list <|start_filename|>Algorithms/Strings/IsPalindrome.fs<|end_filename|> namespace Algorithms.Strings module IsPalindrome = /// <summary> /// Determine whether the string is palindrome /// </summary> /// <param name="str"></param> /// <returns>Boolean</returns> let isPalindrome (str: string): bool = let str = str.ToLower() |> Seq.filter (System.Char.IsLetterOrDigit) |> Seq.toList str = (str |> List.rev) <|start_filename|>Algorithms/Sort/Insertion_Sort.fs<|end_filename|> namespace Algorithms.Sort module InsertionSort = let Sort list: 'T [] = let mutable list = list |> Array.copy for index in 1 .. list.Length - 1 do let item = list.[index] let mutable j = index while j > 0 && list.[j - 1] > item do list.[j] <- list.[j - 1] j <- j - 1 list.[j] <- item list <|start_filename|>Algorithms.Tests/Strings/LevenshteinDistanceTests.fs<|end_filename|> namespace Algorithms.Tests.Strings open Microsoft.VisualStudio.TestTools.UnitTesting open Algorithms.Strings [<TestClass>] type LevenshteinDistanceTests () = [<TestMethod>] [<DataRow("planet", "planetary", 3)>] [<DataRow("", "test", 4)>] [<DataRow("book", "back", 2)>] [<DataRow("book", "book", 0)>] [<DataRow("test", "", 4)>] [<DataRow("", "", 0)>] [<DataRow("orchestration", "container", 10)>] member this.levenshteinDistance (firstWord:string, secondWord:string, expected:int) = let actual = LevenshteinDistance.levenshteinDistance(firstWord, secondWord ) Assert.AreEqual(expected, actual) <|start_filename|>Algorithms.Tests/Strings/CapitalizeTests.fs<|end_filename|> namespace Algorithms.Tests.Strings open Microsoft.VisualStudio.TestTools.UnitTesting open Algorithms.Strings [<TestClass>] type CapitalizeTests () = [<TestMethod>] [<DataRow("hello world", "Hello world")>] [<DataRow("123 hello world", "123 hello world")>] [<DataRow(" hello world", " hello world")>] [<DataRow("a", "A")>] [<DataRow("", "")>] member this.Capitalize (sentence:string, expected:string) = let actual = Capitalize.capitalize sentence Assert.AreEqual(expected, actual) <|start_filename|>Algorithms/Strings/MinCostStringConversion.fs<|end_filename|> /// Algorithm for calculating the most cost-efficient sequence for converting one string /// into another. /// The only allowed operations are /// --- Cost to copy a character is copy_cost /// --- Cost to replace a character is replace_cost /// --- Cost to delete a character is delete_cost /// --- Cost to insert a character is insert_cost /// namespace Algorithms.Strings module MinCostStringConversion = let computeTransformTables ( sourceString: string, destinationString: string, copyCost: int, replaceCost: int, deleteCost: int, insertCost: int ): list<int> * list<string> = let sourceSeq = [ sourceString ] let destinationSeq = [ destinationString ] let lenSourceSeq = sourceSeq.Length let lenDestinationSeq = destinationSeq.Length let costs = [| for i in 0 .. (lenSourceSeq + 1) -> [| for i in 0 .. lenDestinationSeq + 1 -> 0 |] |] let ops = [| for i in 0 .. lenSourceSeq + 1 -> [| for i in 0 .. lenDestinationSeq + 1 -> "" |] |] for i = 1 to lenSourceSeq + 1 do costs.[i].[0] <- i * deleteCost ops.[i].[0] <- sprintf "D%s" (sourceSeq.[i - 1]) for i = 1 to lenDestinationSeq + 1 do costs.[0].[i] <- i * insertCost ops.[0].[i] <- sprintf "I%s" (destinationSeq.[i - 1]) for i in 1 .. lenSourceSeq + 1 do for j in 1 .. lenDestinationSeq + 1 do if sourceSeq.[i - 1] = destinationSeq.[j - 1] then costs.[i].[j] <- costs.[i - 1].[j - 1] + copyCost ops.[i].[j] <- sprintf "C%s" (sourceSeq.[i - 1]) else costs.[i].[j] <- costs.[i - 1].[j - 1] + replaceCost ops.[i].[j] <- sprintf "R%s" (sourceSeq.[i - 1] + (string) (destinationSeq.[j - 1])) if costs.[i - 1].[j] + deleteCost < costs.[i].[j] then costs.[i].[j] <- costs.[i - 1].[j] + deleteCost ops.[i].[j] <- sprintf "D%s" (sourceSeq.[i - 1]) if costs.[i].[j - 1] + insertCost < costs.[i].[j] then costs.[i].[j] <- costs.[i].[j - 1] + insertCost ops.[i].[j] <- sprintf "I%s" (destinationSeq.[j - 1]) costs |> Seq.cast<int> |> Seq.toList, ops |> Seq.cast<string> |> Seq.toList let rec assembleTransformation (ops: list<string>, i: int, j: int): list<string> = if i = 0 && j = 0 then List.empty else match ops.[i].[j] with | o when o = 'C' || o = 'R' -> let mutable seq = assembleTransformation (ops, i - 1, j - 1) |> List.toArray let ch = [ ((string) ops.[i].[j]) ] |> List.toArray seq <- seq |> Array.append ch seq |> List.ofArray | 'D' -> let mutable seq = assembleTransformation (ops, i - 1, j) |> List.toArray let ch = [ ((string) ops.[i].[j]) ] |> List.toArray seq <- seq |> Array.append ch seq |> List.ofArray | _ -> let mutable seq = assembleTransformation (ops, i, j - 1) |> List.toArray let ch = [ ((string) ops.[i].[j]) ] |> List.toArray seq <- seq |> Array.append ch seq |> List.ofArray <|start_filename|>Algorithms/Strings/JaroWinkler.fs<|end_filename|> namespace Algorithms.Strings open Microsoft.FSharp.Collections module JaroWinkler = /// <summary> /// Jaro–Winkler distance is a string metric measuring an edit distance between two /// sequences. /// Output value is between 0.0 and 1.0. /// </summary> /// <param name="str1"></param> /// <param name="str2"></param> /// <returns></returns> let jaroWinkler (str1: string, str2: string): float = let getMatchedCharacters (_str1: string, _str2: string): string = let mutable istr1 = _str1 let mutable istr2 = _str2 let mutable matched = [] let limit = int (floor (double (min _str1.Length str2.Length) / 2.0)) istr1 |> Seq.iteri (fun i l -> let left = int(max 0 (i - limit)) let right = int(min (i + limit + 1) istr2.Length) if (istr2.[left..right - 1]).Contains(l) then matched <- List.append matched [ (string) l ] let myIndex = (istr2.IndexOf(l)) istr2 <- $"{istr2.[0..istr2.IndexOf(l) - 1]} {istr2.[istr2.IndexOf(l) + 1..]}") matched |> List.fold (+) "" // matching characters let matching1 = getMatchedCharacters (str1, str2) let matching2 = getMatchedCharacters (str2, str1) let matchCount = matching1.Length let mutable jaro = 0.0 // Transposition let transpositions = floor ( double ( (double) [ for c1, c2 in List.zip [ matching1 ] [ matching2 ] do if c1 <> c2 then (c1, c2) ] .Length ) ) if matchCount = 0 then jaro <- 0.0 else jaro <- 1.0 / 3.0 * ((double) matchCount / (double) str1.Length + (double) matchCount / (double) str2.Length + ((double) matchCount - transpositions) / (double) matchCount) // Common prefix up to 4 characters let mutable prefixLen = 0 let mutable c1C2BoolList : bool list = [] if str1.Length = str2.Length then for c1, c2 in Array.zip (str1.[..4].ToCharArray()) (str2.[..4].ToCharArray()) do if c1 = c2 then c1C2BoolList <- List.append c1C2BoolList [true] else c1C2BoolList <- List.append c1C2BoolList [false] if (c1C2BoolList |> List.exists(fun x -> (not x))) then prefixLen <- prefixLen + (c1C2BoolList |> List.findIndex(fun x -> (not x))) jaro + 0.1 * (double) prefixLen * (1.0 - jaro) <|start_filename|>Algorithms.Tests/Strings/SwapCaseTests.fs<|end_filename|> namespace Algorithms.Tests.Strings open Microsoft.VisualStudio.TestTools.UnitTesting open Algorithms.Strings [<TestClass>] type SwapCaseTests () = [<TestMethod>] [<DataRow("Algorithm.F#@89", "aLGORITHM.f#@89")>] member this.swapCase (input:string, expected:string) = let actual = SwapCase.swapCase(input) Assert.AreEqual(expected, actual) <|start_filename|>Algorithms/Strings/Upper.fs<|end_filename|> namespace Algorithms.Strings module Upper = /// <summary> /// Will convert the entire string to uppercase letters /// </summary> /// <param name="input">String to change to uppercase.</param> /// <returns>Uppercased string</returns> let upper (input: string) = input.Split() |> Array.map (fun word -> word.ToCharArray() |> Array.map (fun character -> if character >= 'a' && character <= 'z' then char (int character - 32) else character) |> (fun characters -> System.String.Concat(characters))) |> String.concat " " <|start_filename|>Algorithms/Sort/Bubble_Sort.fs<|end_filename|> namespace Algorithms.Sort module BubbleSort = let rec Sort list: 'T [] = let mutable updated = false let mutable list = list |> Array.copy for index in 0 .. list.Length - 1 do if index < list.Length - 1 then let current = list.[index] let next = list.[index + 1] if next < current then list.[index] <- next list.[index + 1] <- current updated <- true if updated then list <- Sort list list <|start_filename|>Algorithms/Strings/Capitalize.fs<|end_filename|> namespace Algorithms.Strings module Capitalize = /// <summary> /// This function will capitalize the first letter of a sentence or a word /// </summary> /// <example> /// <code> /// capitalize("hello world") /// 'Hello world' /// /// capitalize("123 hello world") /// '123 hello world' /// /// capitalize(" hello world") /// ' hello world' /// /// capitalize("a") /// 'A' /// /// capitalize("") /// '' /// </code> /// </example> /// <param name="sentence">String to capitalize.</param> /// <returns>Capitalized string</returns> let capitalize (sentence: string) = match sentence with | "" -> "" | s when s.[0] >= 'a' && s.[0] <= 'z' -> sentence .Remove(0, 1) .Insert(0, (string) ((char) ((int) s.[0] - 32))) | _ -> sentence
BlueKrait7/F-Sharp
<|start_filename|>include/types.hpp<|end_filename|> /* Point Cloud Registration Tool BSD 2-Clause License Copyright (c) 2017, <NAME> See LICENSE at package root for full license */ #ifndef types_hpp #define types_hpp // Standard #include <vector> // PCL #include <pcl/point_types.h> #include <pcl/common/projection_matrix.h> #include <pcl/visualization/pcl_plotter.h> // Boost #include <boost/shared_ptr.hpp> namespace PRT { struct filepair_t { std::string sourcefile; std::string targetfile; }; struct RGB { uint8_t r; uint8_t g; uint8_t b; RGB() : r(0), g(0), b(0) {} RGB(const uint8_t r, const uint8_t g, const uint8_t b) : r(r), g(g), b(b) {} }; typedef pcl::PointXYZ PointT; typedef pcl::PointCloud<PointT> PointCloudT; typedef pcl::Normal NormalT; typedef pcl::PointCloud<NormalT> NormalCloudT; typedef pcl::SHOT352 SHOTDescriptorT; typedef pcl::PointCloud<SHOTDescriptorT> SHOTDescriptorCloudT; typedef pcl::PointXYZRGB PointRGBT; typedef pcl::PointCloud<PointRGBT> PointCloudRGBT; typedef boost::shared_ptr< pcl::visualization::PCLPlotter > PCLPlotterPtr; typedef std::vector<float> FloatVector; typedef boost::shared_ptr< FloatVector > FloatVectorPtr; typedef std::vector<double> DoubleVector; typedef boost::shared_ptr< DoubleVector > DoubleVectorPtr; typedef std::vector<std::string> StringVector; typedef boost::shared_ptr< StringVector > StringVectorPtr; typedef std::vector<filepair_t> FilepairVector; typedef boost::shared_ptr< FilepairVector > FilepairVectorPtr; } #endif /* types_hpp */ <|start_filename|>include/Registrator.hpp<|end_filename|> /* Point Cloud Registration Tool BSD 2-Clause License Copyright (c) 2017, <NAME> See LICENSE at package root for full license */ #ifndef Registrator_hpp #define Registrator_hpp // Standard #include <stdio.h> // Boost #include <boost/shared_ptr.hpp> // PCL #include <pcl/io/ply_io.h> #include <pcl/point_types.h> #include <pcl/kdtree/kdtree_flann.h> #include <pcl/correspondence.h> #include <pcl/registration/icp.h> #include <pcl/console/time.h> #include <pcl/filters/voxel_grid.h> #include <pcl/features/shot_omp.h> #include <pcl/features/normal_3d_omp.h> #include <pcl/registration/transformation_estimation_svd.h> #include <pcl/registration/correspondence_rejection_sample_consensus.h> // PRT #include "types.hpp" #include "util.hpp" // GFLAGS #include <gflags/gflags.h> DECLARE_string(registration_technique); DECLARE_double(residual_threshold); DECLARE_uint64(num_ksearch_neighbors); DECLARE_double(descriptor_radius); DECLARE_double(subsampling_radius); DECLARE_double(consensus_inlier_threshold); DECLARE_uint64(consensus_max_iterations); DECLARE_uint64(icp_max_iterations); DECLARE_double(icp_max_correspondence_distance); using namespace PRT; class Registrator { public: // Constants static const std::string DEFAULT_registration_technique; static const double DEFAULT_residual_threshold; static const int DEFAULT_num_ksearch_neighbors; static const double DEFAULT_descriptor_radius; static const double DEFAULT_subsampling_radius; static const double DEFAULT_consensus_inlier_threshold; static const int DEFAULT_consensus_max_iterations; static const int DEFAULT_icp_max_iterations; static const double DEFAULT_icp_max_correspondence_distance; // Typedefs typedef boost::shared_ptr< Registrator > Ptr; // Constructor Registrator(); /** Sets the source cloud The source cloud is that which we aim to align to the source cloud */ void setSourceCloud(const PointCloudT::Ptr &cloud); /** Sets the target cloud The target cloud is that which we aim to align against */ void setTargetCloud(const PointCloudT::Ptr &cloud); //Setup methods void setSubsamplingRadius(double r); void setDescriptorRadius(double r); void setNumKSearchNeighbors(int n); void setConsensusInlierThreshold(double t); void setConsensusMaxIterations(int i); void setICPMaxCorrespondenceDistance(double d); void setICPMaxIterations(int i); //Computation methods void performRegistration(const std::string); void computeResidualColormap(); int saveResidualColormapPointCloud(std::string &filepath); void setResidualThreshold(double residual_threshold); //Get methods Eigen::Matrix4f getCorrespondenceBasedTransformation(); Eigen::Matrix4f getICPBasedTransformation(); Eigen::Matrix4f getCombinedTransformation(); PointCloudT::Ptr getRegisteredCloud(); PointCloudRGBT::Ptr getRegisteredRGBCloud(); PointCloudT::Ptr getSourceCloud(); PointCloudT::Ptr getTargetCloud(); PointCloudT::Ptr getSourceKeypointsCloud(); PointCloudT::Ptr getTargetKeypointsCloud(); DoubleVectorPtr getTargetToRegisteredResiduals(); DoubleVectorPtr getRegisteredToTargetResiduals(); double getMaxTargetToRegisteredResidual(); double getMaxRegisteredToTargetResidual(); double getFScoreAtThreshold(double threshold = -1); int saveFinalTransform(const std::string filepath); void saveFScoreAtThreshold(const std::string filepath, double threshold); double getResidualThreshold(); private: //Computation methods void correspondenceBasedRegistration(); void ICPBasedRegistration(); void computeNormals(); void extractKeypoints(); void computeDescriptors(); void computeResiduals(); void findCorrespondences(); void filterCorrespondences(); void computeCorrespondenceBasedTransformation(); void setRegisteredCloudToDefaultColor(); //Data members PointCloudT::Ptr s_cloud_; //Source Cloud PointCloudT::Ptr t_cloud_; //Target Cloud PointCloudT::Ptr r_cloud_; //Source Cloud after Registration PointCloudRGBT::Ptr r_cloud_rgb_; //Source Cloud after Registration (with RGB attributes) NormalCloudT::Ptr s_cloud_normals_; //Source Cloud Normals NormalCloudT::Ptr t_cloud_normals_; //Target Cloud Normals PointCloudT::Ptr s_cloud_keypoints_; //Source Cloud Keypoints PointCloudT::Ptr t_cloud_keypoints_; //Target Cloud Keypoints SHOTDescriptorCloudT::Ptr s_cloud_descriptors_; //Source SHOT Descriptors SHOTDescriptorCloudT::Ptr t_cloud_descriptors_; //Target SHOT Descriptors PointCloudT::Ptr s_cloud_corr_; //Source Cloud Correspondence Points PointCloudT::Ptr t_cloud_corr_; //Target Cloud Correspondence Points pcl::CorrespondencesPtr correspondences_; //Keypoint Correspondences DoubleVectorPtr t_r_residuals_; //Residuals from target cloud to registered cloud DoubleVectorPtr r_t_residuals_; //Residuals from registered cloud to target cloud double t_r_max_residual_; //Max residual from target cloud to registered cloud double r_t_max_residual_; //Max residual from registered cloud to target cloud Eigen::Matrix4f correspondence_T_; //Transformation matrix estimated from point correspondences Eigen::Matrix4f icp_T_; //Transformation matrix estimated from ICP Eigen::Matrix4f combined_T_; //Transformation matrix from both correspondence matching & ICP double uniform_sampling_radius_; double descriptor_radius_; int num_k_search_neighbors_; double consensus_inlier_threshold_; int consensus_max_iterations_; int icp_max_iterations_; double icp_max_correspondence_distance_; bool is_correspondence_matching_complete_ = false; bool is_icp_complete_ = false; bool is_residual_colormap_computed_ = false; DoubleVectorPtr colormap_residuals_; RGB r_color_; double residual_threshold_; }; #endif /* Registrator_hpp */ <|start_filename|>src/main.cpp<|end_filename|> /* Point Cloud Registration Tool BSD 2-Clause License Copyright (c) 2017, <NAME> See LICENSE at package root for full license */ #ifdef _OPENMP #include <omp.h> #endif // Standard #include <iostream> #include <iterator> #include <algorithm> #include <string> #include <vector> // PRT #include "util.hpp" #include "types.hpp" #include "Registrator.hpp" #include "Visualizer.hpp" // GFLAGS #include <gflags/gflags.h> DECLARE_bool(help); DEFINE_bool(h, false, "Show help"); DEFINE_bool(gui, false, "launch GUI after registration"); DEFINE_string(batch_file, "", "path to batch processing file"); DEFINE_string(transformation_matrix_filepath, "[source_filename]_transform.csv", "filepath to output transformation matrix CSV"); DEFINE_string(registered_pointcloud_filepath, "[source_filename]_registered.ply", "filepath to output registered point cloud PLY"); DEFINE_string(residual_histogram_image_filepath, "[source_filename]_histogram.png", "filepath to output histogram PNG"); DEFINE_string(fscore_filepath, "[source_filename]_fscore.txt", "filepath to output f-score TXT"); #ifdef _OPENMP DEFINE_bool(no_parallel, false, "run single-threaded"); #endif using namespace PRT; int main (int argc, char* argv[]) { std::string usage_message = "\nUsage:\n\n1. ./point_cloud_registration_tool [options] <source_point_cloud> <target_point_cloud>\n2. ./point_cloud_registration_tool [options] --batch_file <batch_filepath>\n\nA batch file is a two-column CSV. First column: source point cloud filepaths, second column: target point cloud filepaths.\n\nSee --help for optional arguments\n"; gflags::SetUsageMessage(usage_message); gflags::ParseCommandLineFlags(&argc, &argv, true); if (FLAGS_descriptor_radius <= 0) { std::cout << "Error: Descriptor radius must be a positive value." << std::endl; return -1; } if (FLAGS_subsampling_radius <= 0) { std::cout << "Error: Subsampling radius must be a positive value." << std::endl; return -1; } if (FLAGS_consensus_inlier_threshold <= 0) { std::cout << "Error: Consensus inlier threshold must be a positive value." << std::endl; return -1; } if (FLAGS_icp_max_correspondence_distance <= 0) { std::cout << "Error: Maximum correspondence distance must be a positive value." << std::endl; return -1; } if (FLAGS_residual_threshold <= 0) { std::cout << "Error: Residual threshold must be a positive value." << std::endl; return -1; } if (FLAGS_h) { FLAGS_help = true; gflags::HandleCommandLineHelpFlags(); exit(0); } if (argc < 3 && FLAGS_batch_file.empty()) { std::cout << usage_message << std::endl; return 0; } pcl::console::setVerbosityLevel(pcl::console::L_ALWAYS); FilepairVectorPtr filepairs; if (!FLAGS_batch_file.empty()) { filepairs = util::readBatchProcessingFile(FLAGS_batch_file); if(filepairs->empty()) { std::cout << "Invalid batch file path, exiting." << std::endl; return -1; } FLAGS_gui = false; } else { filepair_t pair; pair.sourcefile = argv[1]; pair.targetfile = argv[2]; filepairs = FilepairVectorPtr(new FilepairVector()); filepairs->push_back(pair); } #ifdef _OPENMP omp_set_nested(true); if (FLAGS_no_parallel) omp_set_num_threads(1); else if (FLAGS_verbose) std::cout << "Executing in parallel" << std::endl; #endif for(FilepairVector::size_type i = 0; i < filepairs->size(); i++) { PointCloudT::Ptr target_cloud (new PointCloudT); target_cloud->clear(); std::string target_cloud_filepath = filepairs->at(i).targetfile; PointCloudT::Ptr source_cloud (new PointCloudT); source_cloud->clear(); std::string source_cloud_filepath = filepairs->at(i).sourcefile; bool reads_successful = true; if (util::loadPointCloud(source_cloud_filepath, *source_cloud) != 0) { std::cout << "Invalid input:" << std::endl << source_cloud_filepath << std::endl; std::cout << "Skipping.." << std::endl; reads_successful = false; } if (util::loadPointCloud(target_cloud_filepath, *target_cloud) != 0) { std::cout << "Invalid input:" << std::endl << target_cloud_filepath << std::endl; std::cout << "Skipping.." << std::endl; reads_successful = false; } if(!reads_successful) continue; //Extract prefix for output files std::string prefix = util::removeFileExtension(filepairs->at(i).sourcefile); //Set output file paths std::string transformation_matrix_filepath; std::string registered_pointcloud_filepath; std::string residual_histogram_image_filepath; std::string fscore_filepath; if (FLAGS_transformation_matrix_filepath != "[source_filename]_transform.csv") transformation_matrix_filepath = FLAGS_transformation_matrix_filepath; else transformation_matrix_filepath = prefix + "_transform.csv"; if (FLAGS_registered_pointcloud_filepath != "[source_filename]_registered.ply") registered_pointcloud_filepath = FLAGS_registered_pointcloud_filepath; else registered_pointcloud_filepath = prefix + "_registered.ply"; if (FLAGS_residual_histogram_image_filepath != "[source_filename]_histogram.png") residual_histogram_image_filepath = FLAGS_residual_histogram_image_filepath; else residual_histogram_image_filepath = prefix + "_residual_histogram.png"; if (FLAGS_fscore_filepath != "[source_filename]_fscore.txt") fscore_filepath = FLAGS_fscore_filepath; else fscore_filepath = prefix + "_fscore.txt"; //Ensure unique output filepaths if (util::ensureUniqueFilepath(transformation_matrix_filepath) != 0) { std::cout << "Failed to create transformation matrix file." << std::endl; continue; } if (util::ensureUniqueFilepath(fscore_filepath) != 0) { std::cout << "Failed to create f-score file." << std::endl; continue; } if (util::ensureUniqueFilepath(registered_pointcloud_filepath) != 0) { std::cout << "Failed to create registered PLY file." << std::endl; continue; } if (util::ensureUniqueFilepath(residual_histogram_image_filepath) != 0) { std::cout << "Failed to create residual histogram file." << std::endl; continue; } //Registration //Setup Registrator::Ptr registrator (new Registrator()); registrator->setNumKSearchNeighbors(FLAGS_num_ksearch_neighbors); registrator->setDescriptorRadius(FLAGS_descriptor_radius); registrator->setSubsamplingRadius(FLAGS_subsampling_radius); registrator->setConsensusInlierThreshold(FLAGS_consensus_inlier_threshold); registrator->setConsensusMaxIterations(FLAGS_consensus_max_iterations); registrator->setICPMaxIterations(FLAGS_icp_max_iterations); registrator->setICPMaxCorrespondenceDistance(FLAGS_icp_max_correspondence_distance); registrator->setResidualThreshold(FLAGS_residual_threshold); registrator->setTargetCloud(target_cloud); registrator->setSourceCloud(source_cloud); //Compute registrator->performRegistration(FLAGS_registration_technique); //Save Results registrator->saveResidualColormapPointCloud(registered_pointcloud_filepath); registrator->saveFinalTransform(transformation_matrix_filepath); registrator->saveFScoreAtThreshold(fscore_filepath, FLAGS_residual_threshold); std::cout << "Registration of " << source_cloud_filepath << " finished" << std::endl; std::cout << "F-score: " << registrator->getFScoreAtThreshold() << std::endl; std::cout << "Saved to: " << registered_pointcloud_filepath << std::endl; if (!FLAGS_gui) continue; //Visualization Visualizer visualizer ("Point Cloud Registration Tool"); visualizer.setRegistrator(registrator); visualizer.saveHistogramImage(residual_histogram_image_filepath); visualizer.visualize(); } return 0; } <|start_filename|>src/Visualizer.cpp<|end_filename|> /* Point Cloud Registration Tool BSD 2-Clause License Copyright (c) 2017, <NAME> See LICENSE at package root for full license */ #include "Visualizer.hpp" void keyboardEventOccurred (const pcl::visualization::KeyboardEvent& event, void* obj) { Visualizer* vis = (Visualizer*) obj; if (event.getKeySym () == "s" && event.keyDown ()) vis->toggleShowSource(); if (event.getKeySym () == "t" && event.keyDown ()) vis->toggleShowTarget(); if (event.getKeySym () == "r" && event.keyDown ()) vis->toggleShowRegistered(); if (event.getKeySym () == "k" && event.keyDown ()) vis->toggleShowKeypoints(); if (event.getKeySym () == "Up" && event.keyDown ()) vis->incrementResidualThreshold(); if (event.getKeySym () == "Down" && event.keyDown ()) vis->decrementResidualThreshold(); } Visualizer::Visualizer(const std::string &name) { viewer_ = pcl::visualization::PCLVisualizer::Ptr(new pcl::visualization::PCLVisualizer(name)); viewer_->setBackgroundColor(0,0,0); viewer_->setCameraPosition (-7.5, 0, 7.5, 0, 0, 1, 0); viewer_->setSize (1024, 768); viewer_->registerKeyboardCallback (&keyboardEventOccurred, this); viewer_->setShowFPS(false); plotter_ = PCLPlotterPtr(new pcl::visualization::PCLPlotter); plotter_->setTitle("Residuals Histogram"); plotter_->setXTitle("Distance (m)"); plotter_->setYTitle("Frequency"); plotter_->setShowLegend(false); registrator_ = Registrator::Ptr(); s_color_ = RGB(0, 0, 255); //Blue t_color_ = RGB(0, 255, 0); // Green r_color_ = RGB(255, 0, 0); // Red keypoints_color_ = RGB(255, 255, 0); // Yellow show_source_ = false; show_target_ = false; show_registered_ = true; histogram_residuals_ = DoubleVectorPtr(new DoubleVector()); point_size_ = 1.5; keypoint_size_ = 3; } void Visualizer::setRegistrator(const Registrator::Ptr &registrator) { registrator_ = registrator; } void Visualizer::incrementResidualThreshold() { registrator_->setResidualThreshold((registrator_->getResidualThreshold() < 1) ? registrator_->getResidualThreshold() + 0.01 : registrator_->getResidualThreshold()); registrator_->computeResidualColormap(); updateText(); setHistogramXRange(); computeResidualHistogram(); resetRegisteredCloud(); } void Visualizer::decrementResidualThreshold() { registrator_->setResidualThreshold((registrator_->getResidualThreshold() >= .02) ? registrator_->getResidualThreshold() - 0.01 : registrator_->getResidualThreshold()); registrator_->computeResidualColormap(); updateText(); setHistogramXRange(); computeResidualHistogram(); resetRegisteredCloud(); } int Visualizer::getNumHistogramBins() { return 2 * std::max((int)(registrator_->getResidualThreshold() * 100),1); //One bar represents 0.5cm } void Visualizer::setHistogramXRange(double min, double max) { if (max == -1) max = registrator_->getResidualThreshold(); plotter_->setXRange(min, max); } void Visualizer::toggleShowKeypoints() { show_keypoints_ = !show_keypoints_; } void Visualizer::toggleShowSource() { show_source_ = !show_source_; } void Visualizer::toggleShowTarget() { show_target_ = !show_target_; } void Visualizer::toggleShowRegistered() { show_registered_ = !show_registered_; } void Visualizer::updateText() { if (text_added_) { std::stringstream ss; ss << "f-score @ threshold = " << registrator_->getFScoreAtThreshold(registrator_->getResidualThreshold()); viewer_->updateText(ss.str(), 50, 175, "fscore"); ss.str(std::string()); // Clear stringstream ss << "max residual threshold = " << registrator_->getResidualThreshold() << " (modify: up/down)"; viewer_->updateText(ss.str(), 50, 200, "max_residual_threshold"); } } void Visualizer::resetRegisteredCloud() { if (r_cloud_visible_) { viewer_->removePointCloud("r_cloud"); r_cloud_visible_ = false; } if (show_registered_) { pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGB> color(registrator_->getRegisteredRGBCloud()); viewer_->addPointCloud<PointRGBT> (registrator_->getRegisteredRGBCloud(), color, "r_cloud"); r_cloud_visible_ = true; viewer_->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, point_size_, "r_cloud"); } } void Visualizer::computeResidualHistogram() { if (histogram_residuals_->size() != registrator_->getRegisteredToTargetResiduals()->size()) histogram_residuals_->resize(registrator_->getRegisteredToTargetResiduals()->size()); std::copy(registrator_->getRegisteredToTargetResiduals()->begin(), registrator_->getRegisteredToTargetResiduals()->end(), histogram_residuals_->begin()); util::removeElementsAboveThreshold(histogram_residuals_, registrator_->getResidualThreshold()); //Remove residual values above residual_threshold_ if (!histogram_computed_) { plotter_->clearPlots(); plotter_->addHistogramData(*histogram_residuals_, getNumHistogramBins()); } else { #if VTK_MAJOR_VERSION > 6 plotter_->clearPlots(); plotter_->addHistogramData(*histogram_residuals_, getNumHistogramBins()); #endif } histogram_computed_ = true; } void Visualizer::saveHistogramImage(std::string &filepath) { if (!histogram_computed_) computeResidualHistogram(); plotter_->spinOnce(); vtkWindowToImageFilter* wif = vtkWindowToImageFilter::New(); wif->Modified(); wif->SetInput(plotter_->getRenderWindow()); wif->SetInputBufferTypeToRGB(); wif->Update(); vtkPNGWriter* screenshot_writer = vtkPNGWriter::New(); #if VTK_MAJOR_VERSION<6 screenshot_writer->SetInput(wif->GetOutput()); #else screenshot_writer->SetInputData(wif->GetOutput()); #endif screenshot_writer->SetFileName (filepath.c_str()); screenshot_writer->Write(); screenshot_writer->Delete(); wif->Delete(); #if VTK_MAJOR_VERSION < 6 plotter_->clearPlots(); plotter_->close(); plotter_->getRenderWindow()->Delete(); #endif } void Visualizer::visualize() { if (!histogram_computed_) computeResidualHistogram(); while (!viewer_->wasStopped()) { viewer_->spinOnce(); #if VTK_MAJOR_VERSION > 6 plotter_->spinOnce(); #endif //Registered if (show_registered_ && !registrator_->getRegisteredRGBCloud()->empty() && !r_cloud_visible_) { pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGB> color(registrator_->getRegisteredRGBCloud()); viewer_->addPointCloud<PointRGBT> (registrator_->getRegisteredRGBCloud(), color, "r_cloud"); r_cloud_visible_ = true; viewer_->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, point_size_, "r_cloud"); } else if (!show_registered_ && r_cloud_visible_) { viewer_->removePointCloud("r_cloud"); r_cloud_visible_ = false; } //Source if (show_source_ && !registrator_->getSourceCloud()->empty() && !s_cloud_visible_) { pcl::visualization::PointCloudColorHandlerCustom<PointT> s_cloud_color_h (registrator_->getSourceCloud(), s_color_.r, s_color_.g, s_color_.b); viewer_->addPointCloud<PointT> (registrator_->getSourceCloud(), s_cloud_color_h, "s_cloud"); s_cloud_visible_ = true; viewer_->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, point_size_, "s_cloud"); } else if (!show_source_ && s_cloud_visible_) { viewer_->removePointCloud("s_cloud"); s_cloud_visible_ = false; } //Target if (show_target_ && !registrator_->getTargetCloud()->empty() && !t_cloud_visible_) { pcl::visualization::PointCloudColorHandlerCustom<PointT> t_cloud_color_h (registrator_->getTargetCloud(), t_color_.r, t_color_.g, t_color_.b); viewer_->addPointCloud<PointT> (registrator_->getTargetCloud(), t_cloud_color_h, "t_cloud"); t_cloud_visible_ = true; viewer_->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, point_size_, "t_cloud"); } else if (!show_target_ && t_cloud_visible_) { viewer_->removePointCloud("t_cloud"); t_cloud_visible_ = false; } //Source Keypoints if (show_keypoints_ && !keypoints_visible_) { if (!registrator_->getSourceKeypointsCloud()->empty()) { pcl::visualization::PointCloudColorHandlerCustom<PointT> s_cloud_keypoints_color_h (registrator_->getSourceKeypointsCloud(), keypoints_color_.r, keypoints_color_.g, keypoints_color_.b); viewer_->addPointCloud<PointT> (registrator_->getSourceKeypointsCloud(), s_cloud_keypoints_color_h, "s_cloud_keypoints"); viewer_->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, keypoint_size_, "s_cloud_keypoints"); keypoints_visible_ = true; } if (!registrator_->getSourceKeypointsCloud()->empty()) { pcl::visualization::PointCloudColorHandlerCustom<PointT> t_cloud_keypoints_color_h (registrator_->getTargetKeypointsCloud(), keypoints_color_.r, keypoints_color_.g, keypoints_color_.b); viewer_->addPointCloud<PointT> (registrator_->getTargetKeypointsCloud(), t_cloud_keypoints_color_h, "t_cloud_keypoints"); viewer_->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, keypoint_size_, "t_cloud_keypoints"); keypoints_visible_ = true; } } else if (!show_keypoints_ && keypoints_visible_) { viewer_->removePointCloud("s_cloud_keypoints"); viewer_->removePointCloud("t_cloud_keypoints"); keypoints_visible_ = false; } //Text if (!text_added_) { std::string command_panel = "S: toggle source cloud\nT: toggle target cloud\nR: toggle registered cloud\nK: toggle keypoints\nF: adjust center of revolution\nQ: quit"; viewer_->addText(command_panel, 50, 75, 15, 1, 1, 1, "command_panel"); std::stringstream ss; ss << "f-score @ threshold = " << registrator_->getFScoreAtThreshold(registrator_->getResidualThreshold()); viewer_->addText(ss.str(), 50, 175, 15, 1, 1, 1, "fscore"); ss.str(std::string()); // Clear stringstream ss << "max residual threshold = " << registrator_->getResidualThreshold() << " (modify: up/down)"; viewer_->addText(ss.str(), 50, 200, 15, 1, 1, 1, "max_residual_threshold"); text_added_ = true; } } }
drethage/PointCloudRegistrationTool
<|start_filename|>src/com/vdurmont/emoji/Fitzpatrick.kt<|end_filename|> package com.vdurmont.emoji /** * Enum that represents the Fitzpatrick modifiers supported by the emojis. * @author Improver: <NAME> [https://vk.com/irisism]<br></br> * Creator: <NAME> [<EMAIL>] */ enum class Fitzpatrick( /** * The unicode representation of the Fitzpatrick modifier */ val unicode: String ) { /** * Fitzpatrick modifier of type 1/2 (pale white/white) */ TYPE_1_2("\uD83C\uDFFB"), /** * Fitzpatrick modifier of type 3 (cream white) */ TYPE_3("\uD83C\uDFFC"), /** * Fitzpatrick modifier of type 4 (moderate brown) */ TYPE_4("\uD83C\uDFFD"), /** * Fitzpatrick modifier of type 5 (dark brown) */ TYPE_5("\uD83C\uDFFE"), /** * Fitzpatrick modifier of type 6 (black) */ TYPE_6("\uD83C\uDFFF"); companion object { fun fitzpatrickFromUnicode(unicode: String): Fitzpatrick? { for (v in values()) { if (v.unicode == unicode) { return v } } return null } fun fitzpatrickFromType(type: String): Fitzpatrick? { return try { valueOf(type.toUpperCase()) } catch (e: IllegalArgumentException) { null } } fun find(chars: CharArray, start: Int): Fitzpatrick? { if (chars.size < start + 1) return null var ch = chars[start] if (ch != '\uD83C') return null ch = chars[start + 1] when (ch) { '\uDFFB' -> return TYPE_1_2 '\uDFFC' -> return TYPE_3 '\uDFFD' -> return TYPE_4 '\uDFFE' -> return TYPE_5 '\uDFFF' -> return TYPE_6 } return null } } } <|start_filename|>src/com/vdurmont/emoji/EmojiManager.kt<|end_filename|> package com.vdurmont.emoji import com.vdurmont.emoji.EmojiLoader.loadEmojis import com.vdurmont.emoji.EmojiTrie.Matches import java.io.IOException /** * Holds the loaded emojis and provides search functions. * * @author Improver: <NAME> [https://vk.com/irisism]<br></br> * Creator: <NAME> [<EMAIL>] */ object EmojiManager { private const val PATH = "/emojis.json" private val EMOJIS_BY_ALIAS: MutableMap<String, Emoji> = HashMap() private val EMOJIS_BY_TAG: MutableMap<String, Set<Emoji>> = HashMap() lateinit var ALL_EMOJIS: List<Emoji> lateinit var EMOJI_TRIE: EmojiTrie /** * Returns all the [Emoji]s for a given tag. * * @param tag the tag * * @return the associated [Emoji]s, null if the tag * is unknown */ fun getForTag(tag: String?): Set<Emoji>? { return if (tag == null) { null } else EMOJIS_BY_TAG[tag] } /** * Returns the [Emoji] for a given alias. * * @param alias the alias * * @return the associated [Emoji], null if the alias * is unknown */ fun getForAlias(alias: String?): Emoji? { return if (alias == null || alias.isEmpty()) { null } else EMOJIS_BY_ALIAS[trimAlias(alias)] } private fun trimAlias(alias: String): String { val len = alias.length return alias.substring( if (alias[0] == ':') 1 else 0, if (alias[len - 1] == ':') len - 1 else len ) } /** * Returns the [Emoji] for a given unicode. * * @param unicode the the unicode * * @return the associated [Emoji], null if the * unicode is unknown */ fun getByUnicode(unicode: String?): Emoji? { if (unicode == null) { return null } val res = EmojiParser.getEmojiInPosition(unicode.toCharArray(), 0) ?: return null return res.emoji } /** * Returns all the [Emoji]s * * @return all the [Emoji]s */ val all: Collection<Emoji>? get() = ALL_EMOJIS /** * Tests if a given String is an emoji. * * @param string the string to test * @return true if the string is an emoji's unicode, false else */ fun isEmoji(string: String?): Boolean { if (string == null) return false val chars = string.toCharArray() val result = EmojiParser.getEmojiInPosition(chars, 0) return result != null && result.emojiStartIndex == 0 && result.endIndex == chars.size } /** * Tests if a given String contains an emoji. * * @param string the string to test * @return true if the string contains an emoji's unicode, false otherwise */ fun containsEmoji(string: String?): Boolean { return if (string == null) false else EmojiParser.getNextEmoji(string.toCharArray(), 0) != null } /** * Tests if a given String only contains emojis. * * @param string the string to test * @return true if the string only contains emojis, false else */ fun isOnlyEmojis(string: String?): Boolean { return string != null && EmojiParser.removeAllEmojis(string).isEmpty() } /** * Checks if sequence of chars contain an emoji. * * @param sequence Sequence of char that may contain emoji in full or * partially. * @return &lt;li&gt; * Matches.EXACTLY if char sequence in its entirety is an emoji * &lt;/li&gt; * &lt;li&gt; * Matches.POSSIBLY if char sequence matches prefix of an emoji * &lt;/li&gt; * &lt;li&gt; * Matches.IMPOSSIBLE if char sequence matches no emoji or prefix of an * emoji * &lt;/li&gt; */ fun isEmoji(sequence: CharArray): Matches { return EMOJI_TRIE.isEmoji(sequence) } /** * Returns all the tags in the database * * @return the tags */ val allTags: Collection<String> get() = EMOJIS_BY_TAG.keys init { try { val stream = EmojiLoader::class.java.getResourceAsStream(PATH) val emojis = loadEmojis(stream) for (emoji in emojis) { for (tag in emoji.tags) { val tagSet = EMOJIS_BY_TAG.computeIfAbsent(tag) { k: String? -> HashSet() } as HashSet tagSet.add(emoji) } for (alias in emoji.aliases) { EMOJIS_BY_ALIAS[alias] = emoji } } EMOJI_TRIE = EmojiTrie(emojis) emojis.sortWith(java.util.Comparator { e1: Emoji, e2: Emoji -> e2.unicode.length - e1.unicode.length }) ALL_EMOJIS = emojis stream.close() } catch (e: IOException) { throw RuntimeException(e) } } } <|start_filename|>src/com/vdurmont/emoji/Gender.kt<|end_filename|> package com.vdurmont.emoji /** * Создано 07.07.2020 * @author Improver: <NAME> [https://vk.com/irisism] */ enum class Gender(val unicode: String) { MALE("♂️"), FEMALE("♀️"); companion object { fun genderFromUnicode(unicode: String): Gender? { for (v in values()) { if (v.unicode == unicode) { return v } } return null } fun genderFromType(type: String): Gender? { return try { valueOf(type.toUpperCase()) } catch (e: IllegalArgumentException) { null } } fun find(chars: CharArray, startPos: Int): Gender? { if (startPos >= chars.size) return null val ch = chars[startPos] when (ch) { '♂' -> return MALE '♀' -> return FEMALE } return null } } } <|start_filename|>src/com/vdurmont/emoji/EmojiTrie.kt<|end_filename|> package com.vdurmont.emoji /** * * @author Improver: <NAME> [https://vk.com/irisism]<br></br> * Creator: <NAME> [<EMAIL>] */ class EmojiTrie(emojis: Collection<Emoji>) { private val root = Node() val maxDepth: Int /** * Checks if sequence of chars contain an emoji. * * @param sequence Sequence of char that may contain emoji in full or * partially. * @return &lt;li&gt; * Matches.EXACTLY if char sequence in its entirety is an emoji * &lt;/li&gt; * &lt;li&gt; * Matches.POSSIBLY if char sequence matches prefix of an emoji * &lt;/li&gt; * &lt;li&gt; * Matches.IMPOSSIBLE if char sequence matches no emoji or prefix of an * emoji * &lt;/li&gt; */ fun isEmoji(sequence: CharArray): Matches { return isEmoji(sequence, 0, sequence.size) } /** * Checks if the sequence of chars within the given bound indices contain an emoji. * * @see .isEmoji */ fun isEmoji(sequence: CharArray, start: Int, end: Int): Matches { if (start < 0 || start > end || end > sequence.size) { throw ArrayIndexOutOfBoundsException("start " + start + ", end " + end + ", length " + sequence.size) } var tree: Node = root for (i in start until end) { if (!tree.hasChild(sequence[i])) { return Matches.IMPOSSIBLE } tree = tree.getChild(sequence[i])?: return Matches.IMPOSSIBLE } return if (tree.isEndOfEmoji) Matches.EXACTLY else Matches.POSSIBLY } fun getBestEmoji(sequence: CharArray, start: Int): Emoji? { if (start < 0) { throw ArrayIndexOutOfBoundsException("start " + start + ", length " + sequence.size) } val end = sequence.size var tree: Node = root for (i in start until end) { if (!tree.hasChild(sequence[i])) { return if (tree.isEndOfEmoji) tree.emoji else null } tree = tree.getChild(sequence[i])?: return null } return if (tree.isEndOfEmoji) tree.emoji else null } /** * Finds Emoji instance from emoji unicode * * @param unicode unicode of emoji to get * @return Emoji instance if unicode matches and emoji, null otherwise. */ fun getEmoji(unicode: String): Emoji? { return getEmoji(unicode.toCharArray(), 0, unicode.length) } fun getEmoji(sequence: CharArray, start: Int, end: Int): Emoji? { if (start < 0 || start > end || end > sequence.size) { throw ArrayIndexOutOfBoundsException( "start " + start + ", end " + end + ", length " + sequence.size ) } var tree: Node = root for (i in 0 until end) { if (!tree.hasChild(sequence[i])) { return null } tree = tree.getChild(sequence[i])?: return null } return tree.emoji } enum class Matches { EXACTLY, POSSIBLY, IMPOSSIBLE; fun exactMatch(): Boolean { return this == EXACTLY } fun impossibleMatch(): Boolean { return this == IMPOSSIBLE } } private class Node { private val children: MutableMap<Char, Node> = HashMap() var emoji: Emoji? = null set(emoji) { field = emoji } fun hasChild(child: Char): Boolean { return children.containsKey(child) } fun addChild(child: Char) { children[child] = Node() } fun getChild(child: Char): Node? { return children[child] } val isEndOfEmoji: Boolean get() = emoji != null } init { var maxDepth = 0 for (emoji in emojis) { var tree: Node = root val chars = emoji.unicode.toCharArray() maxDepth = Math.max(maxDepth, chars.size) for (c in chars) { if (!tree.hasChild(c)) { tree.addChild(c) } tree = tree.getChild(c)?: break } tree.emoji = emoji } this.maxDepth = maxDepth } } <|start_filename|>src/com/vdurmont/emoji/Emoji.kt<|end_filename|> package com.vdurmont.emoji import java.nio.charset.StandardCharsets /** * This class represents an emoji.<br></br> * <br></br> * This object is immutable so it can be used safely in a multithreaded context. * * @author Improver: <NAME> [https://vk.com/irisism]<br></br> * Creator: <NAME> [<EMAIL>] */ class Emoji( /** * Returns the description of the emoji * * @return the description */ val description: String, val supportsFitzpatrick: Boolean, /** * Returns the aliases of the emoji * * @return the aliases (unmodifiable) */ val aliases: List<String>, val tags: List<String>, vararg bytes: Byte ) { val unicode: String val htmlDec: String val htmlHex: String /** * Constructor for the Emoji. * * @param description The description of the emoji * @param supportsFitzpatrick Whether the emoji supports Fitzpatrick modifiers * @param aliases the aliases for this emoji * @param tags the tags associated with this emoji * @param bytes the bytes that represent the emoji */ init { var count = 0 unicode = String(bytes, StandardCharsets.UTF_8) val stringLength = unicode.length val pointCodes = arrayOfNulls<String>(stringLength) val pointCodesHex = arrayOfNulls<String>(stringLength) var offset = 0 while (offset < stringLength) { val codePoint = unicode.codePointAt(offset) pointCodes[count] = String.format("&#%d;", codePoint) pointCodesHex[count++] = String.format("&#x%x;", codePoint) offset += Character.charCount(codePoint) } htmlDec = stringJoin(pointCodes, count) htmlHex = stringJoin(pointCodesHex, count) } /** * Method to replace String.join, since it was only introduced in java8 * * @param array the array to be concatenated * @return concatenated String */ private fun stringJoin(array: Array<String?>, count: Int): String { val joined = StringBuilder() for (i in 0 until count) joined.append(array[i]) return joined.toString() } /** * Returns wether the emoji supports the Fitzpatrick modifiers or not * * @return true if the emoji supports the Fitzpatrick modifiers */ fun supportsFitzpatrick(): Boolean { return supportsFitzpatrick } /** * Returns the unicode representation of the emoji associated with the * provided Fitzpatrick modifier.<br></br> * If the modifier is null, then the result is similar to * [Emoji.getUnicode] * * @param fitzpatrick the fitzpatrick modifier or null * @return the unicode representation * @throws UnsupportedOperationException if the emoji doesn't support the * Fitzpatrick modifiers */ fun getUnicode(fitzpatrick: Fitzpatrick?): String { if (!supportsFitzpatrick()) { throw UnsupportedOperationException( "Cannot get the unicode with a fitzpatrick modifier, " + "the emoji doesn't support fitzpatrick." ) } else if (fitzpatrick == null) { return this.unicode } return this.unicode + fitzpatrick.unicode } /** * Returns the HTML decimal representation of the emoji * * @return the HTML decimal representation */ fun getHtmlDecimal(): String { return htmlDec } /** * Returns the HTML hexadecimal representation of the emoji * * @return the HTML hexadecimal representation */ fun getHtmlHexadecimal(): String { return htmlHex } override fun equals(other: Any?): Boolean { return other is Emoji && other.unicode == unicode } override fun hashCode(): Int { return unicode.hashCode() } /** * Returns the String representation of the Emoji object.<br></br> * <br></br> * Example:<br></br> * `Emoji { * description='smiling face with open mouth and smiling eyes', * supportsFitzpatrick=false, * aliases=[smile], * tags=[happy, joy, pleased], * unicode='😄', * htmlDec='&#128516;', * htmlHex='&#x1f604;' * }` * * @return the string representation */ override fun toString(): String { return "Emoji{" + "description='" + description + '\'' + ", supportsFitzpatrick=" + supportsFitzpatrick + ", aliases=" + aliases + ", tags=" + tags + ", unicode='" + unicode + '\'' + ", htmlDec='" + htmlDec + '\'' + ", htmlHex='" + htmlHex + '\'' + '}' } } <|start_filename|>src/com/vdurmont/emoji/EmojiLoader.kt<|end_filename|> package com.vdurmont.emoji import org.json.JSONArray import org.json.JSONObject import java.io.* import java.nio.charset.StandardCharsets import java.util.* /** * Loads the emojis from a JSON database. * * @author Improver: <NAME> [https://vk.com/irisism]<br></br> * Creator: <NAME> [<EMAIL>] */ object EmojiLoader { /** * Loads a JSONArray of emojis from an InputStream, parses it and returns the * associated list of [Emoji]s * * @param stream the stream of the JSONArray * * @return the list of [Emoji]s * @throws IOException if an error occurs while reading the stream or parsing * the JSONArray */ @Throws(IOException::class) fun loadEmojis(stream: InputStream): MutableList<Emoji> { val emojisJSON = JSONArray(inputStreamToString(stream)) val emojis: MutableList<Emoji> = ArrayList(emojisJSON.length()) for (i in 0 until emojisJSON.length()) { val emoji = buildEmojiFromJSON(emojisJSON.getJSONObject(i)) if (emoji != null) { emojis.add(emoji) } } return emojis } @Throws(IOException::class) private fun inputStreamToString(stream: InputStream): String { val bytes = stream.readAllBytes() stream.close() return String(bytes, StandardCharsets.UTF_8) /*val sb = StringBuilder() val isr = InputStreamReader(stream, StandardCharsets.UTF_8) val br = BufferedReader(isr) var read: String? while (br.readLine().also { read = it } != null) { sb.append(read) } br.close() return sb.toString()*/ } /* private static final String[][] gender1 = { {"adult", "\uD83E\uDDD1"} , {"male", "\uD83D\uDC68"} , {"female", "\uD83D\uDC69"} }; private static final String[][] gender2 = { {"male", "\u200D♂️"} , {"female", "\u200D♀️"} }; private static final String[][] skins = { {"white", "\uD83C\uDFFB"} , {"cream white", "\uD83C\uDFFC"} , {"moderate brown", "\uD83C\uDFFD"} , {"dark brown", "\uD83C\uDFFE"} , {"black", "\uD83C\uDFFF"} }; protected static List<Emoji> buildEmojiesFromJSON(JSONObject json) throws UnsupportedEncodingException { if (!json.has("emoji")) { return null; } String pattern = json.getString("emoji"); List<String> aliases = jsonArrayToStringList(json.getJSONArray("aliases")); EmojiPrepare[] emojies; if (pattern.indexOf('{') != -1) { boolean hasGender1 = pattern.contains("{person}"); boolean hasGender2 = pattern.contains("{gender}"); boolean hasSkin = pattern.contains("{skin}"); var patterns = new LinkedList<EmojiPrepare>(); patterns.add(new EmojiPrepare(pattern, aliases)); if (hasSkin) { var tmp = new LinkedList<EmojiPrepare>(); for (EmojiPrepare i : patterns) { tmp.add(new EmojiPrepare(i.pattern.replace("{skin}", ""), aliases)); for (String[] g : skins) { var aa = new LinkedList<String>(); for (String a : i.aliases) aa.add(g[0] + ' ' + a); var newPattern = i.pattern.replace("{skin}", g[1]); tmp.add(new EmojiPrepare(newPattern, aa)); } } patterns = tmp; } if (hasGender1) { var tmp = new LinkedList<EmojiPrepare>(); for (EmojiPrepare i : patterns) for (String[] g : gender1) { var aa = new LinkedList<String>(); for (String a : i.aliases) aa.add(g[0] + ' ' + a); var newPattern = i.pattern.replace("{person}", g[1]); tmp.add(new EmojiPrepare(newPattern, aa)); } patterns = tmp; } if (hasGender2) { var tmp = new LinkedList<EmojiPrepare>(); for (EmojiPrepare i : patterns) for (String[] g : gender2) { tmp.add(new EmojiPrepare(i.pattern.replace("{gender}", ""), aliases)); var aa = new LinkedList<String>(); for (String a : i.aliases) aa.add(g[0] + ' ' + a); var newPattern = i.pattern.replace("{gender}", g[1]); tmp.add(new EmojiPrepare(newPattern, aa)); } patterns = tmp; } emojies = patterns.toArray(new EmojiPrepare[0]); } else emojies = new EmojiPrepare[] {new EmojiPrepare(pattern, aliases)}; String description = null; if (json.has("description")) { description = json.getString("description"); } boolean supportsFitzpatrick = false; if (json.has("supports_fitzpatrick")) { supportsFitzpatrick = json.getBoolean("supports_fitzpatrick"); } List<String> tags = jsonArrayToStringList(json.getJSONArray("tags")); ArrayList<Emoji> res = new ArrayList<>(); for (EmojiPrepare emoji : emojies) { byte[] bytes = emoji.pattern.getBytes(StandardCharsets.UTF_8); res.add(new Emoji(description, supportsFitzpatrick, emoji.aliases, tags, bytes)); } return res; //return new Emoji(description, supportsFitzpatrick, aliases, tags, bytes); } private static final class EmojiPrepare { List<String> aliases; String pattern; public EmojiPrepare(String patter, List<String> aliases) { this.aliases = aliases; this.pattern = patter; } }*/ @Throws(UnsupportedEncodingException::class) internal fun buildEmojiFromJSON( json: JSONObject ): Emoji? { if (!json.has("emoji")) { return null } val bytes = json.getString("emoji").toByteArray(StandardCharsets.UTF_8) var description: String? = null if (json.has("description")) { description = json.getString("description") } var supportsFitzpatrick = false if (json.has("supports_fitzpatrick")) { supportsFitzpatrick = json.getBoolean("supports_fitzpatrick") } val aliases = jsonArrayToStringList(json.getJSONArray("aliases")) val tags = jsonArrayToStringList(json.getJSONArray("tags")) return Emoji(description!!, supportsFitzpatrick, aliases, tags, *bytes) } private fun jsonArrayToStringList(array: JSONArray): List<String> { val strings: MutableList<String> = ArrayList(array.length()) for (i in 0 until array.length()) { strings.add(array.getString(i)) } return strings } } <|start_filename|>src/com/vdurmont/emoji/EmojiParser.kt<|end_filename|> package com.vdurmont.emoji; import com.vdurmont.emoji.EmojiManager.isEmoji import com.vdurmont.emoji.EmojiParser.FitzpatrickAction.* import com.vdurmont.emoji.EmojiParser.extractEmojiStrings import java.util.* /** * Provides methods to parse strings with emojis. * * @author Improver: <NAME> [https://vk.com/irisism]<br> * Creator: <NAME> [<EMAIL>] */ object EmojiParser { /** * See {@link #parseToAliases(String, FitzpatrickAction)} with the action * "PARSE" * * @param input the string to parse * @return the string with the emojis replaced by their alias. */ fun parseToAliases(input: String): String { return parseToAliases(input, PARSE); } /** * Replaces the emoji's unicode occurrences by one of their alias * (between 2 ':').<br> * Example: <code>😄</code> will be replaced by <code>:smile:</code><br> * <br> * When a fitzpatrick modifier is present with a PARSE action, a "|" will be * appendend to the alias, with the fitzpatrick type.<br> * Example: <code>👦🏿</code> will be replaced by * <code>:boy|type_6:</code><br> * The fitzpatrick types are: type_1_2, type_3, type_4, type_5, type_6<br> * <br> * When a fitzpatrick modifier is present with a REMOVE action, the modifier * will be deleted.<br> * Example: <code>👦🏿</code> will be replaced by <code>:boy:</code><br> * <br> * When a fitzpatrick modifier is present with a IGNORE action, the modifier * will be ignored.<br> * Example: <code>👦🏿</code> will be replaced by <code>:boy:🏿</code><br> * * @param input the string to parse * @param fitzpatrickAction the action to apply for the fitzpatrick modifiers * @return the string with the emojis replaced by their alias. */ fun parseToAliases(input: String, fitzpatrickAction: FitzpatrickAction): String { val emojiTransformer = object : EmojiTransformer { override fun transform(emoji: EmojiResult): String { when (fitzpatrickAction) { REMOVE -> return ":" + emoji.emoji.aliases.get(0) + ":"; IGNORE -> return ":" + emoji.emoji.aliases.get(0) + ":" + emoji.fitzpatrickUnicode; /*FitzpatrickAction.PARSE*/ else -> if (emoji.hasFitzpatrick()) { return ":" + emoji.emoji.aliases.get(0) + "|" + emoji.fitzpatrickType + ":"; } else { return ":" + emoji.emoji.aliases.get(0) + ":"; } } } }; return parseFromUnicode(input, emojiTransformer); } /** * Replace all emojis with character * * @param str the string to process * @param replacementString replacement the string that will replace all the emojis * @return the string with replaced character */ fun replaceAllEmojis(str: String, replacementString: String): String { val emojiTransformer: EmojiTransformer = object : EmojiTransformer { override fun transform(emoji: EmojiResult): String { return replacementString; } }; return parseFromUnicode(str, emojiTransformer); } /** * Replaces the emoji's aliases (between 2 ':') occurrences and the html * representations by their unicode.<br> * Examples:<br> * <code>:smile:</code> will be replaced by <code>😄</code><br> * <code>&amp;#128516;</code> will be replaced by <code>😄</code><br> * <code>:boy|type_6:</code> will be replaced by <code>👦🏿</code> * * @param input the string to parse * @return the string with the aliases and html representations replaced by * their unicode. */ fun parseToUnicode(input: String): String? { val sb = StringBuilder(input.length) var last = 0 while (last < input.length) { var alias: AliasCandidate? = getAliasAt(input, last) if (alias == null) { alias = getHtmlEncodedEmojiAt(input, last) } if (alias != null) { sb.append(alias.emoji.unicode) last = alias.endIndex if (alias.fitzpatrick != null) { sb.append(alias.fitzpatrick!!.unicode) } } else { sb.append(input[last]) } last++ } return sb.toString() } /** * Finds the alias in the given string starting at the given point, null otherwise */ private fun getAliasAt(input: String, start: Int): AliasCandidate? { if (input.length < start + 2 || input[start] != ':') return null // Aliases start with : val aliasEnd = input.indexOf(':', start + 2) // Alias must be at least 1 char in length if (aliasEnd == -1) return null // No alias end found val fitzpatrickStart = input.indexOf('|', start + 2) if (fitzpatrickStart != -1 && fitzpatrickStart < aliasEnd) { val emoji = EmojiManager.getForAlias(input.substring(start, fitzpatrickStart)) ?: return null // Not a valid alias if (!emoji.supportsFitzpatrick()) return null // Fitzpatrick was specified, but the emoji does not support it val fitzpatrick = Fitzpatrick.fitzpatrickFromType(input.substring(fitzpatrickStart + 1, aliasEnd)) return AliasCandidate(emoji, fitzpatrick, start, aliasEnd) } val emoji = EmojiManager.getForAlias(input.substring(start, aliasEnd)) ?: return null // Not a valid alias return AliasCandidate(emoji, null, start, aliasEnd) } /** * Finds the HTML encoded emoji in the given string starting at the given point, null otherwise */ private fun getHtmlEncodedEmojiAt(input: String, start: Int): AliasCandidate? { if (input.length < start + 4 || input[start] != '&' || input[start + 1] != '#') return null var longestEmoji: Emoji? = null var longestCodePointEnd = -1 val chars = CharArray(EmojiManager.EMOJI_TRIE.maxDepth) var charsIndex = 0 var codePointStart = start do { val codePointEnd = input.indexOf(';', codePointStart + 3) // Code point must be at least 1 char in length if (codePointEnd == -1) break charsIndex += try { val radix = if (input[codePointStart + 2] == 'x') 16 else 10 val codePoint = input.substring(codePointStart + 2 + radix / 16, codePointEnd).toInt(radix) Character.toChars(codePoint, chars, charsIndex) } catch (e: IllegalArgumentException) { break } val foundEmoji = EmojiManager.EMOJI_TRIE.getEmoji(chars, 0, charsIndex) if (foundEmoji != null) { longestEmoji = foundEmoji longestCodePointEnd = codePointEnd } codePointStart = codePointEnd + 1 } while (input.length > codePointStart + 4 && input[codePointStart] == '&' && input[codePointStart + 1] == '#' && charsIndex < chars.size && !EmojiManager.EMOJI_TRIE.isEmoji(chars, 0, charsIndex).impossibleMatch() ) return if (longestEmoji == null) null else AliasCandidate(longestEmoji, null, start, longestCodePointEnd) } /** * See [.parseToHtmlDecimal] with the action * "PARSE" * * @param input the string to parse * @return the string with the emojis replaced by their html decimal * representation. */ fun parseToHtmlDecimal(input: String): String? { return parseToHtmlDecimal(input, PARSE) } /** * Replaces the emoji's unicode occurrences by their html representation.<br> * Example: <code>😄</code> will be replaced by <code>&amp;#128516;</code><br> * <br> * When a fitzpatrick modifier is present with a PARSE or REMOVE action, the * modifier will be deleted from the string.<br> * Example: <code>👦🏿</code> will be replaced by * <code>&amp;#128102;</code><br> * <br> * When a fitzpatrick modifier is present with a IGNORE action, the modifier * will be ignored and will remain in the string.<br> * Example: <code>👦🏿</code> will be replaced by * <code>&amp;#128102;🏿</code> * * @param input the string to parse * @param fitzpatrickAction the action to apply for the fitzpatrick modifiers * @return the string with the emojis replaced by their html decimal * representation. */ fun parseToHtmlDecimal(input: String, fitzpatrickAction: FitzpatrickAction): String { val emojiTransformer = object : EmojiTransformer { override fun transform(emoji: EmojiResult): String { return when (fitzpatrickAction) { PARSE, REMOVE -> emoji.emoji.getHtmlDecimal(); IGNORE -> emoji.emoji.getHtmlDecimal() + emoji.fitzpatrickUnicode; }; } }; return parseFromUnicode(input, emojiTransformer); } /** * See {@link #parseToHtmlHexadecimal(String, FitzpatrickAction)} with the * action "PARSE" * * @param input the string to parse * @return the string with the emojis replaced by their html hex * representation. */ fun parseToHtmlHexadecimal(input: String): String { return parseToHtmlHexadecimal(input, PARSE); } /** * Replaces the emoji's unicode occurrences by their html hex * representation.<br> * Example: <code>👦</code> will be replaced by <code>&amp;#x1f466;</code><br> * <br> * When a fitzpatrick modifier is present with a PARSE or REMOVE action, the * modifier will be deleted.<br> * Example: <code>👦🏿</code> will be replaced by * <code>&amp;#x1f466;</code><br> * <br> * When a fitzpatrick modifier is present with a IGNORE action, the modifier * will be ignored and will remain in the string.<br> * Example: <code>👦🏿</code> will be replaced by * <code>&amp;#x1f466;🏿</code> * * @param input the string to parse * @param fitzpatrickAction the action to apply for the fitzpatrick modifiers * @return the string with the emojis replaced by their html hex * representation. */ fun parseToHtmlHexadecimal(input: String,fitzpatrickAction: FitzpatrickAction): String { val emojiTransformer = object : EmojiTransformer { override fun transform(unicodeCandidate: EmojiResult): String { return when (fitzpatrickAction) { PARSE, REMOVE -> unicodeCandidate.emoji.getHtmlHexadecimal(); IGNORE -> unicodeCandidate.emoji.getHtmlHexadecimal() + unicodeCandidate.fitzpatrickUnicode; }; } }; return parseFromUnicode(input, emojiTransformer); } /** * Removes all emojis from a String * * @param str the string to process * @return the string without any emoji */ fun removeAllEmojis(str: String): String { val emojiTransformer = object : EmojiTransformer { override fun transform(emoji: EmojiResult): String { return ""; } }; return parseFromUnicode(str, emojiTransformer); } /** * Removes a set of emojis from a String * * @param str the string to process * @param emojisToRemove the emojis to remove from this string * @return the string without the emojis that were removed */ fun removeEmojis(str: String, emojisToRemove: Collection<Emoji>):String { val emojiTransformer = object : EmojiTransformer { override fun transform(emoji: EmojiResult): String { if (!emojisToRemove.contains(emoji.emoji)) { return emoji.emoji.unicode + emoji.fitzpatrickUnicode; } return ""; } }; return parseFromUnicode(str, emojiTransformer); } /** * Removes all the emojis in a String except a provided set * * @param str the string to process * @param emojisToKeep the emojis to keep in this string * @return the string without the emojis that were removed */ fun removeAllEmojisExcept(str: String, emojisToKeep: Collection<Emoji>): String { val emojiTransformer = object : EmojiTransformer { override fun transform(emoji: EmojiResult): String { if (emojisToKeep.contains(emoji.emoji)) { return emoji.emoji.unicode + emoji.fitzpatrickUnicode; } return ""; } }; return parseFromUnicode(str, emojiTransformer); } /** * Detects all unicode emojis in input string and replaces them with the * return value of transformer.transform() * * @param input the string to process * @param transformer emoji transformer to apply to each emoji * @return input string with all emojis transformed */ fun parseFromUnicode(input: String, transformer: EmojiTransformer): String { var prev = 0; val sb = StringBuilder(input.length); val replacements = getEmojies(input); for (candidate in replacements) { sb.append(input, prev, candidate.emojiStartIndex); sb.append(transformer.transform(candidate)); prev = candidate.endIndex; } return sb.append(input.substring(prev)).toString(); } /*fun extractEmojiStrings(input: String?): List<String?>? { return extractEmojiStrings(input, 0) }*/ fun extractEmojiStrings(input: String, limit: Int = 0): List<String?>? { val items = extractEmojis(input, limit) val result: MutableList<String?> = ArrayList(items.size) for (i in items) { result.add(i.toString()) } return result } /*fun extractEmojis(input: String): List<EmojiResult?>? { return getEmojies(input, 0) }*/ fun extractEmojis(input: String, limit: Int = 0): List<EmojiResult> { return getEmojies(input, limit) } /** * Generates a list UnicodeCandidates found in input string. A * UnicodeCandidate is created for every unicode emoticon found in input * string, additionally if Fitzpatrick modifier follows the emoji, it is * included in UnicodeCandidate. Finally, it contains start and end index of * unicode emoji itself (WITHOUT Fitzpatrick modifier whether it is there or * not!). * * @param input String to find all unicode emojis in * @return List of UnicodeCandidates for each unicode emote in text */ fun getEmojies(input: String, limit: Int): List<EmojiResult> { var limit = limit val inputCharArray = input.toCharArray() val candidates: MutableList<EmojiResult> = ArrayList() var next: EmojiResult? var i = 0 while (getNextEmoji(inputCharArray, i).also { next = it } != null) { next!! candidates.add(next!!) if (limit != 0) { limit-- if (limit <= 0) break } i = next!!.endIndex } return candidates } fun getEmojies(input: String): List<EmojiResult> { return getEmojies(input, 0) } /** * Finds the next UnicodeCandidate after a given starting index * * @param chars char array to find UnicodeCandidate in * @param start starting index for search * @return the next UnicodeCandidate or null if no UnicodeCandidate is found after start index */ fun getNextEmoji(chars: CharArray, start: Int): EmojiResult? { for (i in start until chars.size) { val emoji = getEmojiInPosition(chars, i); if (emoji != null) return emoji; } return null; } fun getEmojiInPosition(chars: CharArray, start: Int): EmojiResult? { val emoji = getBestBaseEmoji(chars, start); if (emoji == null) return null; var fitzpatrick: Fitzpatrick? = null; var gender: Gender? = null; var endPos = start + emoji.unicode.length; if (emoji.supportsFitzpatrick) { fitzpatrick = Fitzpatrick.find(chars, endPos); if (fitzpatrick != null) { endPos += 2; } val gg = findGender(chars, endPos); if (gg != null) { endPos = gg.endPos + 1; gender = gg.gender; } } if (chars.size > endPos) { val ch = chars[endPos]; if (ch == '\uFE0F') endPos++; } return EmojiResult(emoji, fitzpatrick, gender, chars, start, endPos); } private fun findGender(chars: CharArray, startPos: Int): GenderMatch? { val len = chars.size; if (len <= startPos) return null; var pos = startPos; val ch = chars[pos]; if (ch != '\u200D') return null; pos++; val gender = Gender.find(chars, pos) ?: return null; return GenderMatch(gender, pos); } private class GenderMatch(val gender: Gender?, val endPos: Int) /** * Returns end index of a unicode emoji if it is found in text starting at * index startPos, -1 if not found. * This returns the longest matching emoji, for example, in * "\uD83D\uDC68\u200D\uD83D\uDC69\u200D\uD83D\uDC66" * it will find alias:family_man_woman_boy, NOT alias:man * * @param text the current text where we are looking for an emoji * @param startPos the position in the text where we should start looking for * an emoji end * @return the end index of the unicode emoji starting at startPos. -1 if not * found */ fun getBestBaseEmoji(text: CharArray, startPos: Int): Emoji? { return EmojiManager.EMOJI_TRIE.getBestEmoji(text, startPos); } class EmojiResult( val emoji: Emoji, val fitzpatrick: Fitzpatrick?, val gender: Gender?, val source: CharArray, val emojiStartIndex: Int, val endIndex: Int ) { fun hasFitzpatrick(): Boolean { return fitzpatrick != null } val fitzpatrickType: String get() = if (hasFitzpatrick()) fitzpatrick!!.name else "" val fitzpatrickUnicode: String get() = if (hasFitzpatrick()) fitzpatrick!!.unicode else "" val emojiEndIndex: Int get() = emojiStartIndex + emoji.unicode.length val fitzpatrickEndIndex: Int get() = emojiEndIndex + if (fitzpatrick != null) 2 else 0 private var sub: String? = null override fun toString(): String { if (sub != null) return sub!! val len = endIndex - emojiStartIndex val sub = CharArray(len) System.arraycopy(source, emojiStartIndex, sub, 0, len) this.sub = String(sub) return this.sub!! } } private class AliasCandidate ( val emoji: Emoji, val fitzpatrick: Fitzpatrick?, val startIndex: Int, val endIndex: Int ) /** * Enum used to indicate what should be done when a Fitzpatrick modifier is * found. */ enum class FitzpatrickAction { /** * Tries to match the Fitzpatrick modifier with the previous emoji */ PARSE, /** * Removes the Fitzpatrick modifier from the string */ REMOVE, /** * Ignores the Fitzpatrick modifier (it will stay in the string) */ IGNORE } interface EmojiTransformer { fun transform(emoji: EmojiResult): String } } fun main() { val text = "\uD83D\uDC68\u200D\uD83D\uDCBB\uD83E\uDDB9\uD83C\uDFFE\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83D\uDD2C\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83C\uDF73\uD83D\uDC70\uD83C\uDFFE\uD83E\uDDDB\uD83C\uDFFD\u200D♂️\uD83E\uDD31\uD83C\uDFFF\uD83D\uDC68\uD83C\uDFFC\u200D\uD83C\uDFEB\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83C\uDF73\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83C\uDF73\uD83D\uDC73\uD83C\uDFFB\u200D♂️" val items = extractEmojiStrings(text) println(items) val res = isEmoji("\uD83E\uDDDB\uD83C\uDFFD\u200D♂️ ") println(res) }
iris2iris/iris-emoji-kotlin
<|start_filename|>src/main/java/org/jenkinsci/plugins/nomad/NomadComputer.java<|end_filename|> package org.jenkinsci.plugins.nomad; import hudson.model.Executor; import hudson.model.Queue; import hudson.slaves.AbstractCloudComputer; import java.util.logging.Level; import java.util.logging.Logger; public class NomadComputer extends AbstractCloudComputer<NomadWorker> { private static final Logger LOGGER = Logger.getLogger(NomadComputer.class.getName()); public NomadComputer(NomadWorker worker) { super(worker); } @Override public void taskAccepted(Executor executor, Queue.Task task) { super.taskAccepted(executor, task); if (!isReusable()) { setAcceptingTasks(false); } LOGGER.log(Level.INFO, " Computer " + this + ": task accepted"); } private boolean isReusable() { NomadWorker node = getNode(); return node == null ? false : node.isReusable(); } @Override public void taskCompleted(Executor executor, Queue.Task task, long durationMS) { super.taskCompleted(executor, task, durationMS); LOGGER.log(Level.INFO, " Computer " + this + ": task completed"); } @Override public void taskCompletedWithProblems(Executor executor, Queue.Task task, long durationMS, Throwable problems) { super.taskCompletedWithProblems(executor, task, durationMS, problems); LOGGER.log(Level.WARNING, " Computer " + this + " task completed with problems"); } @Override public String toString() { return String.format("%s (worker: %s)", getName(), getNode()); } } <|start_filename|>src/main/java/org/jenkinsci/plugins/nomad/Api/DevicePluginGroup.java<|end_filename|> package org.jenkinsci.plugins.nomad.Api; import org.jenkinsci.plugins.nomad.NomadDevicePluginTemplate; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * Only required for backward compatibility */ @Deprecated public class DevicePluginGroup { private final List<Device> devicePlugins = new ArrayList<Device>(); public DevicePluginGroup( List<NomadDevicePluginTemplate> devicePluginTemplate ) { Iterator<NomadDevicePluginTemplate> devicePluginIterator = devicePluginTemplate.iterator(); while (devicePluginIterator.hasNext()) { NomadDevicePluginTemplate nextTemplate = devicePluginIterator.next(); devicePlugins.add(new Device(nextTemplate)); } } public List<Device> getDevicePlugins() { Iterator<Device> devicePluginIterator = devicePlugins.iterator(); List<Device> DevicePlugins = new ArrayList<Device>(); while (devicePluginIterator.hasNext()) { Device nextDevicePlugin = devicePluginIterator.next(); DevicePlugins.add(nextDevicePlugin); } return DevicePlugins; } } <|start_filename|>src/main/java/org/jenkinsci/plugins/nomad/Api/RestartPolicy.java<|end_filename|> package org.jenkinsci.plugins.nomad.Api; /** * Only required for backward compatibility */ @Deprecated public class RestartPolicy { private Long Interval; private String Mode; private Long Delay; private Integer Attempts; public RestartPolicy(Integer attempts, Long interval, Long delay, String mode) { Interval = interval; Mode = mode; Delay = delay; Attempts = attempts; } public Long getInterval() { return Interval; } public void setInterval(Long interval) { Interval = interval; } public String getMode() { return Mode; } public void setMode(String mode) { Mode = mode; } public Long getDelay() { return Delay; } public void setDelay(Long delay) { Delay = delay; } public Integer getAttempts() { return Attempts; } public void setAttempts(Integer attempts) { Attempts = attempts; } } <|start_filename|>src/main/java/org/jenkinsci/plugins/nomad/Api/EphemeralDisk.java<|end_filename|> package org.jenkinsci.plugins.nomad.Api; /** * Only required for backward compatibility */ @Deprecated public class EphemeralDisk { private Integer SizeMB; private Boolean Migrate; private Boolean Sticky; public EphemeralDisk(Integer sizeMB, Boolean migrate, Boolean sticky) { SizeMB = sizeMB; Migrate = migrate; Sticky = sticky; } public Integer getSizeMB() { return SizeMB; } public void setSizeMB(Integer sizeMB) { SizeMB = sizeMB; } public Boolean getMigrate() { return Migrate; } public void setMigrate(Boolean migrate) { Migrate = migrate; } public Boolean getSticky() { return Sticky; } public void setSticky(Boolean sticky) { Sticky = sticky; } } <|start_filename|>src/main/java/org/jenkinsci/plugins/nomad/NomadPortTemplate.java<|end_filename|> package org.jenkinsci.plugins.nomad; import hudson.Extension; import hudson.model.Describable; import hudson.model.Descriptor; import jenkins.model.Jenkins; import org.kohsuke.stapler.DataBoundConstructor; /** * Only required for backward compatibility */ @Deprecated public class NomadPortTemplate implements Describable<NomadPortTemplate> { private final String label; private final String value; private NomadWorkerTemplate worker; @DataBoundConstructor public NomadPortTemplate(String label, String value) { this.label = label; this.value = value; readResolve(); } protected Object readResolve() { return this; } @Override @SuppressWarnings("unchecked") public Descriptor<NomadPortTemplate> getDescriptor() { return Jenkins.get().getDescriptor(getClass()); } public String getLabel() { return label; } public String getValue() { return value; } public NomadWorkerTemplate getNomadWorkerTemplate() { return worker; } public void setNomadWorkerTemplate(NomadWorkerTemplate worker) { this.worker = worker; } @Extension public static final class DescriptorImpl extends Descriptor<NomadPortTemplate> { public DescriptorImpl() { load(); } @Override public String getDisplayName() { return ""; } } }
j3t/nomad-plugin
<|start_filename|>Code/Topshelf/src/Topshelf/Runtime/Windows/Kernel32.cs<|end_filename|> // Copyright 2007-2012 <NAME>, <NAME>, <NAME>, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace Topshelf.Runtime.Windows { using System; using System.Runtime.InteropServices; static class Kernel32 { public static uint TH32CS_SNAPPROCESS = 2; [StructLayout(LayoutKind.Sequential)] public struct PROCESSENTRY32 { public uint dwSize; public uint cntUsage; public uint th32ProcessID; public IntPtr th32DefaultHeapID; public uint th32ModuleID; public uint cntThreads; public uint th32ParentProcessID; public int pcPriClassBase; public uint dwFlags; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string szExeFile; } ; [DllImport("kernel32.dll", SetLastError = true)] public static extern IntPtr CreateToolhelp32Snapshot(uint dwFlags, uint th32ProcessID); [DllImport("kernel32.dll")] public static extern bool Process32First(IntPtr hSnapshot, ref PROCESSENTRY32 lppe); [DllImport("kernel32.dll")] public static extern bool Process32Next(IntPtr hSnapshot, ref PROCESSENTRY32 lppe); } } <|start_filename|>Code/Topshelf/src/Topshelf/Configuration/ServiceConfigurators/ServiceConfiguratorBase.cs<|end_filename|> // Copyright 2007-2012 <NAME>, <NAME>, <NAME>, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace Topshelf.ServiceConfigurators { using System; using Runtime; public abstract class ServiceConfiguratorBase { protected readonly ServiceEventsImpl ServiceEvents; protected ServiceConfiguratorBase() { ServiceEvents = new ServiceEventsImpl(); } public void BeforeStartingService(Action<HostStartContext> callback) { ServiceEvents.AddBeforeStart(callback); } public void AfterStartingService(Action<HostStartedContext> callback) { ServiceEvents.AddAfterStart(callback); } public void BeforeStoppingService(Action<HostStopContext> callback) { ServiceEvents.AddBeforeStop(callback); } public void AfterStoppingService(Action<HostStoppedContext> callback) { ServiceEvents.AddAfterStop(callback); } } } <|start_filename|>Code/DotNetZip/Zip Tests/UpdateTests.cs<|end_filename|> // UpdateTests.cs // ------------------------------------------------------------------ // // Copyright (c) 2009-2011 <NAME> // All rights reserved. // // This code module is part of DotNetZip, a zipfile class library. // // ------------------------------------------------------------------ // // This code is licensed under the Microsoft Public License. // See the file License.txt for the license details. // More info on: http://dotnetzip.codeplex.com // // ------------------------------------------------------------------ // // last saved (in emacs): // Time-stamp: <2011-August-05 16:52:59> // // ------------------------------------------------------------------ // // This module defines tests for updating zip files via DotNetZip. // // ------------------------------------------------------------------ using System; using System.Linq; using System.IO; using System.Text; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; using Ionic.Zip; using Ionic.Zip.Tests.Utilities; namespace Ionic.Zip.Tests.Update { /// <summary> /// Summary description for UnitTest1 /// </summary> [TestClass] public class UpdateTests : IonicTestClass { public UpdateTests() : base() { } [TestMethod] public void UpdateZip_AddNewDirectory() { string zipFileToCreate = Path.Combine(TopLevelDir, "UpdateZip_AddNewDirectory.zip"); String CommentOnArchive = "BasicTests::UpdateZip_AddNewDirectory(): This archive will be overwritten."; string newComment = "This comment has been OVERWRITTEN." + DateTime.Now.ToString("G"); string dirToZip = Path.Combine(TopLevelDir, "zipup"); int i, j; int entries = 0; string subdir = null; String filename = null; int subdirCount = _rnd.Next(4) + 4; for (i = 0; i < subdirCount; i++) { subdir = Path.Combine(dirToZip, "Directory." + i); Directory.CreateDirectory(subdir); int fileCount = _rnd.Next(3) + 3; for (j = 0; j < fileCount; j++) { filename = Path.Combine(subdir, "file" + j + ".txt"); TestUtilities.CreateAndFillFileText(filename, _rnd.Next(12000) + 5000); entries++; } } using (ZipFile zip = new ZipFile()) { zip.AddDirectory(dirToZip); zip.Comment = CommentOnArchive; zip.Save(zipFileToCreate); } Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), entries, "The created Zip file has an unexpected number of entries."); BasicVerifyZip(zipFileToCreate); // Now create a new subdirectory and add that one subdir = Path.Combine(TopLevelDir, "NewSubDirectory"); Directory.CreateDirectory(subdir); filename = Path.Combine(subdir, "newfile.txt"); TestUtilities.CreateAndFillFileText(filename, _rnd.Next(12000) + 5000); entries++; using (ZipFile zip = new ZipFile(zipFileToCreate)) { zip.AddDirectory(subdir); zip.Comment = newComment; // this will add entries into the existing zip file zip.Save(); } Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), entries, "The overwritten Zip file has the wrong number of entries."); using (ZipFile readzip = new ZipFile(zipFileToCreate)) { Assert.AreEqual<string>(newComment, readzip.Comment, "The zip comment is incorrect."); } } [TestMethod] public void UpdateZip_ChangeMetadata_AES() { Directory.SetCurrentDirectory(TopLevelDir); string zipFileToCreate = Path.Combine(TopLevelDir, "UpdateZip_ChangeMetadata_AES.zip"); string subdir = Path.Combine(TopLevelDir, "A"); Directory.CreateDirectory(subdir); // create the files int numFilesToCreate = _rnd.Next(13) + 24; //int numFilesToCreate = 2; string filename = null; for (int j = 0; j < numFilesToCreate; j++) { filename = Path.Combine(subdir, String.Format("file{0:D3}.txt", j)); TestUtilities.CreateAndFillFileText(filename, _rnd.Next(34000) + 5000); //TestUtilities.CreateAndFillFileText(filename, 500); } string password = <PASSWORD>.Get<PASSWORD>() + Path.GetFileNameWithoutExtension(Path.GetRandomFileName()); using (var zip = new ZipFile()) { zip.Password = password; zip.Encryption = EncryptionAlgorithm.WinZipAes256; zip.AddFiles(Directory.GetFiles(subdir), ""); zip.Save(zipFileToCreate); } // Verify the correct number of files are in the zip Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), numFilesToCreate, "Fie! The updated Zip file has the wrong number of entries."); // test extract (and implicitly check CRCs, passwords, etc) VerifyZip(zipFileToCreate, password); byte[] buffer = new byte[_rnd.Next(10000) + 10000]; _rnd.NextBytes(buffer); using (var zip = ZipFile.Read(zipFileToCreate)) { // modify the metadata for an entry zip[0].LastModified = DateTime.Now - new TimeSpan(7 * 31, 0, 0); zip.Password = password; zip.Encryption = EncryptionAlgorithm.WinZipAes256; zip.AddEntry(Path.GetRandomFileName(), buffer); zip.Save(); } // Verify the correct number of files are in the zip Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), numFilesToCreate + 1, "Fie! The updated Zip file has the wrong number of entries."); // test extract (and implicitly check CRCs, passwords, etc) VerifyZip(zipFileToCreate, password); } private void VerifyZip(string zipfile, string password) { Stream bitBucket = Stream.Null; TestContext.WriteLine("Checking file {0}", zipfile); using (ZipFile zip = ZipFile.Read(zipfile)) { zip.Password = password; zip.BufferSize = 65536; foreach (var s in zip.EntryFileNames) { TestContext.WriteLine(" Entry: {0}", s); zip[s].Extract(bitBucket); } } System.Threading.Thread.Sleep(0x500); } [TestMethod] public void UpdateZip_RemoveEntry_ByLastModTime() { // select the name of the zip file string zipFileToCreate = Path.Combine(TopLevelDir, "UpdateZip_RemoveEntry_ByLastModTime.zip"); // create the subdirectory string subdir = Path.Combine(TopLevelDir, "A"); Directory.CreateDirectory(subdir); // create the files int numFilesToCreate = _rnd.Next(13) + 24; string filename = null; int entriesAdded = 0; for (int j = 0; j < numFilesToCreate; j++) { filename = Path.Combine(subdir, String.Format("file{0:D3}.txt", j)); TestUtilities.CreateAndFillFileText(filename, _rnd.Next(34000) + 5000); entriesAdded++; } // Add the files to the zip, save the zip Directory.SetCurrentDirectory(TopLevelDir); int ix = 0; System.DateTime origDate = new System.DateTime(2007, 1, 15, 12, 1, 0); using (ZipFile zip1 = new ZipFile()) { String[] filenames = Directory.GetFiles("A"); foreach (String f in filenames) { ZipEntry e = zip1.AddFile(f, ""); e.LastModified = origDate + new TimeSpan(24 * 31 * ix, 0, 0); // 31 days * number of entries ix++; } zip1.Comment = "UpdateTests::UpdateZip_RemoveEntry_ByLastModTime(): This archive will soon be updated."; zip1.Save(zipFileToCreate); } // Verify the files are in the zip Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), entriesAdded, "The Zip file has the wrong number of entries."); // selectively remove a few files in the zip archive var threshold = new TimeSpan(24 * 31 * (2 + _rnd.Next(ix - 12)), 0, 0); int numRemoved = 0; using (ZipFile zip2 = ZipFile.Read(zipFileToCreate)) { // We cannot remove the entry from the list, within the context of // an enumeration of said list. // So we add the doomed entry to a list to be removed // later. // pass 1: mark the entries for removal var entriesToRemove = new List<ZipEntry>(); foreach (ZipEntry e in zip2) { if (e.LastModified < origDate + threshold) { entriesToRemove.Add(e); numRemoved++; } } // pass 2: actually remove the entry. foreach (ZipEntry zombie in entriesToRemove) zip2.RemoveEntry(zombie); zip2.Comment = "UpdateTests::UpdateZip_RemoveEntry_ByLastModTime(): This archive has been updated."; zip2.Save(); } // Verify the correct number of files are in the zip Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), entriesAdded - numRemoved, "Fie! The updated Zip file has the wrong number of entries."); // verify that all entries in the archive are within the threshold using (ZipFile zip3 = ZipFile.Read(zipFileToCreate)) { foreach (ZipEntry e in zip3) Assert.IsTrue((e.LastModified >= origDate + threshold), "Merde. The updated Zip file has entries that lie outside the threshold."); } } [TestMethod] public void UpdateZip_RemoveEntry_ByFilename_WithPassword() { string password = <PASSWORD>"; string filename = null; int entriesToBeAdded = 0; string repeatedLine = null; int j; // select the name of the zip file string zipFileToCreate = "ByFilename_WithPassword.zip"; // create the subdirectory string subdir = Path.Combine(TopLevelDir, "A"); Directory.CreateDirectory(subdir); // create a bunch of files, fill them with content int numFilesToCreate = _rnd.Next(13) + 24; for (j = 0; j < numFilesToCreate; j++) { filename = String.Format("file{0:D3}.txt", j); repeatedLine = String.Format("This line is repeated over and over and over in file {0}", filename); TestUtilities.CreateAndFillFileText(Path.Combine(subdir, filename), repeatedLine, _rnd.Next(34000) + 5000); entriesToBeAdded++; } // Add the files to the zip, save the zip Directory.SetCurrentDirectory(TopLevelDir); using (ZipFile zip1 = new ZipFile()) { String[] filenames = Directory.GetFiles("A"); zip1.Password = password; zip1.AddFiles(filenames, ""); zip1.Comment = "UpdateTests::UpdateZip_RemoveEntry_ByFilename_WithPassword(): This archive will be updated."; zip1.Save(zipFileToCreate); } // Verify the files are in the zip Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), entriesToBeAdded, "The Zip file has the wrong number of entries."); // selectively remove a few files in the zip archive var filesToRemove = new List<string>(); int numToRemove = _rnd.Next(numFilesToCreate - 4) + 1; using (ZipFile zip2 = ZipFile.Read(zipFileToCreate)) { for (j = 0; j < numToRemove; j++) { // select a new, uniquely named file to create do { filename = String.Format("file{0:D3}.txt", _rnd.Next(numFilesToCreate)); } while (filesToRemove.Contains(filename)); // add this file to the list filesToRemove.Add(filename); zip2.RemoveEntry(filename); } zip2.Comment = "This archive has been modified. Some files have been removed."; zip2.Save(); } // extract all files, verify none should have been removed, // and verify the contents of those that remain using (ZipFile zip3 = ZipFile.Read(zipFileToCreate)) { foreach (string s1 in zip3.EntryFileNames) { Assert.IsFalse(filesToRemove.Contains(s1), String.Format("File ({0}) was not expected.", s1)); zip3[s1].ExtractWithPassword("extract", password); repeatedLine = String.Format("This line is repeated over and over and over in file {0}", s1); // verify the content of the updated file. var sr = new StreamReader(Path.Combine("extract", s1)); string sLine = sr.ReadLine(); sr.Close(); Assert.AreEqual<string>(repeatedLine, sLine, String.Format("The content of the originally added file ({0}) in the zip archive is incorrect.", s1)); } } // Verify the files are in the zip Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), entriesToBeAdded - filesToRemove.Count, "The updated Zip file has the wrong number of entries."); } [TestMethod] public void UpdateZip_RenameEntry() { string dirToZip = Path.GetFileNameWithoutExtension(Path.GetRandomFileName()); var files = TestUtilities.GenerateFilesFlat(dirToZip, _rnd.Next(13) + 24, 42 * 1024 + _rnd.Next(20000)); // Two passes: in pass 1, simply rename the file; // in pass 2, rename it so that it has a directory. // This shouldn't matter, but we test it anyway. for (int k = 0; k < 2; k++) { string zipFileToCreate = String.Format("UpdateZip_RenameEntry-{0}.zip", k); TestContext.WriteLine("-----------------------------"); TestContext.WriteLine("{0}: Trial {1}, adding {2} files into '{3}'...", DateTime.Now.ToString("HH:mm:ss"), k, files.Length, zipFileToCreate); // Add the files to the zip, save the zip Directory.SetCurrentDirectory(TopLevelDir); using (ZipFile zip1 = new ZipFile()) { foreach (String f in files) zip1.AddFile(f, ""); zip1.Comment = "This archive will be updated."; zip1.Save(zipFileToCreate); } // Verify the number of files in the zip Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), files.Length, "the Zip file has the wrong number of entries."); // selectively rename a few files in the zip archive int renameCount = 0; using (ZipFile zip2 = ZipFile.Read(zipFileToCreate)) { var toRename = new List<ZipEntry>(); while (toRename.Count < 2) { foreach (ZipEntry e in zip2) { if (_rnd.Next(2) == 1) toRename.Add(e); } } foreach (ZipEntry e in toRename) { var newname = (k == 0) ? e.FileName + "-renamed" : "renamed_files\\" + e.FileName; TestContext.WriteLine(" renaming {0} to {1}", e.FileName, newname); e.FileName = newname; e.Comment = "renamed"; renameCount++; } zip2.Comment = String.Format("This archive has been modified. {0} files have been renamed.", renameCount); zip2.Save(); } // Extract all the files, verify that none have been removed, // and verify the names of the entries. int renameCount2 = 0; using (ZipFile zip3 = ZipFile.Read(zipFileToCreate)) { foreach (string s1 in zip3.EntryFileNames) { string dir = String.Format("extract{0}", k); zip3[s1].Extract(dir); string origFilename = Path.GetFileName((s1.Contains("renamed")) ? s1.Replace("-renamed", "") : s1); if (zip3[s1].Comment == "renamed") renameCount2++; } } Assert.AreEqual<int>(renameCount, renameCount2, "The updated Zip file has the wrong number of renamed entries."); Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), files.Length, "Wrong number of entries."); } } [TestMethod] public void UpdateZip_UpdateEntryComment() { for (int k = 0; k < 2; k++) { int j; int entriesToBeAdded = 0; string filename = null; string repeatedLine = null; // select the name of the zip file string zipFileToCreate = Path.Combine(TopLevelDir, String.Format("UpdateZip_UpdateEntryComment-{0}.zip", k)); // create the subdirectory string subdir = Path.Combine(TopLevelDir, String.Format("A{0}", k)); Directory.CreateDirectory(subdir); // create a bunch of files //int numFilesToCreate = _rnd.Next(15) + 18; int numFilesToCreate = _rnd.Next(5) + 3; TestContext.WriteLine("\n-----------------------------\r\n{0}: Trial {1}, adding {2} files into '{3}'...", DateTime.Now.ToString("HH:mm:ss"), k, numFilesToCreate, zipFileToCreate); for (j = 0; j < numFilesToCreate; j++) { filename = String.Format("file{0:D3}.txt", j); repeatedLine = String.Format("This line is repeated over and over and over in file {0}", filename); int filesize = _rnd.Next(34000) + 800; TestUtilities.CreateAndFillFileText(Path.Combine(subdir, filename), repeatedLine, filesize); entriesToBeAdded++; } // Add the files to the zip, save the zip Directory.SetCurrentDirectory(TopLevelDir); using (ZipFile zip1 = new ZipFile()) { String[] filenames = Directory.GetFiles(String.Format("A{0}", k)); foreach (String f in filenames) zip1.AddFile(f, ""); zip1.Comment = "UpdateTests::UpdateZip_UpdateEntryComment(): This archive will be updated."; zip1.Save(zipFileToCreate); } // Verify the files are in the zip Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), entriesToBeAdded, "the Zip file has the wrong number of entries."); // update the comments for a few files in the zip archive int updateCount = 0; using (ZipFile zip2 = ZipFile.Read(zipFileToCreate)) { do { foreach (ZipEntry e in zip2) { if (_rnd.Next(2) == 1) { if (String.IsNullOrEmpty(e.Comment)) { e.Comment = "This is a new comment on entry " + e.FileName; updateCount++; } } } } while (updateCount < 2); zip2.Comment = String.Format("This archive has been modified. Comments on {0} entries have been inserted.", updateCount); zip2.Save(); } // Extract all files, verify that none have been removed, // and verify the contents of those that remain. int commentCount = 0; using (ZipFile zip3 = ZipFile.Read(zipFileToCreate)) { foreach (string s1 in zip3.EntryFileNames) { string dir = String.Format("extract{0}", k); zip3[s1].Extract(dir); repeatedLine = String.Format("This line is repeated over and over and over in file {0}", s1); // verify the content of the updated file. var sr = new StreamReader(Path.Combine(dir, s1)); string sLine = sr.ReadLine(); sr.Close(); Assert.AreEqual<string>(repeatedLine, sLine, String.Format("The content of the originally added file ({0}) in the zip archive is incorrect.", s1)); if (!String.IsNullOrEmpty(zip3[s1].Comment)) { commentCount++; } } } Assert.AreEqual<int>(updateCount, commentCount, "The updated Zip file has the wrong number of entries with comments."); // Verify the files are in the zip Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), entriesToBeAdded, "The updated Zip file has the wrong number of entries."); } } [TestMethod] public void UpdateZip_RemoveEntry_ByFilename() { for (int k = 0; k < 2; k++) { int j; int entriesToBeAdded = 0; string filename = null; string repeatedLine = null; // select the name of the zip file string zipFileToCreate = Path.Combine(TopLevelDir, String.Format("UpdateZip_RemoveEntry_ByFilename-{0}.zip", k)); // create the subdirectory string subdir = Path.Combine(TopLevelDir, String.Format("A{0}", k)); Directory.CreateDirectory(subdir); // create a bunch of files int numFilesToCreate = _rnd.Next(13) + 24; for (j = 0; j < numFilesToCreate; j++) { filename = String.Format("file{0:D3}.txt", j); repeatedLine = String.Format("This line is repeated over and over and over in file {0}", filename); TestUtilities.CreateAndFillFileText(Path.Combine(subdir, filename), repeatedLine, _rnd.Next(34000) + 5000); entriesToBeAdded++; } // Add the files to the zip, save the zip. // in pass 2, remove one file, then save again. Directory.SetCurrentDirectory(TopLevelDir); using (ZipFile zip1 = new ZipFile()) { String[] filenames = Directory.GetFiles(String.Format("A{0}", k)); foreach (String f in filenames) zip1.AddFile(f, ""); zip1.Comment = "UpdateTests::UpdateZip_RemoveEntry_ByFilename(): This archive will be updated."; zip1.Save(zipFileToCreate); // conditionally remove a single entry, on the 2nd trial if (k == 1) { int chosen = _rnd.Next(filenames.Length); zip1.RemoveEntry(zip1[chosen]); zip1.Save(); } } // Verify the files are in the zip Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), entriesToBeAdded - k, "Trial {0}: the Zip file has the wrong number of entries.", k); if (k == 0) { // selectively remove a few files in the zip archive var filesToRemove = new List<string>(); int numToRemove = _rnd.Next(numFilesToCreate - 4) + 1; using (ZipFile zip2 = ZipFile.Read(zipFileToCreate)) { for (j = 0; j < numToRemove; j++) { // select a new, uniquely named file to create do { filename = String.Format("file{0:D3}.txt", _rnd.Next(numFilesToCreate)); } while (filesToRemove.Contains(filename)); // add this file to the list filesToRemove.Add(filename); zip2.RemoveEntry(filename); } zip2.Comment = "This archive has been modified. Some files have been removed."; zip2.Save(); } // extract all files, verify none should have been removed, // and verify the contents of those that remain using (ZipFile zip3 = ZipFile.Read(zipFileToCreate)) { foreach (string s1 in zip3.EntryFileNames) { Assert.IsFalse(filesToRemove.Contains(s1), String.Format("File ({0}) was not expected.", s1)); zip3[s1].Extract("extract"); repeatedLine = String.Format("This line is repeated over and over and over in file {0}", s1); // verify the content of the updated file. var sr = new StreamReader(Path.Combine("extract", s1)); string sLine = sr.ReadLine(); sr.Close(); Assert.AreEqual<string>(repeatedLine, sLine, String.Format("The content of the originally added file ({0}) in the zip archive is incorrect.", s1)); } } // Verify the files are in the zip Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), entriesToBeAdded - filesToRemove.Count, "The updated Zip file has the wrong number of entries."); } } } [TestMethod] public void UpdateZip_RemoveEntry_ViaIndexer_WithPassword() { string password = TestUtilities.GenerateRandomPassword(); string filename = null; int entriesToBeAdded = 0; string repeatedLine = null; int j; // select the name of the zip file string zipFileToCreate = Path.Combine(TopLevelDir, "UpdateZip_RemoveEntry_ViaIndexer_WithPassword.zip"); // create the subdirectory string subdir = Path.Combine(TopLevelDir, "A"); Directory.CreateDirectory(subdir); // create the files int numFilesToCreate = _rnd.Next(13) + 14; for (j = 0; j < numFilesToCreate; j++) { filename = String.Format("file{0:D3}.txt", j); repeatedLine = String.Format("This line is repeated over and over and over in file {0}", filename); TestUtilities.CreateAndFillFileText(Path.Combine(subdir, filename), repeatedLine, _rnd.Next(34000) + 5000); entriesToBeAdded++; } // Add the files to the zip, save the zip Directory.SetCurrentDirectory(TopLevelDir); using (ZipFile zip = new ZipFile()) { String[] filenames = Directory.GetFiles("A"); zip.Password = password; foreach (String f in filenames) zip.AddFile(f, ""); zip.Comment = "UpdateTests::UpdateZip_OpenForUpdate_Password_RemoveViaIndexer(): This archive will be updated."; zip.Save(zipFileToCreate); } // Verify the files are in the zip Assert.AreEqual<int>(entriesToBeAdded, TestUtilities.CountEntries(zipFileToCreate), "The Zip file has the wrong number of entries."); // selectively remove a few files in the zip archive var filesToRemove = new List<string>(); int numToRemove = _rnd.Next(numFilesToCreate - 4); using (ZipFile zip2 = ZipFile.Read(zipFileToCreate)) { for (j = 0; j < numToRemove; j++) { // select a new, uniquely named file to create do { filename = String.Format("file{0:D3}.txt", _rnd.Next(numFilesToCreate)); } while (filesToRemove.Contains(filename)); // add this file to the list filesToRemove.Add(filename); // remove the file from the zip archive zip2.RemoveEntry(filename); } zip2.Comment = "This archive has been modified. Some files have been removed."; zip2.Save(); } // extract all files, verify none should have been removed, // and verify the contents of those that remain using (ZipFile zip3 = ZipFile.Read(zipFileToCreate)) { foreach (string s1 in zip3.EntryFileNames) { Assert.IsFalse(filesToRemove.Contains(s1), String.Format("File ({0}) was not expected.", s1)); zip3[s1].ExtractWithPassword("extract", password); repeatedLine = String.Format("This line is repeated over and over and over in file {0}", s1); // verify the content of the updated file. var sr = new StreamReader(Path.Combine("extract", s1)); string sLine = sr.ReadLine(); sr.Close(); Assert.AreEqual<string>(repeatedLine, sLine, String.Format("The content of the originally added file ({0}) in the zip archive is incorrect.", s1)); } } // Verify the files are in the zip Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), entriesToBeAdded - filesToRemove.Count, "The updated Zip file has the wrong number of entries."); } [TestMethod] public void UpdateZip_RemoveAllEntries() { string password = "<PASSWORD>!!" + TestUtilities.GenerateRandomLowerString(7); string filename = null; int entriesToBeAdded = 0; string repeatedLine = null; int j; // select the name of the zip file string zipFileToCreate = Path.Combine(TopLevelDir, "UpdateZip_RemoveAllEntries.zip"); // create the subdirectory string subdir = Path.Combine(TopLevelDir, "A"); Directory.CreateDirectory(subdir); // create the files int numFilesToCreate = _rnd.Next(13) + 14; for (j = 0; j < numFilesToCreate; j++) { filename = String.Format("file{0:D3}.txt", j); repeatedLine = String.Format("This line is repeated over and over and over in file {0}", filename); TestUtilities.CreateAndFillFileText(Path.Combine(subdir, filename), repeatedLine, _rnd.Next(34000) + 5000); entriesToBeAdded++; } // Add the files to the zip, save the zip Directory.SetCurrentDirectory(TopLevelDir); using (ZipFile zip = new ZipFile()) { String[] filenames = Directory.GetFiles("A"); zip.Password = password; foreach (String f in filenames) zip.AddFile(f, ""); zip.Comment = "UpdateTests::UpdateZip_RemoveAllEntries(): This archive will be updated."; zip.Save(zipFileToCreate); } // Verify the files are in the zip Assert.AreEqual<int>(entriesToBeAdded, TestUtilities.CountEntries(zipFileToCreate), "The Zip file has the wrong number of entries."); // remove all the entries from the zip archive using (ZipFile zip2 = ZipFile.Read(zipFileToCreate)) { zip2.RemoveSelectedEntries("*.*"); zip2.Comment = "This archive has been modified. All the entries have been removed."; zip2.Save(); } // Verify the files are in the zip Assert.AreEqual<int>(0, TestUtilities.CountEntries(zipFileToCreate), "The Zip file has the wrong number of entries."); } [TestMethod] public void UpdateZip_AddFile_OldEntriesWithPassword() { string password = "<PASSWORD>!"; string filename = null; int entriesAdded = 0; string repeatedLine = null; int j; // select the name of the zip file string zipFileToCreate = Path.Combine(TopLevelDir, "UpdateZip_AddFile_OldEntriesWithPassword.zip"); // create the subdirectory string subdir = Path.Combine(TopLevelDir, "A"); Directory.CreateDirectory(subdir); // create the files int numFilesToCreate = _rnd.Next(10) + 8; for (j = 0; j < numFilesToCreate; j++) { filename = Path.Combine(subdir, String.Format("file{0:D3}.txt", j)); repeatedLine = String.Format("This line is repeated over and over and over in file {0}", Path.GetFileName(filename)); TestUtilities.CreateAndFillFileText(filename, repeatedLine, _rnd.Next(34000) + 5000); entriesAdded++; } // Create the zip file Directory.SetCurrentDirectory(TopLevelDir); using (ZipFile zip1 = new ZipFile()) { zip1.Password = password; String[] filenames = Directory.GetFiles("A"); foreach (String f in filenames) zip1.AddFile(f, ""); zip1.Comment = "UpdateTests::UpdateZip_AddFile_OldEntriesWithPassword(): This archive will be updated."; zip1.Save(zipFileToCreate); } // Verify the files are in the zip Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), entriesAdded, "The Zip file has the wrong number of entries."); // Create a bunch of new files... var addedFiles = new List<string>(); int numToUpdate = _rnd.Next(numFilesToCreate - 4); for (j = 0; j < numToUpdate; j++) { // select a new, uniquely named file to create filename = String.Format("newfile{0:D3}.txt", j); // create a new file, and fill that new file with text data repeatedLine = String.Format("**UPDATED** This file ({0}) has been updated on {1}.", filename, System.DateTime.Now.ToString("yyyy-MM-dd")); TestUtilities.CreateAndFillFileText(Path.Combine(subdir, filename), repeatedLine, _rnd.Next(34000) + 5000); addedFiles.Add(filename); } // add each one of those new files in the zip archive using (ZipFile zip2 = ZipFile.Read(zipFileToCreate)) { foreach (string s in addedFiles) zip2.AddFile(Path.Combine(subdir, s), ""); zip2.Comment = "UpdateTests::UpdateZip_AddFile_OldEntriesWithPassword(): This archive has been updated."; zip2.Save(); } // Verify the number of files in the zip Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), entriesAdded + addedFiles.Count, "The Zip file has the wrong number of entries."); // now extract the newly-added files and verify their contents using (ZipFile zip3 = ZipFile.Read(zipFileToCreate)) { foreach (string s in addedFiles) { repeatedLine = String.Format("**UPDATED** This file ({0}) has been updated on {1}.", s, System.DateTime.Now.ToString("yyyy-MM-dd")); zip3[s].Extract("extract"); // verify the content of the updated file. var sr = new StreamReader(Path.Combine("extract", s)); string sLine = sr.ReadLine(); sr.Close(); Assert.AreEqual<string>(repeatedLine, sLine, String.Format("The content of the Updated file ({0}) in the zip archive is incorrect.", s)); } } // extract all the other files and verify their contents using (ZipFile zip4 = ZipFile.Read(zipFileToCreate)) { foreach (string s1 in zip4.EntryFileNames) { bool addedLater = false; foreach (string s2 in addedFiles) { if (s2 == s1) addedLater = true; } if (!addedLater) { zip4[s1].ExtractWithPassword("extract", password); repeatedLine = String.Format("This line is repeated over and over and over in file {0}", s1); // verify the content of the updated file. var sr = new StreamReader(Path.Combine("extract", s1)); string sLine = sr.ReadLine(); sr.Close(); Assert.AreEqual<string>(repeatedLine, sLine, String.Format("The content of the originally added file ({0}) in the zip archive is incorrect.", s1)); } } } } [TestMethod] public void UpdateZip_UpdateItem() { string filename = null; int entriesAdded = 0; string repeatedLine = null; int j; // select the name of the zip file string zipFileToCreate = Path.Combine(TopLevelDir, "UpdateZip_UpdateItem.zip"); // create the subdirectory string subdir = Path.Combine(TopLevelDir, "A"); Directory.CreateDirectory(subdir); // create a bunch of files int numFilesToCreate = _rnd.Next(10) + 8; for (j = 0; j < numFilesToCreate; j++) { filename = Path.Combine(subdir, String.Format("file{0:D3}.txt", j)); repeatedLine = String.Format("Content for Original file {0}", Path.GetFileName(filename)); TestUtilities.CreateAndFillFileText(filename, repeatedLine, _rnd.Next(34000) + 5000); entriesAdded++; } // Create the zip file Directory.SetCurrentDirectory(TopLevelDir); using (ZipFile zip1 = new ZipFile()) { String[] filenames = Directory.GetFiles("A"); foreach (String f in filenames) zip1.AddFile(f, ""); zip1.Comment = "UpdateTests::UpdateZip_UpdateItem(): This archive will be updated."; zip1.Save(zipFileToCreate); } // Verify the files are in the zip Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), entriesAdded, "The Zip file has the wrong number of entries."); // create another subdirectory subdir = Path.Combine(TopLevelDir, "B"); Directory.CreateDirectory(subdir); // create a bunch more files int newFileCount = numFilesToCreate + _rnd.Next(3) + 3; for (j = 0; j < newFileCount; j++) { filename = Path.Combine(subdir, String.Format("file{0:D3}.txt", j)); repeatedLine = String.Format("Content for the updated file {0} {1}", Path.GetFileName(filename), System.DateTime.Now.ToString("yyyy-MM-dd")); TestUtilities.CreateAndFillFileText(filename, repeatedLine, _rnd.Next(1000) + 2000); entriesAdded++; } // Update those files in the zip file Directory.SetCurrentDirectory(TopLevelDir); using (ZipFile zip1 = new ZipFile()) { String[] filenames = Directory.GetFiles("B"); foreach (String f in filenames) zip1.UpdateItem(f, ""); zip1.Comment = "UpdateTests::UpdateZip_UpdateItem(): This archive has been updated."; zip1.Save(zipFileToCreate); } // Verify the number of files in the zip Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), newFileCount, "The Zip file has the wrong number of entries."); // now extract the files and verify their contents using (ZipFile zip3 = ZipFile.Read(zipFileToCreate)) { foreach (string s in zip3.EntryFileNames) { repeatedLine = String.Format("Content for the updated file {0} {1}", s, System.DateTime.Now.ToString("yyyy-MM-dd")); zip3[s].Extract("extract"); // verify the content of the updated file. var sr = new StreamReader(Path.Combine("extract", s)); string sLine = sr.ReadLine(); sr.Close(); Assert.AreEqual<string>(repeatedLine, sLine, String.Format("The content of the Updated file ({0}) in the zip archive is incorrect.", s)); } } } [TestMethod] public void UpdateZip_AddFile_NewEntriesWithPassword() { string password = "<PASSWORD>!"; string filename = null; int entriesAdded = 0; string repeatedLine = null; int j; // select the name of the zip file string zipFileToCreate = Path.Combine(TopLevelDir, "UpdateZip_AddFile_NewEntriesWithPassword.zip"); // create the subdirectory string subdir = Path.Combine(TopLevelDir, "A"); Directory.CreateDirectory(subdir); // create a bunch of files int numFilesToCreate = _rnd.Next(10) + 8; for (j = 0; j < numFilesToCreate; j++) { filename = Path.Combine(subdir, String.Format("file{0:D3}.txt", j)); repeatedLine = String.Format("This line is repeated over and over and over in file {0}", Path.GetFileName(filename)); TestUtilities.CreateAndFillFileText(filename, repeatedLine, _rnd.Next(34000) + 5000); entriesAdded++; } // Create the zip archive Directory.SetCurrentDirectory(TopLevelDir); using (ZipFile zip = new ZipFile()) { String[] filenames = Directory.GetFiles("A"); zip.AddFiles(filenames, ""); zip.Comment = "UpdateTests::UpdateZip_AddFile_NewEntriesWithPassword(): This archive will be updated."; zip.Save(zipFileToCreate); } // Verify the number of files in the zip Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), entriesAdded, "The Zip file has the wrong number of entries."); // Create a bunch of new files... var addedFiles = new List<string>(); int numToUpdate = _rnd.Next(numFilesToCreate - 4); for (j = 0; j < numToUpdate; j++) { // select a new, uniquely named file to create filename = String.Format("newfile{0:D3}.txt", j); // create a new file, and fill that new file with text data repeatedLine = String.Format("**UPDATED** This file ({0}) has been updated on {1}.", filename, System.DateTime.Now.ToString("yyyy-MM-dd")); TestUtilities.CreateAndFillFileText(Path.Combine(subdir, filename), repeatedLine, _rnd.Next(34000) + 5000); addedFiles.Add(filename); } // add each one of those new files in the zip archive using a password using (ZipFile zip2 = ZipFile.Read(zipFileToCreate)) { zip2.Password = password; foreach (string s in addedFiles) zip2.AddFile(Path.Combine(subdir, s), ""); zip2.Comment = "UpdateTests::UpdateZip_AddFile_OldEntriesWithPassword(): This archive has been updated."; zip2.Save(); } // Verify the number of files in the zip Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), entriesAdded + addedFiles.Count, "The Zip file has the wrong number of entries."); // now extract the newly-added files and verify their contents using (ZipFile zip3 = ZipFile.Read(zipFileToCreate)) { foreach (string s in addedFiles) { repeatedLine = String.Format("**UPDATED** This file ({0}) has been updated on {1}.", s, System.DateTime.Now.ToString("yyyy-MM-dd")); zip3[s].ExtractWithPassword("extract", password); // verify the content of the updated file. var sr = new StreamReader(Path.Combine("extract", s)); string sLine = sr.ReadLine(); sr.Close(); Assert.AreEqual<string>(repeatedLine, sLine, String.Format("The content of the Updated file ({0}) in the zip archive is incorrect.", s)); } } // extract all the other files and verify their contents using (ZipFile zip4 = ZipFile.Read(zipFileToCreate)) { foreach (string s1 in zip4.EntryFileNames) { bool addedLater = false; foreach (string s2 in addedFiles) { if (s2 == s1) addedLater = true; } if (!addedLater) { zip4[s1].Extract("extract"); repeatedLine = String.Format("This line is repeated over and over and over in file {0}", s1); // verify the content of the updated file. var sr = new StreamReader(Path.Combine("extract", s1)); string sLine = sr.ReadLine(); sr.Close(); Assert.AreEqual<string>(repeatedLine, sLine, String.Format("The content of the originally added file ({0}) in the zip archive is incorrect.", s1)); } } } } [TestMethod] public void UpdateZip_AddFile_DifferentPasswords() { string password1 = Path.GetRandomFileName(); string password2 = "<PASSWORD>" + Path.GetRandomFileName(); string filename = null; int entriesAdded = 0; string repeatedLine = null; int j; // select the name of the zip file string zipFileToCreate = Path.Combine(TopLevelDir, "UpdateZip_AddFile_DifferentPasswords.zip"); // create the subdirectory string subdir = Path.Combine(TopLevelDir, "A"); Directory.CreateDirectory(subdir); // create a bunch of files int numFilesToCreate = _rnd.Next(11) + 8; for (j = 0; j < numFilesToCreate; j++) { filename = Path.Combine(subdir, String.Format("file{0:D3}.txt", j)); repeatedLine = String.Format("This line is repeated over and over and over in file {0}", Path.GetFileName(filename)); TestUtilities.CreateAndFillFileText(filename, repeatedLine, _rnd.Next(34000) + 5000); entriesAdded++; } // Add the files to the zip, save the zip Directory.SetCurrentDirectory(TopLevelDir); using (ZipFile zip1 = new ZipFile()) { zip1.Password = <PASSWORD>; String[] filenames = Directory.GetFiles("A"); foreach (String f in filenames) zip1.AddFile(f, ""); zip1.Comment = "UpdateTests::UpdateZip_AddFile_DifferentPasswords(): This archive will be updated."; zip1.Save(zipFileToCreate); } // Verify the number of files in the zip Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), entriesAdded, "The Zip file has the wrong number of entries."); // Create a bunch of new files... var addedFiles = new List<string>(); //int numToUpdate = _rnd.Next(numFilesToCreate - 4); int numToUpdate = 1; for (j = 0; j < numToUpdate; j++) { // select a new, uniquely named file to create filename = String.Format("newfile{0:D3}.txt", j); // create a new file, and fill that new file with text data repeatedLine = String.Format("**UPDATED** This file ({0}) has been updated on {1}.", filename, System.DateTime.Now.ToString("yyyy-MM-dd")); TestUtilities.CreateAndFillFileText(Path.Combine(subdir, filename), repeatedLine, _rnd.Next(34000) + 5000); addedFiles.Add(filename); } // add each one of those new files in the zip archive using a password using (ZipFile zip2 = ZipFile.Read(zipFileToCreate)) { zip2.Password = <PASSWORD>; foreach (string s in addedFiles) zip2.AddFile(Path.Combine(subdir, s), ""); zip2.Comment = "UpdateTests::UpdateZip_AddFile_OldEntriesWithPassword(): This archive has been updated."; zip2.Save(); } // Verify the number of files in the zip Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), entriesAdded + addedFiles.Count, "The Zip file has the wrong number of entries."); // now extract the newly-added files and verify their contents using (ZipFile zip3 = ZipFile.Read(zipFileToCreate)) { foreach (string s in addedFiles) { repeatedLine = String.Format("**UPDATED** This file ({0}) has been updated on {1}.", s, System.DateTime.Now.ToString("yyyy-MM-dd")); zip3[s].ExtractWithPassword("extract", password2); // verify the content of the updated file. var sr = new StreamReader(Path.Combine("extract", s)); string sLine = sr.ReadLine(); sr.Close(); Assert.AreEqual<string>(repeatedLine, sLine, String.Format("The content of the Updated file ({0}) in the zip archive is incorrect.", s)); } } // extract all the other files and verify their contents using (ZipFile zip4 = ZipFile.Read(zipFileToCreate)) { foreach (string s1 in zip4.EntryFileNames) { bool addedLater = false; foreach (string s2 in addedFiles) { if (s2 == s1) addedLater = true; } if (!addedLater) { zip4[s1].ExtractWithPassword("extract", password1); repeatedLine = String.Format("This line is repeated over and over and over in file {0}", s1); // verify the content of the updated file. var sr = new StreamReader(Path.Combine("extract", s1)); string sLine = sr.ReadLine(); sr.Close(); Assert.AreEqual<string>(repeatedLine, sLine, String.Format("The content of the originally added file ({0}) in the zip archive is incorrect.", s1)); } } } } [TestMethod] public void UpdateZip_UpdateFile_NoPasswords() { string filename = null; int entriesAdded = 0; int j = 0; string repeatedLine = null; // select the name of the zip file string zipFileToCreate = Path.Combine(TopLevelDir, "UpdateZip_UpdateFile_NoPasswords.zip"); // create the subdirectory string subdir = Path.Combine(TopLevelDir, "A"); Directory.CreateDirectory(subdir); // create the files int NumFilesToCreate = _rnd.Next(23) + 14; for (j = 0; j < NumFilesToCreate; j++) { filename = Path.Combine(subdir, String.Format("file{0:D3}.txt", j)); repeatedLine = String.Format("This line is repeated over and over and over in file {0}", Path.GetFileName(filename)); TestUtilities.CreateAndFillFileText(filename, repeatedLine, _rnd.Next(34000) + 5000); entriesAdded++; } // create the zip archive Directory.SetCurrentDirectory(TopLevelDir); using (ZipFile zip1 = new ZipFile()) { String[] filenames = Directory.GetFiles("A"); foreach (String f in filenames) zip1.AddFile(f, ""); zip1.Comment = "UpdateTests::UpdateZip_UpdateFile_NoPasswords(): This archive will be updated."; zip1.Save(zipFileToCreate); } // Verify the number of files in the zip Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), entriesAdded, "Zoiks! The Zip file has the wrong number of entries."); // create another subdirectory subdir = Path.Combine(TopLevelDir, "updates"); Directory.CreateDirectory(subdir); // Create a bunch of new files, in that new subdirectory var UpdatedFiles = new List<string>(); int NumToUpdate = _rnd.Next(NumFilesToCreate - 4); for (j = 0; j < NumToUpdate; j++) { // select a new, uniquely named file to create do { filename = String.Format("file{0:D3}.txt", _rnd.Next(NumFilesToCreate)); } while (UpdatedFiles.Contains(filename)); // create a new file, and fill that new file with text data repeatedLine = String.Format("**UPDATED** This file ({0}) has been updated on {1}.", filename, System.DateTime.Now.ToString("yyyy-MM-dd")); TestUtilities.CreateAndFillFileText(Path.Combine(subdir, filename), repeatedLine, _rnd.Next(34000) + 5000); UpdatedFiles.Add(filename); } // update those files in the zip archive using (ZipFile zip2 = ZipFile.Read(zipFileToCreate)) { foreach (string s in UpdatedFiles) zip2.UpdateFile(Path.Combine(subdir, s), ""); zip2.Comment = "UpdateTests::UpdateZip_UpdateFile_OldEntriesWithPassword(): This archive has been updated."; zip2.Save(); } // extract those files and verify their contents using (ZipFile zip3 = ZipFile.Read(zipFileToCreate)) { foreach (string s in UpdatedFiles) { repeatedLine = String.Format("**UPDATED** This file ({0}) has been updated on {1}.", s, System.DateTime.Now.ToString("yyyy-MM-dd")); zip3[s].Extract("extract"); // verify the content of the updated file. var sr = new StreamReader(Path.Combine("extract", s)); string sLine = sr.ReadLine(); sr.Close(); Assert.AreEqual<string>(repeatedLine, sLine, String.Format("The content of the Updated file ({0}) in the zip archive is incorrect.", s)); } } // extract all the other files and verify their contents using (ZipFile zip4 = ZipFile.Read(zipFileToCreate)) { foreach (string s1 in zip4.EntryFileNames) { bool NotUpdated = true; foreach (string s2 in UpdatedFiles) { if (s2 == s1) NotUpdated = false; } if (NotUpdated) { zip4[s1].Extract("extract"); repeatedLine = String.Format("This line is repeated over and over and over in file {0}", s1); // verify the content of the updated file. var sr = new StreamReader(Path.Combine("extract", s1)); string sLine = sr.ReadLine(); sr.Close(); Assert.AreEqual<string>(repeatedLine, sLine, String.Format("The content of the originally added file ({0}) in the zip archive is incorrect.", s1)); } } } } [TestMethod] public void UpdateZip_UpdateFile_2_NoPasswords() { string filename = null; int entriesAdded = 0; int j = 0; string repeatedLine = null; // select the name of the zip file string zipFileToCreate = Path.Combine(TopLevelDir, "UpdateZip_UpdateFile_NoPasswords.zip"); // create the subdirectory string subdir = Path.Combine(TopLevelDir, "A"); Directory.CreateDirectory(subdir); // create the files int NumFilesToCreate = _rnd.Next(23) + 14; for (j = 0; j < NumFilesToCreate; j++) { filename = Path.Combine(subdir, String.Format("file{0:D3}.txt", j)); repeatedLine = String.Format("This line is repeated over and over and over in file {0}", Path.GetFileName(filename)); TestUtilities.CreateAndFillFileText(filename, repeatedLine, _rnd.Next(34000) + 5000); entriesAdded++; } // create the zip archive Directory.SetCurrentDirectory(TopLevelDir); using (ZipFile zip1 = new ZipFile()) { String[] filenames = Directory.GetFiles("A"); foreach (String f in filenames) zip1.UpdateFile(f, ""); zip1.Comment = "UpdateTests::UpdateZip_UpdateFile_NoPasswords(): This archive will be updated."; zip1.Save(zipFileToCreate); } // Verify the number of files in the zip Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), entriesAdded, "Zoiks! The Zip file has the wrong number of entries."); // create another subdirectory subdir = Path.Combine(TopLevelDir, "updates"); Directory.CreateDirectory(subdir); // Create a bunch of new files, in that new subdirectory var UpdatedFiles = new List<string>(); int NumToUpdate = _rnd.Next(NumFilesToCreate - 4); for (j = 0; j < NumToUpdate; j++) { // select a new, uniquely named file to create do { filename = String.Format("file{0:D3}.txt", _rnd.Next(NumFilesToCreate)); } while (UpdatedFiles.Contains(filename)); // create a new file, and fill that new file with text data repeatedLine = String.Format("**UPDATED** This file ({0}) has been updated on {1}.", filename, System.DateTime.Now.ToString("yyyy-MM-dd")); TestUtilities.CreateAndFillFileText(Path.Combine(subdir, filename), repeatedLine, _rnd.Next(34000) + 5000); UpdatedFiles.Add(filename); } // update those files in the zip archive using (ZipFile zip2 = ZipFile.Read(zipFileToCreate)) { foreach (string s in UpdatedFiles) zip2.UpdateFile(Path.Combine(subdir, s), ""); zip2.Comment = "UpdateTests::UpdateZip_UpdateFile_NoPasswords(): This archive has been updated."; zip2.Save(); } // Verify the number of files in the zip Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), entriesAdded, "Zoiks! The Zip file has the wrong number of entries."); // update those files AGAIN in the zip archive using (ZipFile zip3 = ZipFile.Read(zipFileToCreate)) { foreach (string s in UpdatedFiles) zip3.UpdateFile(Path.Combine(subdir, s), ""); zip3.Comment = "UpdateTests::UpdateZip_UpdateFile_NoPasswords(): This archive has been re-updated."; zip3.Save(); } // extract the updated files and verify their contents using (ZipFile zip4 = ZipFile.Read(zipFileToCreate)) { foreach (string s in UpdatedFiles) { repeatedLine = String.Format("**UPDATED** This file ({0}) has been updated on {1}.", s, System.DateTime.Now.ToString("yyyy-MM-dd")); zip4[s].Extract("extract"); // verify the content of the updated file. var sr = new StreamReader(Path.Combine("extract", s)); string sLine = sr.ReadLine(); sr.Close(); Assert.AreEqual<string>(repeatedLine, sLine, String.Format("The content of the Updated file ({0}) in the zip archive is incorrect.", s)); } } // extract all the other files and verify their contents using (ZipFile zip5 = ZipFile.Read(zipFileToCreate)) { foreach (string s1 in zip5.EntryFileNames) { bool NotUpdated = true; foreach (string s2 in UpdatedFiles) { if (s2 == s1) NotUpdated = false; } if (NotUpdated) { zip5[s1].Extract("extract"); repeatedLine = String.Format("This line is repeated over and over and over in file {0}", s1); // verify the content of the updated file. var sr = new StreamReader(Path.Combine("extract", s1)); string sLine = sr.ReadLine(); sr.Close(); Assert.AreEqual<string>(repeatedLine, sLine, String.Format("The content of the originally added file ({0}) in the zip archive is incorrect.", s1)); } } } } [TestMethod] public void UpdateZip_UpdateFile_OldEntriesWithPassword() { string Password = "<PASSWORD>"; string filename = null; int entriesAdded = 0; int j = 0; string repeatedLine = null; // select the name of the zip file string zipFileToCreate = Path.Combine(TopLevelDir, "UpdateZip_UpdateFile_OldEntriesWithPassword.zip"); // create the subdirectory string subdir = Path.Combine(TopLevelDir, "A"); Directory.CreateDirectory(subdir); // create a bunch of files int NumFilesToCreate = _rnd.Next(23) + 14; for (j = 0; j < NumFilesToCreate; j++) { filename = Path.Combine(subdir, String.Format("file{0:D3}.txt", j)); repeatedLine = String.Format("This line is repeated over and over and over in file {0}", Path.GetFileName(filename)); TestUtilities.CreateAndFillFileText(filename, repeatedLine, _rnd.Next(34000) + 5000); entriesAdded++; } // Create the zip archive Directory.SetCurrentDirectory(TopLevelDir); using (ZipFile zip1 = new ZipFile()) { zip1.Password = Password; String[] filenames = Directory.GetFiles("A"); foreach (String f in filenames) zip1.AddFile(f, ""); zip1.Comment = "UpdateTests::UpdateZip_UpdateFile_OldEntriesWithPassword(): This archive will be updated."; zip1.Save(zipFileToCreate); } // Verify the number of files in the zip Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), entriesAdded, "The Zip file has the wrong number of entries."); // create another subdirectory subdir = Path.Combine(TopLevelDir, "updates"); Directory.CreateDirectory(subdir); // Create a bunch of new files, in that new subdirectory var UpdatedFiles = new List<string>(); int NumToUpdate = _rnd.Next(NumFilesToCreate - 4); for (j = 0; j < NumToUpdate; j++) { // select a new, uniquely named file to create do { filename = String.Format("file{0:D3}.txt", _rnd.Next(NumFilesToCreate)); } while (UpdatedFiles.Contains(filename)); // create a new file, and fill that new file with text data repeatedLine = String.Format("**UPDATED** This file ({0}) has been updated on {1}.", filename, System.DateTime.Now.ToString("yyyy-MM-dd")); TestUtilities.CreateAndFillFileText(Path.Combine(subdir, filename), repeatedLine, _rnd.Next(34000) + 5000); UpdatedFiles.Add(filename); } // update those files in the zip archive using (ZipFile zip2 = ZipFile.Read(zipFileToCreate)) { foreach (string s in UpdatedFiles) zip2.UpdateFile(Path.Combine(subdir, s), ""); zip2.Comment = "UpdateTests::UpdateZip_UpdateFile_OldEntriesWithPassword(): This archive has been updated."; zip2.Save(); } // extract those files and verify their contents using (ZipFile zip3 = ZipFile.Read(zipFileToCreate)) { foreach (string s in UpdatedFiles) { repeatedLine = String.Format("**UPDATED** This file ({0}) has been updated on {1}.", s, System.DateTime.Now.ToString("yyyy-MM-dd")); zip3[s].Extract("extract"); // verify the content of the updated file. var sr = new StreamReader(Path.Combine("extract", s)); string sLine = sr.ReadLine(); sr.Close(); Assert.AreEqual<string>(repeatedLine, sLine, String.Format("The content of the Updated file ({0}) in the zip archive is incorrect.", s)); } } // extract all the other files and verify their contents using (ZipFile zip4 = ZipFile.Read(zipFileToCreate)) { foreach (string s1 in zip4.EntryFileNames) { bool NotUpdated = true; foreach (string s2 in UpdatedFiles) { if (s2 == s1) NotUpdated = false; } if (NotUpdated) { zip4[s1].ExtractWithPassword("extract", Password); repeatedLine = String.Format("This line is repeated over and over and over in file {0}", s1); // verify the content of the updated file. var sr = new StreamReader(Path.Combine("extract", s1)); string sLine = sr.ReadLine(); sr.Close(); Assert.AreEqual<string>(repeatedLine, sLine, String.Format("The content of the originally added file ({0}) in the zip archive is incorrect.", s1)); } } } } [TestMethod] public void UpdateZip_UpdateFile_NewEntriesWithPassword() { string Password = " <PASSWORD>"; string filename = null; int entriesAdded = 0; string repeatedLine = null; int j = 0; // select the name of the zip file string zipFileToCreate = Path.Combine(TopLevelDir, "UpdateZip_UpdateFile_NewEntriesWithPassword.zip"); // create the subdirectory string subdir = Path.Combine(TopLevelDir, "A"); Directory.CreateDirectory(subdir); // create a bunch of files int NumFilesToCreate = _rnd.Next(23) + 9; for (j = 0; j < NumFilesToCreate; j++) { filename = Path.Combine(subdir, String.Format("file{0:D3}.txt", j)); repeatedLine = String.Format("This line is repeated over and over and over in file {0}", Path.GetFileName(filename)); TestUtilities.CreateAndFillFileText(filename, repeatedLine, _rnd.Next(34000) + 5000); entriesAdded++; } // create the zip archive, add those files to it Directory.SetCurrentDirectory(TopLevelDir); using (ZipFile zip1 = new ZipFile()) { // no password used here. String[] filenames = Directory.GetFiles("A"); foreach (String f in filenames) zip1.AddFile(f, ""); zip1.Comment = "UpdateTests::UpdateZip_UpdateFile_NewEntriesWithPassword(): This archive will be updated."; zip1.Save(zipFileToCreate); } // Verify the files are in the zip Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), entriesAdded, "The Zip file has the wrong number of entries."); // create another subdirectory subdir = Path.Combine(TopLevelDir, "updates"); Directory.CreateDirectory(subdir); // Create a bunch of new files, in that new subdirectory var UpdatedFiles = new List<string>(); int NumToUpdate = _rnd.Next(NumFilesToCreate - 5); for (j = 0; j < NumToUpdate; j++) { // select a new, uniquely named file to create do { filename = String.Format("file{0:D3}.txt", _rnd.Next(NumFilesToCreate)); } while (UpdatedFiles.Contains(filename)); // create the new file, and fill that new file with text data repeatedLine = String.Format("**UPDATED** This file ({0}) has been updated on {1}.", filename, System.DateTime.Now.ToString("yyyy-MM-dd")); TestUtilities.CreateAndFillFileText(Path.Combine(subdir, filename), repeatedLine, _rnd.Next(34000) + 5000); UpdatedFiles.Add(filename); } // update those files in the zip archive using (ZipFile zip2 = ZipFile.Read(zipFileToCreate)) { zip2.Password = Password; foreach (string s in UpdatedFiles) zip2.UpdateFile(Path.Combine(subdir, s), ""); zip2.Comment = "UpdateTests::UpdateZip_UpdateFile_NewEntriesWithPassword(): This archive has been updated."; zip2.Save(); } // extract those files and verify their contents using (ZipFile zip3 = ZipFile.Read(zipFileToCreate)) { foreach (string s in UpdatedFiles) { repeatedLine = String.Format("**UPDATED** This file ({0}) has been updated on {1}.", s, System.DateTime.Now.ToString("yyyy-MM-dd")); zip3[s].ExtractWithPassword("extract", Password); // verify the content of the updated file. var sr = new StreamReader(Path.Combine("extract", s)); string sLine = sr.ReadLine(); sr.Close(); Assert.AreEqual<string>(repeatedLine, sLine, String.Format("The content of the Updated file ({0}) in the zip archive is incorrect.", s)); } } // extract all the other files and verify their contents using (ZipFile zip4 = ZipFile.Read(zipFileToCreate)) { foreach (string s1 in zip4.EntryFileNames) { bool NotUpdated = true; foreach (string s2 in UpdatedFiles) { if (s2 == s1) NotUpdated = false; } if (NotUpdated) { zip4[s1].Extract("extract"); repeatedLine = String.Format("This line is repeated over and over and over in file {0}", s1); // verify the content of the updated file. var sr = new StreamReader(Path.Combine("extract", s1)); string sLine = sr.ReadLine(); sr.Close(); Assert.AreEqual<string>(repeatedLine, sLine, String.Format("The content of the originally added file ({0}) in the zip archive is incorrect.", s1)); } } } } [TestMethod] public void UpdateZip_UpdateFile_DifferentPasswords() { string Password1 = "<PASSWORD>"; string Password2 = "<PASSWORD>"; string filename = null; int entriesAdded = 0; int j = 0; string repeatedLine; // select the name of the zip file string zipFileToCreate = Path.Combine(TopLevelDir, "UpdateZip_UpdateFile_DifferentPasswords.zip"); // create the subdirectory string subdir = Path.Combine(TopLevelDir, "A"); Directory.CreateDirectory(subdir); // create a bunch of files int NumFilesToCreate = _rnd.Next(13) + 14; for (j = 0; j < NumFilesToCreate; j++) { filename = Path.Combine(subdir, String.Format("file{0:D3}.txt", j)); repeatedLine = String.Format("This line is repeated over and over and over in file {0}", Path.GetFileName(filename)); TestUtilities.CreateAndFillFileText(filename, repeatedLine, _rnd.Next(34000) + 5000); entriesAdded++; } // create the zip archive Directory.SetCurrentDirectory(TopLevelDir); using (ZipFile zip1 = new ZipFile()) { zip1.Password = <PASSWORD>; String[] filenames = Directory.GetFiles("A"); foreach (String f in filenames) zip1.AddFile(f, ""); zip1.Comment = "UpdateTests::UpdateZip_UpdateFile_DifferentPasswords(): This archive will be updated."; zip1.Save(zipFileToCreate); } // Verify the files are in the zip Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), entriesAdded, "The Zip file has the wrong number of entries."); // create another subdirectory subdir = Path.Combine(TopLevelDir, "updates"); Directory.CreateDirectory(subdir); // Create a bunch of new files, in that new subdirectory var UpdatedFiles = new List<string>(); int NumToUpdate = _rnd.Next(NumFilesToCreate - 4); for (j = 0; j < NumToUpdate; j++) { // select a new, uniquely named file to create do { filename = String.Format("file{0:D3}.txt", _rnd.Next(NumFilesToCreate)); } while (UpdatedFiles.Contains(filename)); // create a new file, and fill that new file with text data repeatedLine = String.Format("**UPDATED** This file ({0}) has been updated on {1}.", filename, System.DateTime.Now.ToString("yyyy-MM-dd")); TestUtilities.CreateAndFillFileText(Path.Combine(subdir, filename), repeatedLine, _rnd.Next(34000) + 5000); UpdatedFiles.Add(filename); } // update those files in the zip archive using (ZipFile zip2 = ZipFile.Read(zipFileToCreate)) { zip2.Password = <PASSWORD>; foreach (string s in UpdatedFiles) zip2.UpdateFile(Path.Combine(subdir, s), ""); zip2.Comment = "UpdateTests::UpdateZip_UpdateFile_DifferentPasswords(): This archive has been updated."; zip2.Save(); } // extract those files and verify their contents using (ZipFile zip3 = ZipFile.Read(zipFileToCreate)) { foreach (string s in UpdatedFiles) { repeatedLine = String.Format("**UPDATED** This file ({0}) has been updated on {1}.", s, System.DateTime.Now.ToString("yyyy-MM-dd")); zip3[s].ExtractWithPassword("extract", <PASSWORD>); // verify the content of the updated file. var sr = new StreamReader(Path.Combine("extract", s)); string sLine = sr.ReadLine(); sr.Close(); Assert.AreEqual<string>(sLine, repeatedLine, String.Format("The content of the Updated file ({0}) in the zip archive is incorrect.", s)); } } // extract all the other files and verify their contents using (ZipFile zip4 = ZipFile.Read(zipFileToCreate)) { foreach (string s1 in zip4.EntryFileNames) { bool wasUpdated = false; foreach (string s2 in UpdatedFiles) { if (s2 == s1) wasUpdated = true; } if (!wasUpdated) { // use original password zip4[s1].ExtractWithPassword("extract", Password1); repeatedLine = String.Format("This line is repeated over and over and over in file {0}", s1); // verify the content of the updated file. var sr = new StreamReader(Path.Combine("extract", s1)); string sLine = sr.ReadLine(); sr.Close(); Assert.AreEqual<string>(repeatedLine, sLine, String.Format("The content of the originally added file ({0}) in the zip archive is incorrect.", s1)); } } } } [TestMethod] [ExpectedException(typeof(System.ArgumentException))] public void UpdateZip_AddFile_ExistingFile_Error() { // select the name of the zip file string zipFileToCreate = Path.Combine(TopLevelDir, "UpdateZip_AddFile_ExistingFile_Error.zip"); // create the subdirectory string subdir = Path.Combine(TopLevelDir, "A"); Directory.CreateDirectory(subdir); // create the files int fileCount = _rnd.Next(3) + 4; string filename = null; int entriesAdded = 0; for (int j = 0; j < fileCount; j++) { filename = Path.Combine(subdir, String.Format("file{0:D3}.txt", j)); TestUtilities.CreateAndFillFileText(filename, _rnd.Next(34000) + 5000); entriesAdded++; } // Add the files to the zip, save the zip Directory.SetCurrentDirectory(TopLevelDir); using (ZipFile zip = new ZipFile()) { String[] filenames = Directory.GetFiles("A"); foreach (String f in filenames) zip.AddFile(f, ""); zip.Comment = "UpdateTests::UpdateZip_AddFile_ExistingFile_Error(): This archive will be updated."; zip.Save(zipFileToCreate); } // create and file a new file with text data int FileToUpdate = _rnd.Next(fileCount); filename = String.Format("file{0:D3}.txt", FileToUpdate); string repeatedLine = String.Format("**UPDATED** This file ({0}) was updated at {1}.", filename, System.DateTime.Now.ToString("G")); TestUtilities.CreateAndFillFileText(filename, repeatedLine, _rnd.Next(21567) + 23872); // Try to again add that file in the zip archive. This // should fail. using (ZipFile z = ZipFile.Read(zipFileToCreate)) { // Try Adding a file again. THIS SHOULD THROW. ZipEntry e = z.AddFile(filename, ""); z.Comment = "UpdateTests::UpdateZip_AddFile_ExistingFile_Error(): This archive has been updated."; z.Save(); } } [TestMethod] public void Update_MultipleSaves_wi10319() { string zipFileToCreate = "MultipleSaves_wi10319.zip"; using (ZipFile _zipFile = new ZipFile(zipFileToCreate)) { using (MemoryStream data = new MemoryStream()) { using (StreamWriter writer = new StreamWriter(data)) { writer.Write("Dit is een test string."); writer.Flush(); data.Seek(0, SeekOrigin.Begin); _zipFile.AddEntry("test.txt", data); _zipFile.Save(); _zipFile.AddEntry("test2.txt", "Esta es un string de test"); _zipFile.Save(); _zipFile.AddEntry("test3.txt", "this is some content for the entry."); _zipFile.Save(); } } } using (ZipFile _zipFile = new ZipFile(zipFileToCreate)) { using (MemoryStream data = new MemoryStream()) { using (StreamWriter writer = new StreamWriter(data)) { writer.Write("Dit is een andere test string."); writer.Flush(); data.Seek(0, SeekOrigin.Begin); _zipFile.UpdateEntry("test.txt", data); _zipFile.Save(); _zipFile.UpdateEntry("test2.txt", "Esta es un otro string de test"); _zipFile.Save(); _zipFile.UpdateEntry("test3.txt", "This is another string for content."); _zipFile.Save(); } } } } [TestMethod] public void Update_MultipleSaves_wi10694() { string zipFileToCreate = "Update_MultipleSaves_wi10694.zip"; var shortDir = "fodder"; string subdir = Path.Combine(TopLevelDir, shortDir); string[] filesToZip = TestUtilities.GenerateFilesFlat(subdir); using (ZipFile zip1 = new ZipFile()) { zip1.AddFiles(filesToZip, "Download"); zip1.AddFiles(filesToZip, "other"); zip1.Save(zipFileToCreate); } Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), 2 * filesToZip.Length, "Incorrect number of entries in the zip file."); using (var zip2 = ZipFile.Read(zipFileToCreate)) { var entries = zip2.Entries.Where(e => e.FileName.Contains("Download")).ToArray(); //PART1 - Add directory and save zip2.AddDirectoryByName("XX"); zip2.Save(); //PART2 - Rename paths (not related to XX directory from above) and save foreach (var zipEntry in entries) { zipEntry.FileName = zipEntry.FileName.Replace("Download", "Download2"); } zip2.Save(); } Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), 2 * filesToZip.Length, "Incorrect number of entries in the zip file."); } [TestMethod] public void Update_MultipleSavesWithRename_wi10544() { // select the name of the zip file string zipFileToCreate = Path.Combine(TopLevelDir, "Update_MultipleSaves_wi10319.zip"); string entryName = "Entry1.txt"; TestContext.WriteLine("Creating zip file... "); using (var zip = new ZipFile()) { string firstline = "This is the first line in the Entry.\n"; byte[] a = System.Text.Encoding.ASCII.GetBytes(firstline.ToCharArray()); zip.AddEntry(entryName, a); zip.Save(zipFileToCreate); } int N = _rnd.Next(34) + 59; for (int i = 0; i < N; i++) { string tempZipFile = "AppendToEntry.zip.tmp" + i; TestContext.WriteLine("Update cycle {0}... ", i); using (var zip1 = ZipFile.Read(zipFileToCreate)) { using (var zip = new ZipFile()) { zip.AddEntry(entryName, (name, stream) => { var src = zip1[name].OpenReader(); int n; byte[] b = new byte[2048]; while ((n = src.Read(b, 0, b.Length)) > 0) stream.Write(b, 0, n); string update = String.Format("Updating zip file {0} at {1}\n", i, DateTime.Now.ToString("G")); byte[] a = System.Text.Encoding.ASCII.GetBytes(update.ToCharArray()); stream.Write(a, 0, a.Length); }); zip.Save(tempZipFile); } } File.Delete(zipFileToCreate); System.Threading.Thread.Sleep(1400); File.Move(tempZipFile, zipFileToCreate); } } [TestMethod] public void Update_FromRoot_wi11988() { string zipFileToCreate = "FromRoot.zip"; string dirToZip = "Fodder"; var files = TestUtilities.GenerateFilesFlat(dirToZip); string windir = System.Environment.GetEnvironmentVariable("Windir"); string substExe = Path.Combine(Path.Combine(windir, "system32"), "subst.exe"); Assert.IsTrue(File.Exists(substExe), "subst.exe does not exist ({0})", substExe); try { // create a subst drive this.Exec(substExe, "G: " + dirToZip); using (var zip = new ZipFile()) { zip.UpdateSelectedFiles("*.*", "G:\\", "", true); zip.Save(zipFileToCreate); } Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), files.Length); Assert.IsTrue(files.Length > 3); BasicVerifyZip(zipFileToCreate); } finally { // remove the virt drive this.Exec(substExe, "/D G:"); } } } } <|start_filename|>Code/DotNetZip/Zip Tests/BasicTests.cs<|end_filename|> // BasicTests.cs // ------------------------------------------------------------------ // // Copyright (c) 2009-2011 <NAME> // All rights reserved. // // This code module is part of DotNetZip, a zipfile class library. // // ------------------------------------------------------------------ // // This code is licensed under the Microsoft Public License. // See the file License.txt for the license details. // More info on: http://dotnetzip.codeplex.com // // ------------------------------------------------------------------ // // last saved (in emacs): // Time-stamp: <2011-July-26 11:39:21> // // ------------------------------------------------------------------ // // This module defines basic unit tests for DotNetZip. // // ------------------------------------------------------------------ using System; using System.Text; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; using RE = System.Text.RegularExpressions; using Ionic.Zip; using Ionic.Zip.Tests.Utilities; using System.IO; namespace Ionic.Zip.Tests.Basic { /// <summary> /// Summary description for UnitTest1 /// </summary> [TestClass] public class BasicTests : IonicTestClass { EncryptionAlgorithm[] crypto = { EncryptionAlgorithm.None, EncryptionAlgorithm.PkzipWeak, EncryptionAlgorithm.WinZipAes128, EncryptionAlgorithm.WinZipAes256, }; public BasicTests() : base() { } [TestMethod] public void CreateZip_AddItem_WithDirectory() { // select the name of the zip file string zipFileToCreate = "CreateZip_AddItem.zip"; // create a bunch of files string subdir = "files"; string[] filesToZip = TestUtilities.GenerateFilesFlat(subdir); // Create the zip archive using (ZipFile zip1 = new ZipFile()) { //zip.StatusMessageTextWriter = System.Console.Out; for (int i = 0; i < filesToZip.Length; i++) zip1.AddItem(filesToZip[i], "files"); zip1.Save(zipFileToCreate); } // Verify the number of files in the zip Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), filesToZip.Length); } [TestMethod] public void CreateZip_AddItem_NoDirectory() { string zipFileToCreate = "CreateZip_AddItem.zip"; string[] filesToZip = TestUtilities.GenerateFilesFlat("."); // Create the zip archive using (ZipFile zip1 = new ZipFile()) { foreach (var f in filesToZip) zip1.AddItem(f); zip1.Save(zipFileToCreate); } // Verify the number of files in the zip Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), filesToZip.Length); } [TestMethod] [ExpectedException(typeof(Ionic.Zip.ZipException))] public void FileNotAvailableFails_wi10387() { string zipFileToCreate = Path.Combine(TopLevelDir, "FileNotAvailableFails.zip"); using (var zip1 = new ZipFile(zipFileToCreate)) { zip1.Save(); } try { using (new FileStream(zipFileToCreate, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) { using (new ZipFile(zipFileToCreate)) { } } } finally { } } [TestMethod] public void CreateZip_AddFile() { int i; string zipFileToCreate = "CreateZip_AddFile.zip"; string subdir = "files"; string[] filesToZip = TestUtilities.GenerateFilesFlat(subdir); using (ZipFile zip1 = new ZipFile()) { for (i = 0; i < filesToZip.Length; i++) zip1.AddFile(filesToZip[i], "files"); zip1.Save(zipFileToCreate); } Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), filesToZip.Length); } [TestMethod] public void CreateZip_AddFile_CharCase_wi13481() { string zipFileToCreate = "AddFile.zip"; string subdir = "files"; string[] filesToZip = TestUtilities.GenerateFilesFlat(subdir); Directory.SetCurrentDirectory(subdir); Array.ForEach(filesToZip, x => { File.Move(Path.GetFileName(x),Path.GetFileName(x).ToUpper()); }); Directory.SetCurrentDirectory(TopLevelDir); filesToZip= Directory.GetFiles(subdir); using (ZipFile zip1 = new ZipFile()) { for (int i = 0; i < filesToZip.Length; i++) zip1.AddFile(filesToZip[i], "files"); zip1.Save(zipFileToCreate); } Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), filesToZip.Length); int nEntries = 0; // now, verify that we have not downcased the filenames using (ZipFile zip2 = new ZipFile(zipFileToCreate)) { foreach (var entry in zip2.Entries) { var fname1 = Path.GetFileName(entry.FileName); var fnameLower = fname1.ToLower(); Assert.IsFalse(fname1.Equals(fnameLower), "{0} is all lowercase.", fname1); nEntries++; } } Assert.IsFalse(nEntries < 2, "not enough entries"); } [TestMethod] public void CreateZip_AddFileInDirectory() { string subdir = "fodder"; TestUtilities.GenerateFilesFlat(subdir); for (int m = 0; m < 2; m++) { string directoryName = ""; for (int k = 0; k < 4; k++) { // select the name of the zip file string zipFileToCreate = String.Format("CreateZip_AddFileInDirectory-trial{0}.{1}.zip", m, k); TestContext.WriteLine("====================="); TestContext.WriteLine("Trial {0}", k); TestContext.WriteLine("Zipfile: {0}", zipFileToCreate); directoryName = Path.Combine(directoryName, String.Format("{0:D2}", k)); string[] filesToSelectFrom = Directory.GetFiles(subdir, "*.*", SearchOption.AllDirectories); TestContext.WriteLine("using dirname: {0}", directoryName); int n = _rnd.Next(filesToSelectFrom.Length / 2) + 2; TestContext.WriteLine("Zipping {0} files", n); // Create the zip archive var addedFiles = new List<String>(); using (ZipFile zip1 = new ZipFile()) { // add n files int j=0; for (int i = 0; i < n; i++) { // select files at random while (addedFiles.Contains(filesToSelectFrom[j])) j = _rnd.Next(filesToSelectFrom.Length); zip1.AddFile(filesToSelectFrom[j], directoryName); addedFiles.Add(filesToSelectFrom[j]); } zip1.Save(zipFileToCreate); } // Verify the number of files in the zip Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), n, "Wrong number of entries in the zip file {0}", zipFileToCreate); using (ZipFile zip2 = ZipFile.Read(zipFileToCreate)) { foreach (var e in zip2) { TestContext.WriteLine("Check entry: {0}", e.FileName); Assert.AreEqual<String>(directoryName, Path.GetDirectoryName(e.FileName), "Wrong directory on zip entry {0}", e.FileName); } } } // add progressively more files to the fodder directory TestUtilities.GenerateFilesFlat(subdir); } } [TestMethod] public void CreateZip_AddFile_LeadingDot() { // select the name of the zip file string zipFileToCreate = "CreateZip_AddFile_LeadingDot.zip"; string[] filesToZip = TestUtilities.GenerateFilesFlat("."); using (ZipFile zip1 = new ZipFile()) { for (int i = 0; i < filesToZip.Length; i++) { zip1.AddFile(filesToZip[i]); } zip1.Save(zipFileToCreate); } Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), filesToZip.Length); } [TestMethod] public void CreateZip_AddFiles_LeadingDot_Array() { // select the name of the zip file string zipFileToCreate = "CreateZip_AddFiles_LeadingDot_Array.zip"; string[] filesToZip = TestUtilities.GenerateFilesFlat("."); // Create the zip archive using (ZipFile zip1 = new ZipFile()) { zip1.AddFiles(filesToZip); zip1.Save(zipFileToCreate); } // Verify the number of files in the zip Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), filesToZip.Length); } [TestMethod] public void CreateZip_AddFiles_PreserveDirHierarchy() { // select the name of the zip file string zipFileToCreate = "CreateZip_AddFiles_PreserveDirHierarchy.zip"; string dirToZip = "zipthis"; // create a bunch of files int subdirCount; int entries = TestUtilities.GenerateFilesOneLevelDeep(TestContext, "PreserveDirHierarchy", dirToZip, null, out subdirCount); string[] filesToZip = Directory.GetFiles(".", "*.*", SearchOption.AllDirectories); Assert.AreEqual<int>(filesToZip.Length, entries); // Create the zip archive using (ZipFile zip1 = new ZipFile()) { zip1.AddFiles(filesToZip, true, ""); zip1.Save(zipFileToCreate); } // Verify the number of files in the zip Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), filesToZip.Length); } private bool ArraysAreEqual(byte[] b1, byte[] b2) { return (CompareArrays(b1, b2) == 0); } private int CompareArrays(byte[] b1, byte[] b2) { if (b1 == null && b2 == null) return 0; if (b1 == null || b2 == null) return 0; if (b1.Length > b2.Length) return 1; if (b1.Length < b2.Length) return -1; for (int i = 0; i < b1.Length; i++) { if (b1[i] > b2[i]) return 1; if (b1[i] < b2[i]) return -1; } return 0; } [TestMethod] public void CreateZip_AddEntry_ByteArray() { // select the name of the zip file string zipFileToCreate = "CreateZip_AddEntry_ByteArray.zip"; int entriesToCreate = _rnd.Next(42) + 12; var dict = new Dictionary<string, byte[]>(); // Create the zip archive using (ZipFile zip1 = new ZipFile()) { for (int i = 0; i < entriesToCreate; i++) { var b = new byte[_rnd.Next(1000) + 1000]; _rnd.NextBytes(b); string filename = String.Format("Filename{0:D3}.bin", i); var e = zip1.AddEntry(Path.Combine("data", filename), b); dict.Add(e.FileName, b); } zip1.Save(zipFileToCreate); } // Verify the number of files in the zip Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), entriesToCreate); using (ZipFile zip1 = ZipFile.Read(zipFileToCreate)) { foreach (var e in zip1) { // extract to a stream using (var ms1 = new MemoryStream()) { e.Extract(ms1); Assert.IsTrue(ArraysAreEqual(ms1.ToArray(), dict[e.FileName])); } } } } [TestMethod] public void CreateZip_AddFile_AddItem() { string zipFileToCreate = "CreateZip_AddFile_AddItem.zip"; string subdir = "files"; string[] filesToZip = TestUtilities.GenerateFilesFlat(subdir); // use the parameterized ctor using (ZipFile zip1 = new ZipFile(zipFileToCreate)) { for (int i = 0; i < filesToZip.Length; i++) { if (_rnd.Next(2) == 0) zip1.AddFile(filesToZip[i], "files"); else zip1.AddItem(filesToZip[i], "files"); } zip1.Save(); } // Verify the number of files in the zip Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), filesToZip.Length); } private void DumpZipFile(ZipFile z) { TestContext.WriteLine("found {0} entries", z.Entries.Count); TestContext.WriteLine("RequiresZip64: '{0}'", z.RequiresZip64.HasValue ? z.RequiresZip64.Value.ToString() : "not set"); TestContext.WriteLine("listing the entries in {0}...", String.IsNullOrEmpty(z.Name) ? "(zipfile)" : z.Name); foreach (var e in z) { TestContext.WriteLine("{0}", e.FileName); } } [TestMethod] public void CreateZip_ZeroEntries() { // select the name of the zip file string zipFileToCreate = "CreateZip_ZeroEntries.zip"; using (ZipFile zip1 = new ZipFile()) { zip1.Save(zipFileToCreate); DumpZipFile(zip1); } // workitem 7685 using (ZipFile zip1 = new ZipFile(zipFileToCreate)) { DumpZipFile(zip1); } using (ZipFile zip1 = ZipFile.Read(zipFileToCreate)) { DumpZipFile(zip1); } // Verify the number of files in the zip Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), 0); } [TestMethod] public void CreateZip_Basic_ParameterizedSave() { string zipFileToCreate = "CreateZip_Basic_ParameterizedSave.zip"; string subdir = "files"; int numFilesToCreate = _rnd.Next(23) + 14; string[] filesToZip = TestUtilities.GenerateFilesFlat(subdir, numFilesToCreate); using (ZipFile zip1 = new ZipFile()) { //zip.StatusMessageTextWriter = System.Console.Out; for (int i = 0; i < filesToZip.Length; i++) { if (_rnd.Next(2) == 0) zip1.AddFile(filesToZip[i], "files"); else zip1.AddItem(filesToZip[i], "files"); } zip1.Save(zipFileToCreate); } // Verify the number of files in the zip Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), filesToZip.Length); } [TestMethod] public void CreateZip_AddFile_OnlyZeroLengthFiles() { _Internal_ZeroLengthFiles(_rnd.Next(33) + 3, "CreateZip_AddFile_OnlyZeroLengthFiles", null); } [TestMethod] public void CreateZip_AddFile_OnlyZeroLengthFiles_Password() { _Internal_ZeroLengthFiles(_rnd.Next(33) + 3, "CreateZip_AddFile_OnlyZeroLengthFiles", Path.GetRandomFileName()); } [TestMethod] public void CreateZip_AddFile_OneZeroLengthFile() { _Internal_ZeroLengthFiles(1, "CreateZip_AddFile_OneZeroLengthFile", null); } [TestMethod] public void CreateZip_AddFile_OneZeroLengthFile_Password() { _Internal_ZeroLengthFiles(1, "CreateZip_AddFile_OneZeroLengthFile_Password", Path.GetRandomFileName()); } private void _Internal_ZeroLengthFiles(int fileCount, string nameStub, string password) { string zipFileToCreate = Path.Combine(TopLevelDir, nameStub + ".zip"); int i; string[] filesToZip = new string[fileCount]; for (i = 0; i < fileCount; i++) filesToZip[i] = TestUtilities.CreateUniqueFile("zerolength", TopLevelDir); var sw = new StringWriter(); using (ZipFile zip = new ZipFile()) { zip.StatusMessageTextWriter = sw; zip.Password = password; for (i = 0; i < filesToZip.Length; i++) zip.AddFile(filesToZip[i]); zip.Save(zipFileToCreate); } string status = sw.ToString(); TestContext.WriteLine("save output: " + status); BasicVerifyZip(zipFileToCreate, password); Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), filesToZip.Length, "The zip file created has the wrong number of entries."); } [TestMethod] public void CreateZip_UpdateDirectory() { int i, j; string zipFileToCreate = "CreateZip_UpdateDirectory.zip"; string dirToZip = "zipthis"; Directory.CreateDirectory(dirToZip); TestContext.WriteLine("\n------------\nCreating files ..."); int entries = 0; int subdirCount = _rnd.Next(17) + 14; //int subdirCount = _rnd.Next(3) + 2; var FileCount = new Dictionary<string, int>(); var checksums = new Dictionary<string, byte[]>(); for (i = 0; i < subdirCount; i++) { string subdirShort = String.Format("dir{0:D4}", i); string subdir = Path.Combine(dirToZip, subdirShort); Directory.CreateDirectory(subdir); int filecount = _rnd.Next(11) + 17; //int filecount = _rnd.Next(2) + 2; FileCount[subdirShort] = filecount; for (j = 0; j < filecount; j++) { string filename = String.Format("file{0:D4}.x", j); string fqFilename = Path.Combine(subdir, filename); TestUtilities.CreateAndFillFile(fqFilename, _rnd.Next(1000) + 100); var chk = TestUtilities.ComputeChecksum(fqFilename); var t1 = Path.GetFileName(dirToZip); var t2 = Path.Combine(t1, subdirShort); var key = Path.Combine(t2, filename); key = TestUtilities.TrimVolumeAndSwapSlashes(key); TestContext.WriteLine("chk[{0}]= {1}", key, TestUtilities.CheckSumToString(chk)); checksums.Add(key, chk); entries++; } } Directory.SetCurrentDirectory(TopLevelDir); TestContext.WriteLine("\n------------\nAdding files into the Zip..."); // add all the subdirectories into a new zip using (ZipFile zip1 = new ZipFile()) { zip1.AddDirectory(dirToZip, "zipthis"); zip1.Save(zipFileToCreate); } TestContext.WriteLine("\n"); Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), entries, "The Zip file has an unexpected number of entries."); TestContext.WriteLine("\n------------\nExtracting and validating checksums..."); // validate all the checksums using (ZipFile zip2 = ZipFile.Read(zipFileToCreate)) { foreach (ZipEntry e in zip2) { e.Extract("unpack"); string pathToExtractedFile = Path.Combine("unpack", e.FileName); // if it is a file.... if (checksums.ContainsKey(e.FileName)) { // verify the checksum of the file is correct string expectedCheckString = TestUtilities.CheckSumToString(checksums[e.FileName]); string actualCheckString = TestUtilities.GetCheckSumString(pathToExtractedFile); Assert.AreEqual<String> (expectedCheckString, actualCheckString, "Unexpected checksum on extracted filesystem file ({0}).", pathToExtractedFile); } } } TestContext.WriteLine("\n------------\nCreating some new files ..."); // now, update some of the existing files dirToZip = Path.Combine(TopLevelDir, "updates"); Directory.CreateDirectory(dirToZip); for (i = 0; i < subdirCount; i++) { string subdirShort = String.Format("dir{0:D4}", i); string subdir = Path.Combine(dirToZip, subdirShort); Directory.CreateDirectory(subdir); int filecount = FileCount[subdirShort]; for (j = 0; j < filecount; j++) { if (_rnd.Next(2) == 1) { string filename = String.Format("file{0:D4}.x", j); TestUtilities.CreateAndFillFile(Path.Combine(subdir, filename), _rnd.Next(1000) + 100); string fqFilename = Path.Combine(subdir, filename); var chk = TestUtilities.ComputeChecksum(fqFilename); //var t1 = Path.GetFileName(dirToZip); var t2 = Path.Combine("zipthis", subdirShort); var key = Path.Combine(t2, filename); key = TestUtilities.TrimVolumeAndSwapSlashes(key); TestContext.WriteLine("chk[{0}]= {1}", key, TestUtilities.CheckSumToString(chk)); checksums.Remove(key); checksums.Add(key, chk); } } } TestContext.WriteLine("\n------------\nUpdating some of the files in the zip..."); // add some new content using (ZipFile zip3 = ZipFile.Read(zipFileToCreate)) { zip3.UpdateDirectory(dirToZip, "zipthis"); //String[] dirs = Directory.GetDirectories(dirToZip); //foreach (String d in dirs) //{ // string dir = Path.Combine(Path.GetFileName(dirToZip), Path.GetFileName(d)); // //string root = Path.Combine("zipthis", Path.GetFileName(d)); // zip3.UpdateDirectory(dir, "zipthis"); //} zip3.Save(); } TestContext.WriteLine("\n------------\nValidating the checksums for all of the files ..."); // validate all the checksums again using (ZipFile zip4 = ZipFile.Read(zipFileToCreate)) { foreach (ZipEntry e in zip4) TestContext.WriteLine("Found entry: {0}", e.FileName); foreach (ZipEntry e in zip4) { e.Extract("unpack2"); if (!e.IsDirectory) { string pathToExtractedFile = Path.Combine("unpack2", e.FileName); // verify the checksum of the file is correct string expectedCheckString = TestUtilities.CheckSumToString(checksums[e.FileName]); string actualCheckString = TestUtilities.GetCheckSumString(pathToExtractedFile); Assert.AreEqual<String> (expectedCheckString, actualCheckString, "Unexpected checksum on extracted filesystem file ({0}).", pathToExtractedFile); } } } } [TestMethod] public void CreateZip_AddDirectory_OnlyZeroLengthFiles() { string zipFileToCreate = "CreateZip_AddDirectory_OnlyZeroLengthFiles.zip"; string dirToZip = "zipthis"; Directory.CreateDirectory(dirToZip); int entries = 0; int subdirCount = _rnd.Next(8) + 8; for (int i = 0; i < subdirCount; i++) { string subdir = Path.Combine(dirToZip, "dir" + i); Directory.CreateDirectory(subdir); int n = _rnd.Next(6) + 2; for (int j=0; j < n; j++) { TestUtilities.CreateUniqueFile("bin", subdir); entries++; } } using (var zip = new ZipFile()) { zip.AddDirectory(Path.GetFileName(dirToZip)); zip.Save(zipFileToCreate); } Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), entries); } [TestMethod] public void CreateZip_AddDirectory_OneZeroLengthFile() { string zipFileToCreate = "CreateZip_AddDirectory_OneZeroLengthFile.zip"; string dirToZip = "zipthis"; Directory.CreateDirectory(dirToZip); // one empty file string file = TestUtilities.CreateUniqueFile("ZeroLengthFile.txt", dirToZip); using (ZipFile zip = new ZipFile()) { zip.AddDirectory(Path.GetFileName(dirToZip)); zip.Save(zipFileToCreate); } Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), 1); } [TestMethod] public void CreateZip_AddDirectory_OnlyEmptyDirectories() { string zipFileToCreate = "CreateZip_AddDirectory_OnlyEmptyDirectories.zip"; string dirToZip = "zipthis"; Directory.CreateDirectory(dirToZip); int subdirCount = _rnd.Next(28) + 18; for (int i = 0; i < subdirCount; i++) { string subdir = Path.Combine(dirToZip, "EmptyDir" + i); Directory.CreateDirectory(subdir); } using (ZipFile zip = new ZipFile()) { zip.AddDirectory(Path.GetFileName(dirToZip)); zip.Save(zipFileToCreate); } Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), 0); } [TestMethod] public void CreateZip_AddDirectory_OneEmptyDirectory() { string zipFileToCreate = "CreateZip_AddDirectory_OneEmptyDirectory.zip"; string dirToZip = "zipthis"; Directory.CreateDirectory(dirToZip); using (ZipFile zip = new ZipFile()) { zip.AddDirectory(Path.GetFileName(dirToZip)); zip.Save(zipFileToCreate); } Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), 0); BasicVerifyZip(zipFileToCreate); } [TestMethod] public void CreateZip_WithEmptyDirectory() { string zipFileToCreate = "Create_WithEmptyDirectory.zip"; string subdir = "EmptyDirectory"; Directory.CreateDirectory(subdir); using (ZipFile zip = new ZipFile()) { zip.AddDirectory(subdir, ""); zip.Save(zipFileToCreate); } Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), 0); BasicVerifyZip(zipFileToCreate); } [TestMethod] public void CreateZip_AddDirectory_CheckStatusTextWriter() { string zipFileToCreate = "CreateZip_AddDirectory_CheckStatusTextWriter.zip"; string dirToZip = "zipthis"; Directory.CreateDirectory(dirToZip); int entries = 0; int subdirCount = _rnd.Next(8) + 8; for (int i = 0; i < subdirCount; i++) { string subdir = Path.Combine(dirToZip, "Dir" + i); Directory.CreateDirectory(subdir); // a few files per subdir int fileCount = _rnd.Next(12) + 4; for (int j = 0; j < fileCount; j++) { string file = Path.Combine(subdir, "File" + j); TestUtilities.CreateAndFillFile(file, 1020); entries++; } } var sw = new StringWriter(); using (ZipFile zip = new ZipFile()) { zip.StatusMessageTextWriter = sw; zip.AddDirectory(Path.GetFileName(dirToZip)); zip.Save(zipFileToCreate); } string status = sw.ToString(); TestContext.WriteLine("save output: " + status); Assert.IsTrue(status.Length > 24 * entries, "status messages? ({0}!>{1})", status.Length, 24 * entries); int n = TestUtilities.CountEntries(zipFileToCreate); Assert.AreEqual<int>(n, entries, "wrong number of entries. ({0}!={1})", n, entries); BasicVerifyZip(zipFileToCreate); } struct TestTrial { public string arg; public string re; } [TestMethod] public void CreateZip_AddDirectory() { TestTrial[] trials = { new TestTrial { arg=null, re="^file(\\d+).ext$"}, new TestTrial { arg="", re="^file(\\d+).ext$"}, new TestTrial { arg=null, re="^file(\\d+).ext$"}, new TestTrial { arg="Xabf", re="(?s)^Xabf/(file(\\d+).ext)?$"}, new TestTrial { arg="AAAA/BBB", re="(?s)^AAAA/BBB/(file(\\d+).ext)?$"} }; for (int k = 0; k < trials.Length; k++) { TestContext.WriteLine("\n--------------------------------\n\n\n"); string zipFileToCreate = Path.Combine(TopLevelDir, String.Format("CreateZip_AddDirectory-{0}.zip", k)); Assert.IsFalse(File.Exists(zipFileToCreate), "The temporary zip file '{0}' already exists.", zipFileToCreate); string dirToZip = String.Format("DirectoryToZip.{0}.test", k); Directory.CreateDirectory(dirToZip); int fileCount = _rnd.Next(5) + 4; for (int i = 0; i < fileCount; i++) { String file = Path.Combine(dirToZip, String.Format("file{0:D3}.ext", i)); TestUtilities.CreateAndFillFile(file, _rnd.Next(2000) + 500); } var sw = new StringWriter(); using (ZipFile zip = new ZipFile()) { zip.StatusMessageTextWriter = sw; if (k == 0) zip.AddDirectory(dirToZip); else zip.AddDirectory(dirToZip, trials[k].arg); zip.Save(zipFileToCreate); } TestContext.WriteLine(sw.ToString()); Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), fileCount, String.Format("The zip file created in cycle {0} has the wrong number of entries.", k)); //TestContext.WriteLine(""); // verify that the entries in the zip are in the top level directory!! using (ZipFile zip2 = ZipFile.Read(zipFileToCreate)) { foreach (ZipEntry e in zip2) TestContext.WriteLine("found entry: {0}", e.FileName); foreach (ZipEntry e in zip2) { //Assert.IsFalse(e.FileName.StartsWith("dir"), // String.Format("The Zip entry '{0}' is not rooted in top level directory.", e.FileName)); // check the filename: //RE.Match m0 = RE.Regex.Match(e.FileName, fnameRegex[k]); // Assert.IsTrue(m0 != null, "No match"); // Assert.AreEqual<int>(m0.Groups.Count, 2, // String.Format("In cycle {0}, Matching {1} against {2}, Wrong number of matches ({3})", // k, e.FileName, fnameRegex[k], m0.Groups.Count)); Assert.IsTrue(RE.Regex.IsMatch(e.FileName, trials[k].re), String.Format("In cycle {0}, Matching {1} against {2}", k, e.FileName, trials[k].re)); } } } } [TestMethod] public void CreateZip_AddDirectory_Nested() { // Each trial provides a directory name into which to add // files, and a regex, used for verification after the zip // is created, to match the names on any added entries. TestTrial[] trials = { new TestTrial { arg=null, re="^dir(\\d){3}/(file(\\d+).ext)?$"}, new TestTrial { arg="", re="^dir(\\d){3}/(file(\\d+).ext)?$"}, new TestTrial { arg=null, re="^dir(\\d){3}/(file(\\d+).ext)?$"}, new TestTrial { arg="rtdha", re="(?s)^rtdha/(dir(\\d){3}/(file(\\d+).ext)?)?$"}, new TestTrial { arg="sdfjk/BBB", re="(?s)^sdfjk/BBB/(dir(\\d){3}/(file(\\d+).ext)?)?$"} }; for (int k = 0; k < trials.Length; k++) { TestContext.WriteLine("\n--------------------------------\n\n\n"); string zipFileToCreate = Path.Combine(TopLevelDir, String.Format("CreateZip_AddDirectory_Nested-{0}.zip", k)); Assert.IsFalse(File.Exists(zipFileToCreate), "The temporary zip file '{0}' already exists.", zipFileToCreate); string dirToZip = String.Format("DirectoryToZip.{0}.test", k); Directory.CreateDirectory(dirToZip); int i, j; int entries = 0; int subdirCount = _rnd.Next(23) + 7; for (i = 0; i < subdirCount; i++) { string subdir = Path.Combine(dirToZip, String.Format("dir{0:D3}", i)); Directory.CreateDirectory(subdir); int fileCount = _rnd.Next(8); // sometimes zero for (j = 0; j < fileCount; j++) { String file = Path.Combine(subdir, String.Format("file{0:D3}.ext", j)); TestUtilities.CreateAndFillFile(file, _rnd.Next(10750) + 50); entries++; } } var sw = new StringWriter(); using (ZipFile zip = new ZipFile()) { zip.StatusMessageTextWriter = sw; if (k == 0) zip.AddDirectory(dirToZip); else zip.AddDirectory(dirToZip, trials[k].arg); zip.Save(zipFileToCreate); } TestContext.WriteLine(sw.ToString()); Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), entries, String.Format("The zip file created in cycle {0} has the wrong number of entries.", k)); // verify that the entries in the zip are in the top level directory!! using (ZipFile zip2 = ZipFile.Read(zipFileToCreate)) { foreach (ZipEntry e in zip2) TestContext.WriteLine("found entry: {0}", e.FileName); foreach (ZipEntry e in zip2) { Assert.IsTrue(RE.Regex.IsMatch(e.FileName, trials[k].re), String.Format("In cycle {0}, Matching {1} against {2}", k, e.FileName, trials[k].re)); } } } } [TestMethod] public void Basic_SaveToFileStream() { // from small numbers of files to larger numbers of files for (int k = 0; k < 3; k++) { string zipFileToCreate = String.Format("SaveToFileStream-t{0}.zip", k); string dirToZip = Path.GetRandomFileName(); Directory.CreateDirectory(dirToZip); int filesToAdd = _rnd.Next(k * 10 + 3) + k * 10 + 3; for (int i = 0; i < filesToAdd; i++) { var s = Path.Combine(dirToZip, String.Format("tempfile-{0}.bin", i)); int sz = _rnd.Next(10000) + 5000; TestContext.WriteLine(" Creating file: {0} sz({1})", s, sz); TestUtilities.CreateAndFillFileBinary(s, sz); } using (var fileStream = File.Create(zipFileToCreate)) { using (ZipFile zip1 = new ZipFile()) { zip1.AddDirectory(dirToZip); zip1.Comment = "This is a Comment On the Archive (AM/PM)"; zip1.Save(fileStream); } } // Verify the files are in the zip Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), filesToAdd, "Trial {0}: file {1} wrong number of entries.", k, zipFileToCreate); } } [TestMethod] public void Basic_IsText() { // from small numbers of files to larger numbers of files for (int k = 0; k < 3; k++) { string zipFileToCreate = String.Format("Basic_IsText-trial{0}.zip", k); string dirToZip = Path.GetRandomFileName(); Directory.CreateDirectory(dirToZip); int filesToAdd = _rnd.Next(33) + 11; for (int i = 0; i < filesToAdd; i++) { var s = Path.Combine(dirToZip, String.Format("tempfile-{0}.txt", i)); int sz = _rnd.Next(10000) + 5000; TestContext.WriteLine(" Creating file: {0} sz({1})", s, sz); TestUtilities.CreateAndFillFileText(s, sz); } using (ZipFile zip1 = new ZipFile()) { int count = 0; var filesToZip = Directory.GetFiles(dirToZip); foreach (var f in filesToZip) { var e = zip1.AddFile(f, "files"); switch (k) { case 0: break; case 1: if ((count % 2) == 0) e.IsText = true; break; case 2: if ((count % 2) != 0) e.IsText = true; break; case 3: e.IsText = true; break; } count++; } zip1.Comment = "This is a Comment On the Archive (AM/PM)"; zip1.Save(zipFileToCreate); } // Verify the files are in the zip Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), filesToAdd, "trial {0}: file {1} number of entries.", k, zipFileToCreate); // verify the isText setting using (ZipFile zip2 = ZipFile.Read(zipFileToCreate)) { int count = 0; foreach (var e in zip2) { switch (k) { case 0: Assert.IsFalse(e.IsText); break; case 1: Assert.AreEqual<bool>((count % 2) == 0, e.IsText); break; case 2: Assert.AreEqual<bool>((count % 2) != 0, e.IsText); break; case 3: Assert.IsTrue(e.IsText); break; } count++; } } } } [TestMethod] public void CreateZip_VerifyThatStreamRemainsOpenAfterSave() { Ionic.Zlib.CompressionLevel[] compressionLevelOptions = { Ionic.Zlib.CompressionLevel.None, Ionic.Zlib.CompressionLevel.BestSpeed, Ionic.Zlib.CompressionLevel.Default, Ionic.Zlib.CompressionLevel.BestCompression, }; string[] Passwords = { null, Path.GetRandomFileName() }; for (int j = 0; j < Passwords.Length; j++) { for (int k = 0; k < compressionLevelOptions.Length; k++) { TestContext.WriteLine("\n\n---------------------------------\n" + "Trial ({0},{1}): Password='{2}' Compression={3}\n", j, k, Passwords[j], compressionLevelOptions[k]); string dirToZip = Path.GetRandomFileName(); Directory.CreateDirectory(dirToZip); int filesAdded = _rnd.Next(3) + 3; for (int i = 0; i < filesAdded; i++) { var s = Path.Combine(dirToZip, String.Format("tempfile-{0}-{1}-{2}.bin", j, k, i)); int sz = _rnd.Next(10000) + 5000; TestContext.WriteLine(" Creating file: {0} sz({1})", s, sz); TestUtilities.CreateAndFillFileBinary(s, sz); } TestContext.WriteLine("\n"); //string dirToZip = Path.GetFileName(TopLevelDir); var ms = new MemoryStream(); Assert.IsTrue(ms.CanSeek, String.Format("Trial {0}: The output MemoryStream does not do Seek.", k)); using (ZipFile zip1 = new ZipFile()) { zip1.CompressionLevel = compressionLevelOptions[k]; zip1.Password = Passwords[j]; zip1.Comment = String.Format("Trial ({0},{1}): Password='{2}' Compression={3}\n", j, k, Passwords[j], compressionLevelOptions[k]); zip1.AddDirectory(dirToZip); zip1.Save(ms); } Assert.IsTrue(ms.CanSeek, String.Format("Trial {0}: After writing, the OutputStream does not do Seek.", k)); Assert.IsTrue(ms.CanRead, String.Format("Trial {0}: The OutputStream cannot be Read.", k)); // seek to the beginning ms.Seek(0, SeekOrigin.Begin); int filesFound = 0; using (ZipFile zip2 = ZipFile.Read(ms)) { foreach (ZipEntry e in zip2) { TestContext.WriteLine(" Found entry: {0} isDir({1}) sz_c({2}) sz_unc({3})", e.FileName, e.IsDirectory, e.CompressedSize, e.UncompressedSize); if (!e.IsDirectory) filesFound++; } } Assert.AreEqual<int>(filesFound, filesAdded, "Trial {0}", k); } } } [TestMethod] public void CreateZip_AddFile_VerifyCrcAndContents() { string filename = null; int entriesAdded = 0; string repeatedLine = null; int j; string zipFileToCreate = "CreateZip_AddFile_VerifyCrcAndContents.zip"; string subdir = "A"; Directory.CreateDirectory(subdir); // create the files int numFilesToCreate = _rnd.Next(10) + 8; for (j = 0; j < numFilesToCreate; j++) { filename = Path.Combine(subdir, String.Format("file{0:D3}.txt", j)); repeatedLine = String.Format("This line is repeated over and over and over in file {0}", Path.GetFileName(filename)); TestUtilities.CreateAndFillFileText(filename, repeatedLine, _rnd.Next(34000) + 5000); entriesAdded++; } using (ZipFile zip1 = new ZipFile()) { String[] filenames = Directory.GetFiles("A"); foreach (String f in filenames) zip1.AddFile(f, ""); zip1.Comment = "UpdateTests::CreateZip_AddFile_VerifyCrcAndContents(): This archive will be updated."; zip1.Save(zipFileToCreate); } Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate),entriesAdded); // now extract the files and verify their contents using (ZipFile zip2 = ZipFile.Read(zipFileToCreate)) { foreach (string s in zip2.EntryFileNames) { repeatedLine = String.Format("This line is repeated over and over and over in file {0}", s); zip2[s].Extract("extract"); // verify the content of the updated file. var sr = new StreamReader(Path.Combine("extract", s)); string actualLine = sr.ReadLine(); sr.Close(); Assert.AreEqual<string>(repeatedLine, actualLine, "Updated file ({0}) is incorrect.", s); } } } [TestMethod] public void Extract_IntoMemoryStream() { string filename = null; int entriesAdded = 0; string repeatedLine = null; int j; string zipFileToCreate = "Extract_IntoMemoryStream.zip"; string subdir = "A"; Directory.CreateDirectory(subdir); // create the files int numFilesToCreate = _rnd.Next(10) + 8; for (j = 0; j < numFilesToCreate; j++) { filename = Path.Combine(subdir, String.Format("file{0:D3}.txt", j)); repeatedLine = String.Format("This line is repeated over and over and over in file {0}", Path.GetFileName(filename)); TestUtilities.CreateAndFillFileText(filename, repeatedLine, _rnd.Next(34000) + 5000); entriesAdded++; } // Create the zip file using (ZipFile zip1 = new ZipFile()) { String[] filenames = Directory.GetFiles("A"); foreach (String f in filenames) zip1.AddFile(f, ""); zip1.Comment = "BasicTests::Extract_IntoMemoryStream()"; zip1.Save(zipFileToCreate); } // Verify the files are in the zip Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), entriesAdded, "The Zip file has the wrong number of entries."); // now extract the files into memory streams, checking only the length of the file. using (ZipFile zip2 = ZipFile.Read(zipFileToCreate)) { foreach (string s in zip2.EntryFileNames) { using (MemoryStream ms = new MemoryStream()) { zip2[s].Extract(ms); byte[] a = ms.ToArray(); string f = Path.Combine(subdir, s); var fi = new FileInfo(f); Assert.AreEqual<int>((int)(fi.Length), a.Length, "Unequal file lengths."); } } } } [TestMethod] public void Retrieve_ViaIndexer2_wi11056() { string fileName = "wi11056.dwf"; string entryName = @"com.autodesk.dwf.ePlot_5VFMLy3OdEetAPFe7uWXYg\descriptor.xml"; string SourceDir = CurrentDir; for (int i = 0; i < 3; i++) SourceDir = Path.GetDirectoryName(SourceDir); TestContext.WriteLine("Current Dir: {0}", CurrentDir); string filename = Path.Combine(SourceDir, "Zip Tests\\bin\\Debug\\zips\\" + fileName); TestContext.WriteLine("Reading zip file: '{0}'", filename); using (ZipFile zip = ZipFile.Read(filename)) { var e = zip[entryName]; Assert.IsFalse(e == null, "Retrieval by stringindex failed."); } } [TestMethod] public void Retrieve_ViaIndexer() { // select the name of the zip file string zipFileToCreate = Path.Combine(TopLevelDir, "Retrieve_ViaIndexer.zip"); string filename = null; int entriesAdded = 0; string repeatedLine = null; int j; // create the subdirectory string subdir = "A"; Directory.CreateDirectory(subdir); // create the files int numFilesToCreate = _rnd.Next(10) + 8; for (j = 0; j < numFilesToCreate; j++) { filename = Path.Combine(subdir, String.Format("File{0:D3}.txt", j)); repeatedLine = String.Format("This line is repeated over and over and over in file {0}", Path.GetFileName(filename)); TestUtilities.CreateAndFillFileText(filename, repeatedLine, _rnd.Next(23000) + 4000); entriesAdded++; } // Create the zip file using (ZipFile zip1 = new ZipFile()) { String[] filenames = Directory.GetFiles("A"); foreach (String f in filenames) zip1.AddFile(f, ""); zip1.Comment = "BasicTests::Retrieve_ViaIndexer()"; zip1.Save(zipFileToCreate); } // Verify the files are in the zip Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), entriesAdded, "The Zip file has the wrong number of entries."); // now extract the files into memory streams, checking only the length of the file. // We do 4 combinations: case-sensitive on or off, and filename conversion on or off. for (int m = 0; m < 2; m++) { for (int n = 0; n < 2; n++) { using (ZipFile zip2 = ZipFile.Read(zipFileToCreate)) { if (n == 1) zip2.CaseSensitiveRetrieval = true; foreach (string s in zip2.EntryFileNames) { var s2 = (m == 1) ? s.ToUpper() : s; using (MemoryStream ms = new MemoryStream()) { try { zip2[s2].Extract(ms); byte[] a = ms.ToArray(); string f = Path.Combine(subdir, s2); var fi = new FileInfo(f); Assert.AreEqual<int>((int)(fi.Length), a.Length, "Unequal file lengths."); } catch { Assert.AreEqual<int>(1, n * m, "Indexer retrieval failed unexpectedly."); } } } } } } } [TestMethod] public void CreateZip_SetFileComments() { string zipFileToCreate = "FileComments.zip"; string FileCommentFormat = "Comment Added By Test to file '{0}'"; string commentOnArchive = "Comment added by FileComments() method."; int fileCount = _rnd.Next(3) + 3; string[] filesToZip = new string[fileCount]; for (int i = 0; i < fileCount; i++) { filesToZip[i] = Path.Combine(TopLevelDir, String.Format("file{0:D3}.bin", i)); TestUtilities.CreateAndFillFile(filesToZip[i], _rnd.Next(10000) + 5000); } using (ZipFile zip = new ZipFile()) { //zip.StatusMessageTextWriter = System.Console.Out; for (int i = 0; i < filesToZip.Length; i++) { // use the local filename (not fully qualified) ZipEntry e = zip.AddFile(Path.GetFileName(filesToZip[i])); e.Comment = String.Format(FileCommentFormat, e.FileName); } zip.Comment = commentOnArchive; zip.Save(zipFileToCreate); } int entries = 0; using (ZipFile z2 = ZipFile.Read(zipFileToCreate)) { Assert.AreEqual<String>(commentOnArchive, z2.Comment, "Unexpected comment on ZipFile."); foreach (ZipEntry e in z2) { string expectedComment = String.Format(FileCommentFormat, e.FileName); Assert.AreEqual<string>(expectedComment, e.Comment, "Unexpected comment on ZipEntry."); entries++; } } Assert.AreEqual<int>(entries, filesToZip.Length, "Unexpected file count. Expected {0}, got {1}.", filesToZip.Length, entries); } [TestMethod] public void CreateZip_SetFileLastModified() { //int fileCount = _rnd.Next(13) + 23; int fileCount = _rnd.Next(3) + 2; string[] filesToZip = new string[fileCount]; for (int i = 0; i < fileCount; i++) { filesToZip[i] = Path.Combine(TopLevelDir, String.Format("file{0:D3}.bin", i)); TestUtilities.CreateAndFillFileBinary(filesToZip[i], _rnd.Next(10000) + 5000); } DateTime[] timestamp = { new System.DateTime(2007, 9, 1, 15, 0, 0), new System.DateTime(2007, 4, 2, 14, 0, 0), new System.DateTime(2007, 5, 18, 19, 0, 0), }; // try Kind = unspecified, local, and UTC DateTimeKind[] kinds = { DateTimeKind.Unspecified, DateTimeKind.Local, DateTimeKind.Utc, }; for (int m = 0; m < timestamp.Length; m++) { for (int n = 0; n < 3; n++) { for (int k = 0; k < 2; k++) { string zipFileToCreate = Path.Combine(TopLevelDir, String.Format("CreateZip-SetFileLastModified-{0}.{1}.{2}.zip", m, n, k)); TestContext.WriteLine("Cycle {0}.{1}.{2}", m, n, k); TestContext.WriteLine("zipfile {0}", zipFileToCreate); DateTime t = DateTime.SpecifyKind(timestamp[m], kinds[n]); using (ZipFile zip = new ZipFile()) { zip.EmitTimesInWindowsFormatWhenSaving = (k != 0); for (int i = 0; i < filesToZip.Length; i++) { // use the local filename (not fully qualified) ZipEntry e = zip.AddFile(Path.GetFileName(filesToZip[i])); e.LastModified = t; } zip.Comment = "All files in this archive have the same LastModified value."; zip.Save(zipFileToCreate); } // NB: comparing two DateTime variables will return "not // equal" if they are not of the same "Kind", even if they // represent the same point in time. To counteract that, // we compare using UniversalTime. var x1 = t.ToUniversalTime().ToString("u"); string unpackDir = String.Format("unpack{0}.{1}.{2}", m, n, k); int entries = 0; using (ZipFile z2 = ZipFile.Read(zipFileToCreate)) { foreach (ZipEntry e in z2) { var t2 = e.LastModified; var x2 = t2.ToUniversalTime().ToString("u"); Assert.AreEqual<String>(x1, x2, "cycle {0}.{1}.{2}: Unexpected LastModified value on ZipEntry.", m, n, k); entries++; // now verify that the LastMod time on the filesystem file is set correctly e.Extract(unpackDir); DateTime ActualFilesystemLastMod = File.GetLastWriteTime(Path.Combine(unpackDir, e.FileName)); ActualFilesystemLastMod = AdjustTime_Win32ToDotNet(ActualFilesystemLastMod); //Assert.AreEqual<DateTime>(t, ActualFilesystemLastMod, x2 = ActualFilesystemLastMod.ToUniversalTime().ToString("u"); Assert.AreEqual<String>(x1, x2, "cycle {0}.{1}.{2}: Unexpected LastWriteTime on extracted filesystem file.", m, n, k); } } Assert.AreEqual<int>(entries, filesToZip.Length, "Unexpected file count. Expected {0}, got {1}.", filesToZip.Length, entries); } } } } [TestMethod] public void CreateAndExtract_VerifyAttributes() { try { string zipFileToCreate = "CreateAndExtract_VerifyAttributes.zip"; string subdir = "A"; Directory.CreateDirectory(subdir); //int fileCount = _rnd.Next(13) + 23; FileAttributes[] attributeCombos = { FileAttributes.ReadOnly, FileAttributes.ReadOnly | FileAttributes.System, FileAttributes.ReadOnly | FileAttributes.System | FileAttributes.Hidden, FileAttributes.ReadOnly | FileAttributes.System | FileAttributes.Hidden | FileAttributes.Archive, FileAttributes.ReadOnly | FileAttributes.Hidden, FileAttributes.ReadOnly | FileAttributes.Hidden| FileAttributes.Archive, FileAttributes.ReadOnly | FileAttributes.Archive, FileAttributes.System, FileAttributes.System | FileAttributes.Hidden, FileAttributes.System | FileAttributes.Hidden | FileAttributes.Archive, FileAttributes.System | FileAttributes.Archive, FileAttributes.Hidden, FileAttributes.Hidden | FileAttributes.Archive, FileAttributes.Archive, FileAttributes.Normal, FileAttributes.NotContentIndexed | FileAttributes.ReadOnly, FileAttributes.NotContentIndexed | FileAttributes.System, FileAttributes.NotContentIndexed | FileAttributes.Hidden, FileAttributes.NotContentIndexed | FileAttributes.Archive, FileAttributes.Temporary, FileAttributes.Temporary | FileAttributes.Archive, }; int fileCount = attributeCombos.Length; string[] filesToZip = new string[fileCount]; TestContext.WriteLine("============\nCreating."); for (int i = 0; i < fileCount; i++) { filesToZip[i] = Path.Combine(subdir, String.Format("file{0:D3}.bin", i)); TestUtilities.CreateAndFillFileBinary(filesToZip[i], _rnd.Next(10000) + 5000); TestContext.WriteLine("Creating {0} [{1}]", filesToZip[i], attributeCombos[i].ToString()); File.SetAttributes(filesToZip[i], attributeCombos[i]); } TestContext.WriteLine("============\nZipping."); using (ZipFile zip = new ZipFile()) { for (int i = 0; i < filesToZip.Length; i++) { // use the local filename (not fully qualified) ZipEntry e = zip.AddFile(filesToZip[i], ""); } zip.Save(zipFileToCreate); } int entries = 0; TestContext.WriteLine("============\nExtracting."); using (ZipFile z2 = ZipFile.Read(zipFileToCreate)) { foreach (ZipEntry e in z2) { TestContext.WriteLine("Extracting {0}", e.FileName); Assert.AreEqual<FileAttributes> (attributeCombos[entries], e.Attributes, "unexpected attribute {0} 0x{1:X4}", e.FileName, (int)e.Attributes); entries++; e.Extract("unpack"); // now verify that the attributes are set // correctly in the filesystem var attrs = File.GetAttributes(Path.Combine("unpack", e.FileName)); Assert.AreEqual<FileAttributes>(attrs, e.Attributes, "Unexpected attributes on the extracted filesystem file {0}.", e.FileName); } } Assert.AreEqual<int>(entries, filesToZip.Length, "Bad file count. Expected {0}, got {1}.", filesToZip.Length, entries); } catch (Exception ex1) { TestContext.WriteLine("Exception: " + ex1); throw; } } [TestMethod] public void CreateAndExtract_SetAndVerifyAttributes() { string zipFileToCreate = "CreateAndExtract_SetAndVerifyAttributes.zip"; // Here, we build a list of combinations of FileAttributes // to try. We cannot simply do an exhaustive combination // because (a) not all combinations are valid, and (b) if // you SetAttributes(file,Compressed) (also with Encrypted, // ReparsePoint) it does not "work." So those attributes // must be excluded. FileAttributes[] attributeCombos = { FileAttributes.ReadOnly, FileAttributes.ReadOnly | FileAttributes.System, FileAttributes.ReadOnly | FileAttributes.System | FileAttributes.Hidden, FileAttributes.ReadOnly | FileAttributes.System | FileAttributes.Hidden | FileAttributes.Archive, FileAttributes.ReadOnly | FileAttributes.Hidden, FileAttributes.ReadOnly | FileAttributes.Hidden| FileAttributes.Archive, FileAttributes.ReadOnly | FileAttributes.Archive, FileAttributes.System, FileAttributes.System | FileAttributes.Hidden, FileAttributes.System | FileAttributes.Hidden | FileAttributes.Archive, FileAttributes.System | FileAttributes.Archive, FileAttributes.Hidden, FileAttributes.Hidden | FileAttributes.Archive, FileAttributes.Archive, FileAttributes.Normal, FileAttributes.NotContentIndexed | FileAttributes.ReadOnly, FileAttributes.NotContentIndexed | FileAttributes.System, FileAttributes.NotContentIndexed | FileAttributes.Hidden, FileAttributes.NotContentIndexed | FileAttributes.Archive, FileAttributes.Temporary, FileAttributes.Temporary | FileAttributes.Archive, }; int fileCount = attributeCombos.Length; TestContext.WriteLine("============\nZipping."); using (ZipFile zip = new ZipFile()) { for (int i = 0; i < fileCount; i++) { // use the local filename (not fully qualified) ZipEntry e = zip.AddEntry("file" + i.ToString(), "FileContent: This file has these attributes: " + attributeCombos[i].ToString()); TestContext.WriteLine("Adding {0} [{1}]", e.FileName, attributeCombos[i].ToString()); e.Attributes = attributeCombos[i]; } zip.Save(zipFileToCreate); } int entries = 0; TestContext.WriteLine("============\nExtracting."); using (ZipFile z2 = ZipFile.Read(zipFileToCreate)) { foreach (ZipEntry e in z2) { TestContext.WriteLine("Extracting {0}", e.FileName); Assert.AreEqual<FileAttributes> (attributeCombos[entries], e.Attributes, "unexpected attributes value in the entry {0} 0x{1:X4}", e.FileName, (int)e.Attributes); entries++; e.Extract("unpack"); // now verify that the attributes are set correctly in the filesystem var attrs = File.GetAttributes(Path.Combine("unpack", e.FileName)); Assert.AreEqual<FileAttributes> (e.Attributes, attrs, "Unexpected attributes on the extracted filesystem file {0}.", e.FileName); } } Assert.AreEqual<int>(fileCount, entries, "Unexpected file count."); } [TestMethod] [Timeout(1000 * 240)] // timeout in ms. 240s = 4 mins public void CreateZip_VerifyFileLastModified() { string zipFileToCreate = "CreateZip_VerifyFileLastModified.zip"; string envTemp = Environment.GetEnvironmentVariable("TEMP"); String[] candidateFileNames = Directory.GetFiles(envTemp); var checksums = new Dictionary<string, byte[]>(); var timestamps = new Dictionary<string, DateTime>(); var actualFilenames = new List<string>(); var excludedFilenames = new List<string>(); int maxFiles = _rnd.Next(candidateFileNames.Length / 2) + candidateFileNames.Length / 3; maxFiles = Math.Min(maxFiles, 145); //maxFiles = Math.Min(maxFiles, 15); TestContext.WriteLine("\n-----------------------------\r\n{1}: Finding files in '{0}'...", envTemp, DateTime.Now.ToString("HH:mm:ss")); do { string filename = null; bool foundOne = false; while (!foundOne) { filename = candidateFileNames[_rnd.Next(candidateFileNames.Length)]; if (excludedFilenames.Contains(filename)) continue; var fi = new FileInfo(filename); if (Path.GetFileName(filename)[0] == '~' || actualFilenames.Contains(filename) || fi.Length > 10000000 || Path.GetFileName(filename) == "dd_BITS.log" // There WERE some weird files on my system that cause this // test to fail! the GetLastWrite() method returns the // "wrong" time - does not agree with what is shown in // Explorer or in a cmd.exe dir output. So I exclude those // files here. (This is no longer a problem?) //|| filename.EndsWith(".cer") //|| filename.EndsWith(".msrcincident") //|| filename == "MSCERTS.ini" ) { excludedFilenames.Add(filename); } else { foundOne = true; } } var key = Path.GetFileName(filename); // surround this in a try...catch so as to avoid grabbing a file that is open by someone else, or has disappeared try { var lastWrite = File.GetLastWriteTime(filename); var fi = new FileInfo(filename); // Rounding to nearest even second was necessary when DotNetZip did // not process NTFS times in the NTFS Extra field. Since v1.8.0.5, // this is no longer the case. // // var tm = TestUtilities.RoundToEvenSecond(lastWrite); var tm = lastWrite; // hop out of the try block if the file is from TODAY. (heuristic // to avoid currently open files) if ((tm.Year == DateTime.Now.Year) && (tm.Month == DateTime.Now.Month) && (tm.Day == DateTime.Now.Day)) throw new Exception(); var chk = TestUtilities.ComputeChecksum(filename); checksums.Add(key, chk); TestContext.WriteLine(" {4}: {1} {2} {3,-9} {0}", Path.GetFileName(filename), lastWrite.ToString("yyyy MMM dd HH:mm:ss"), tm.ToString("yyyy MMM dd HH:mm:ss"), fi.Length, DateTime.Now.ToString("HH:mm:ss")); timestamps.Add(key, this.AdjustTime_Win32ToDotNet(tm)); actualFilenames.Add(filename); } catch { excludedFilenames.Add(filename); } } while ((actualFilenames.Count < maxFiles) && (actualFilenames.Count < candidateFileNames.Length) && actualFilenames.Count + excludedFilenames.Count < candidateFileNames.Length); TestContext.WriteLine("{0}: Creating zip...", DateTime.Now.ToString("HH:mm:ss")); // create the zip file using (ZipFile zip = new ZipFile()) { foreach (string s in actualFilenames) { ZipEntry e = zip.AddFile(s, ""); e.Comment = File.GetLastWriteTime(s).ToString("yyyyMMMdd HH:mm:ss"); } zip.Comment = "The files in this archive will be checked for LastMod timestamp and checksum."; TestContext.WriteLine("{0}: Saving zip....", DateTime.Now.ToString("HH:mm:ss")); zip.Save(zipFileToCreate); } TestContext.WriteLine("{0}: Unpacking zip....", DateTime.Now.ToString("HH:mm:ss")); // unpack the zip, and verify contents int entries = 0; using (ZipFile z2 = ZipFile.Read(zipFileToCreate)) { foreach (ZipEntry e in z2) { TestContext.WriteLine("{0}: Checking entry {1}....", DateTime.Now.ToString("HH:mm:ss"), e.FileName); entries++; // verify that the LastMod time on the filesystem file is set correctly e.Extract("unpack"); string pathToExtractedFile = Path.Combine("unpack", e.FileName); DateTime actualFilesystemLastMod = AdjustTime_Win32ToDotNet(File.GetLastWriteTime(pathToExtractedFile)); TimeSpan delta = timestamps[e.FileName] - actualFilesystemLastMod; // get the delta as an absolute value: if (delta < new TimeSpan(0, 0, 0)) delta = new TimeSpan(0, 0, 0) - delta; TestContext.WriteLine("time delta: {0}", delta.ToString()); // The time delta can be at most, 1 second. Assert.IsTrue(delta < new TimeSpan(0, 0, 1), "Unexpected LastMod timestamp on extracted filesystem file ({0}) expected({1}) actual({2}) delta({3}).", pathToExtractedFile, timestamps[e.FileName].ToString("F"), actualFilesystemLastMod.ToString("F"), delta.ToString() ); // verify the checksum of the file is correct string expectedCheckString = TestUtilities.CheckSumToString(checksums[e.FileName]); string actualCheckString = TestUtilities.GetCheckSumString(pathToExtractedFile); Assert.AreEqual<String> (expectedCheckString, actualCheckString, "Unexpected checksum on extracted filesystem file ({0}).", pathToExtractedFile); } } Assert.AreEqual<int>(entries, actualFilenames.Count, "Unexpected file count."); } private DateTime AdjustTime_Win32ToDotNet(DateTime time) { // If I read a time from a file with GetLastWriteTime() (etc), I need // to adjust it for display in the .NET environment. if (time.Kind == DateTimeKind.Utc) return time; DateTime adjusted = time; if (DateTime.Now.IsDaylightSavingTime() && !time.IsDaylightSavingTime()) adjusted = time + new System.TimeSpan(1, 0, 0); else if (!DateTime.Now.IsDaylightSavingTime() && time.IsDaylightSavingTime()) adjusted = time - new System.TimeSpan(1, 0, 0); return adjusted; } [TestMethod] public void CreateZip_AddDirectory_NoFilesInRoot() { string zipFileToCreate = "CreateZip_AddDirectory_NoFilesInRoot.zip"; string zipThis = "ZipThis"; Directory.CreateDirectory(zipThis); int i, j; int entries = 0; int subdirCount = _rnd.Next(4) + 4; for (i = 0; i < subdirCount; i++) { string subdir = Path.Combine(zipThis, "DirectoryToZip.test." + i); Directory.CreateDirectory(subdir); int fileCount = _rnd.Next(3) + 3; for (j = 0; j < fileCount; j++) { String file = Path.Combine(subdir, "file" + j); TestUtilities.CreateAndFillFile(file, _rnd.Next(1000) + 1500); entries++; } } using (ZipFile zip = new ZipFile()) { zip.AddDirectory(zipThis); zip.Save(zipFileToCreate); } Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), entries, "The Zip file has the wrong number of entries."); } [TestMethod] public void CreateZip_AddDirectory_OneCharOverrideName() { int entries = 0; String filename = null; // set the name of the zip file to create string zipFileToCreate = "CreateZip_AddDirectory_OneCharOverrideName.zip"; String commentOnArchive = "BasicTests::CreateZip_AddDirectory_OneCharOverrideName(): This archive override the name of a directory with a one-char name."; string subdir = "A"; Directory.CreateDirectory(subdir); int numFilesToCreate = _rnd.Next(23) + 14; var checksums = new Dictionary<string, string>(); for (int j = 0; j < numFilesToCreate; j++) { filename = Path.Combine(subdir, String.Format("file{0:D3}.txt", j)); TestUtilities.CreateAndFillFileText(filename, _rnd.Next(12000) + 5000); var chk = TestUtilities.ComputeChecksum(filename); var relativePath = Path.Combine(Path.GetFileName(subdir), Path.GetFileName(filename)); //var key = Path.Combine("A", filename); var key = TestUtilities.TrimVolumeAndSwapSlashes(relativePath); checksums.Add(key, TestUtilities.CheckSumToString(chk)); entries++; } using (ZipFile zip1 = new ZipFile()) { zip1.AddDirectory(subdir, Path.GetFileName(subdir)); zip1.Comment = commentOnArchive; zip1.Save(zipFileToCreate); } Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), entries); // validate all the checksums using (ZipFile zip2 = ZipFile.Read(zipFileToCreate)) { foreach (ZipEntry e in zip2) { e.Extract("unpack"); if (checksums.ContainsKey(e.FileName)) { string pathToExtractedFile = Path.Combine("unpack", e.FileName); // verify the checksum of the file is correct string expectedCheckString = checksums[e.FileName]; string actualCheckString = TestUtilities.GetCheckSumString(pathToExtractedFile); Assert.AreEqual<String> (expectedCheckString, actualCheckString, "Unexpected checksum on extracted filesystem file ({0}).", pathToExtractedFile); } } } } [TestMethod] public void CreateZip_CompressionLevelZero_AllEntries() { string zipFileToCreate = "CompressionLevelZero.zip"; String commentOnArchive = "BasicTests::CompressionLevelZero(): This archive override the name of a directory with a one-char name."; int entriesAdded = 0; String filename = null; string subdir = "A"; Directory.CreateDirectory(subdir); int fileCount = _rnd.Next(10) + 10; for (int j = 0; j < fileCount; j++) { filename = Path.Combine(subdir, String.Format("file{0:D3}.txt", j)); TestUtilities.CreateAndFillFileText(filename, _rnd.Next(34000) + 5000); entriesAdded++; } using (ZipFile zip = new ZipFile()) { zip.CompressionLevel = Ionic.Zlib.CompressionLevel.None; zip.AddDirectory(subdir, Path.GetFileName(subdir)); zip.Comment = commentOnArchive; zip.Save(zipFileToCreate); } int entriesFound = 0; using (ZipFile zip = ZipFile.Read(zipFileToCreate)) { foreach (ZipEntry e in zip) { if (!e.IsDirectory) entriesFound++; Assert.AreEqual<short>(0, (short)e.CompressionMethod, "compression method"); } } Assert.AreEqual<int>(entriesAdded, entriesFound, "unexpected number of entries."); BasicVerifyZip(zipFileToCreate); } [TestMethod] public void CreateZip_ForceNoCompressionSomeEntries() { string zipFileToCreate = "ForceNoCompression.zip"; String filename = null; string subdir = "A"; Directory.CreateDirectory(subdir); int fileCount = _rnd.Next(13) + 13; for (int j = 0; j < fileCount; j++) { filename = Path.Combine(subdir, String.Format("{0}-file{1:D3}.txt", (_rnd.Next(2) == 0) ? "C":"U", j)); TestUtilities.CreateAndFillFileText(filename, _rnd.Next(34000) + 5000); } using (ZipFile zip = new ZipFile()) { String[] filenames = Directory.GetFiles("A"); foreach (String f in filenames) { ZipEntry e = zip.AddFile(f, ""); if (e.FileName.StartsWith("U")) e.CompressionMethod = 0x0; } zip.Comment = "Some of these files do not use compression."; zip.Save(zipFileToCreate); } int entriesFound = 0; using (ZipFile zip = ZipFile.Read(zipFileToCreate)) { foreach (ZipEntry e in zip) { if (!e.IsDirectory) entriesFound++; Assert.AreEqual<Int32>((e.FileName.StartsWith("U"))?0x00:0x08, (Int32)e.CompressionMethod, "Unexpected compression method on text file ({0}).", e.FileName); } } Assert.AreEqual<int>(fileCount, entriesFound, "The created Zip file has an unexpected number of entries."); BasicVerifyZip(zipFileToCreate); } [TestMethod] public void AddFile_CompressionMethod_None_wi9208() { string zipFileToCreate = "AddFile_CompressionMethod_None_wi9208.zip"; string subdir = "A"; Directory.CreateDirectory(subdir); using (ZipFile zip = new ZipFile()) { string filename = Path.Combine(subdir, String.Format("FileToBeAdded-{0:D2}.txt", _rnd.Next(1000))); TestUtilities.CreateAndFillFileText(filename, _rnd.Next(34000) + 5000); var e = zip.AddFile(filename,"zipped"); e.CompressionMethod = CompressionMethod.None; zip.Save(zipFileToCreate); } TestContext.WriteLine("File zipped!..."); TestContext.WriteLine("Reading..."); using (ZipFile zip = ZipFile.Read(zipFileToCreate)) { foreach (var e in zip) { Assert.AreEqual<String>("None", e.CompressionMethod.ToString()); } } BasicVerifyZip(zipFileToCreate); } [TestMethod] public void GetInfo() { TestContext.WriteLine("GetInfo"); string zipFileToCreate = "GetInfo.zip"; String filename = null; int n; string subdir = Path.Combine(TopLevelDir, TestUtilities.GenerateRandomAsciiString(9)); Directory.CreateDirectory(subdir); int fileCount = _rnd.Next(27) + 23; TestContext.WriteLine("Creating {0} files", fileCount); for (int j = 0; j < fileCount; j++) { filename = Path.Combine(subdir, String.Format("file{0:D3}.txt", j)); if (_rnd.Next(7)!=0) TestUtilities.CreateAndFillFileText(filename, _rnd.Next(34000) + 5000); else { // create an empty file using (var fs = File.Create(filename)) { } } } TestContext.WriteLine("Creating a zip file"); using (ZipFile zip = new ZipFile()) { zip.Password = TestUtilities.GenerateRandomPassword(11); var filenames = Directory.GetFiles(subdir); foreach (String f in filenames) { ZipEntry e = zip.AddFile(f, ""); if (_rnd.Next(3)==0) e.CompressionMethod = 0x0; n = _rnd.Next(crypto.Length); e.Encryption = crypto[n]; } zip.Save(zipFileToCreate); } TestContext.WriteLine("Calling ZipFile::Info_get"); using (ZipFile zip = ZipFile.Read(zipFileToCreate)) { string info = zip.Info; TestContext.WriteLine("Info: (len({0}))", info.Length); foreach (var line in info.Split('\n')) TestContext.WriteLine(line); Assert.IsTrue(info.Length > 300, "Suspect info string (length({0}))", info.Length); } } [TestMethod] public void Create_WithChangeDirectory() { string zipFileToCreate = "Create_WithChangeDirectory.zip"; String filename = "Testfile.txt"; TestUtilities.CreateAndFillFileText(filename, _rnd.Next(34000) + 5000); string cwd = Directory.GetCurrentDirectory(); using (var zip = new ZipFile()) { zip.AddFile(filename, ""); Directory.SetCurrentDirectory("\\"); zip.AddFile("dev\\codeplex\\DotNetZip\\Zip Tests\\BasicTests.cs", ""); Directory.SetCurrentDirectory(cwd); zip.Save(zipFileToCreate); } } private void VerifyEntries(string zipFile, Variance variance, int[] values, EncryptionAlgorithm[] a, int stage, int compFlavor, int encryptionFlavor) { using (var zip = ZipFile.Read(zipFile)) { foreach (ZipEntry e in zip) { var compCheck = false; if (variance == Variance.Method) { compCheck = (e.CompressionMethod == (CompressionMethod)values[stage]); } else { // Variance.Level CompressionMethod expectedMethod = ((Ionic.Zlib.CompressionLevel)values[stage] == Ionic.Zlib.CompressionLevel.None) ? CompressionMethod.None : CompressionMethod.Deflate; compCheck = (e.CompressionMethod == expectedMethod); } Assert.IsTrue(compCheck, "Unexpected compression method ({0}) on entry ({1}) variance({2}) flavor({3},{4}) stage({5})", e.CompressionMethod, e.FileName, variance, compFlavor, encryptionFlavor, stage ); var cryptoCheck = (e.Encryption == a[stage]); Assert.IsTrue(cryptoCheck, "Unexpected encryption ({0}) on entry ({1}) variance({2}) flavor({3},{4}) stage({5})", e.Encryption, e.FileName, variance, compFlavor, encryptionFlavor, stage ); } } } private void QuickCreateZipAndChecksums(string zipFile, Variance variance, object compressionMethodOrLevel, EncryptionAlgorithm encryption, string password, out string[] files, out Dictionary<string, byte[]> checksums ) { string srcDir = TestUtilities.GetTestSrcDir(CurrentDir); files = Directory.GetFiles(srcDir, "*.cs", SearchOption.TopDirectoryOnly); checksums = new Dictionary<string, byte[]>(); foreach (string f in files) { var chk = TestUtilities.ComputeChecksum(f); var key = Path.GetFileName(f); checksums.Add(key, chk); } using (var zip = new ZipFile()) { if (variance == Variance.Level) { zip.CompressionLevel= (Ionic.Zlib.CompressionLevel) compressionMethodOrLevel; } else { if ((Ionic.Zip.CompressionMethod)compressionMethodOrLevel == CompressionMethod.None) zip.CompressionLevel = Ionic.Zlib.CompressionLevel.None; } if (password != null) { zip.Password = password; zip.Encryption = encryption; } zip.AddFiles(files, ""); zip.Save(zipFile); } int count = TestUtilities.CountEntries(zipFile); Assert.IsTrue(count > 5, "Unexpected number of entries ({0}) in the zip file.", count); } enum Variance { Method = 0 , Level = 1 } private string GeneratePassword() { return TestUtilities.GenerateRandomPassword(); //return TestUtilities.GenerateRandomAsciiString(9); //return "Alphabet"; } private void _Internal_Resave(string zipFile, Variance variance, int[] values, EncryptionAlgorithm[] cryptos, int compFlavor, int encryptionFlavor ) { // Create a zip file, then re-save it with changes in compression methods, // compression levels, and/or encryption. The methods/levels, cryptos are // for original and re-saved values. This tests whether we can update a zip // entry with changes in those properties. string[] passwords = new string[2]; passwords[0]= (cryptos[0]==EncryptionAlgorithm.None) ? null : GeneratePassword(); passwords[1]= passwords[0] ?? ((cryptos[1]==EncryptionAlgorithm.None) ? null : GeneratePassword()); //TestContext.WriteLine(" crypto: '{0}' '{1}'", crypto[0]??"-NONE-", passwords[1]??"-NONE-"); TestContext.WriteLine(" crypto: '{0}' '{1}'", cryptos[0], cryptos[1]); // first, create a zip file string[] filesToZip; Dictionary<string, byte[]> checksums; QuickCreateZipAndChecksums(zipFile, variance, values[0], cryptos[0], passwords[0], out filesToZip, out checksums); // check that the zip was constructed as expected VerifyEntries(zipFile, variance, values, cryptos, 0, compFlavor, encryptionFlavor); // modify some properties (CompressionLevel, CompressionMethod, and/or Encryption) on each entry using (var zip = ZipFile.Read(zipFile)) { zip.Password = <PASSWORD>[1]; foreach (ZipEntry e in zip) { if (variance == Variance.Method) e.CompressionMethod = (CompressionMethod)values[1]; else e.CompressionLevel = (Ionic.Zlib.CompressionLevel)values[1]; e.Encryption = cryptos[1]; } zip.Save(); } // Check that the zip was modified as expected VerifyEntries(zipFile, variance, values, cryptos, 1, compFlavor, encryptionFlavor); // now extract the items and verify checksums string extractDir = "ex"; int c=0; while (Directory.Exists(extractDir + c)) c++; extractDir += c; // extract using (var zip = ZipFile.Read(zipFile)) { zip.Password = <PASSWORD>]; zip.ExtractAll(extractDir); } VerifyChecksums(extractDir, filesToZip, checksums); } EncryptionAlgorithm[][] CryptoPairs = { new EncryptionAlgorithm[] {EncryptionAlgorithm.None, EncryptionAlgorithm.None}, new EncryptionAlgorithm[] {EncryptionAlgorithm.None, EncryptionAlgorithm.WinZipAes128}, new EncryptionAlgorithm[] {EncryptionAlgorithm.WinZipAes128, EncryptionAlgorithm.None}, new EncryptionAlgorithm[] {EncryptionAlgorithm.WinZipAes128, EncryptionAlgorithm.WinZipAes128}, new EncryptionAlgorithm[] {EncryptionAlgorithm.None, EncryptionAlgorithm.PkzipWeak}, new EncryptionAlgorithm[] {EncryptionAlgorithm.PkzipWeak, EncryptionAlgorithm.None}, new EncryptionAlgorithm[] {EncryptionAlgorithm.WinZipAes128, EncryptionAlgorithm.PkzipWeak}, new EncryptionAlgorithm[] {EncryptionAlgorithm.PkzipWeak, EncryptionAlgorithm.WinZipAes128} }; int[][][] VariancePairs = { new int[][] { new int[] {(int)CompressionMethod.Deflate, (int)CompressionMethod.Deflate}, new int[] {(int)CompressionMethod.Deflate, (int)CompressionMethod.None}, new int[] {(int)CompressionMethod.None, (int)CompressionMethod.Deflate}, new int[] {(int)CompressionMethod.None, (int)CompressionMethod.None} }, new int[][] { new int[] {(int)Ionic.Zlib.CompressionLevel.Default, (int)Ionic.Zlib.CompressionLevel.Default}, new int[] {(int)Ionic.Zlib.CompressionLevel.Default, (int)Ionic.Zlib.CompressionLevel.None}, new int[] {(int)Ionic.Zlib.CompressionLevel.None, (int)Ionic.Zlib.CompressionLevel.Default}, new int[] {(int)Ionic.Zlib.CompressionLevel.None, (int)Ionic.Zlib.CompressionLevel.None} } }; private void _Internal_Resave(Variance variance, int compFlavor, int encryptionFlavor) { // Check that re-saving a zip, after modifying properties on // each entry, actually does what we want. if (encryptionFlavor == 0) TestContext.WriteLine("Resave workdir: {0}", TopLevelDir); string rootname = String.Format("Resave_Compression{0}_{1}_Encryption_{2}.zip", variance, compFlavor, encryptionFlavor); string zipFileToCreate = Path.Combine(TopLevelDir, rootname); int[] values = VariancePairs[(int)variance][compFlavor]; TestContext.WriteLine("Resave {0} {1} {2} file({3})", variance, compFlavor, encryptionFlavor, Path.GetFileName(zipFileToCreate)); _Internal_Resave(zipFileToCreate, variance, values, CryptoPairs[encryptionFlavor], compFlavor, encryptionFlavor); } [TestMethod] public void Resave_CompressionMethod_0() { for (int i=0; i<8; i++) { _Internal_Resave(Variance.Method, 0, i); } } [TestMethod] public void Resave_CompressionMethod_1() { for (int i=0; i<8; i++) { if (i!=3) _Internal_Resave(Variance.Method, 1, i); } } [TestMethod] public void Resave_CompressionMethod_2() { for (int i=0; i<8; i++) { _Internal_Resave(Variance.Method, 2, i); } } [TestMethod] public void Resave_CompressionMethod_3() { for (int i=0; i<8; i++) { _Internal_Resave(Variance.Method, 3, i); } } [TestMethod] public void Resave_CompressionLevel_0() { for (int i=0; i<8; i++) { _Internal_Resave(Variance.Level, 0, i); } } [TestMethod] public void Resave_CompressionLevel_1() { for (int i=0; i<8; i++) { if (i!=3) _Internal_Resave(Variance.Level, 1, i); } } [TestMethod] public void Resave_CompressionLevel_2() { for (int i=0; i<8; i++) { _Internal_Resave(Variance.Level, 2, i); } } [TestMethod] public void Resave_CompressionLevel_3() { for (int i=0; i<8; i++) { _Internal_Resave(Variance.Level, 3, i); } } } } <|start_filename|>Code/Topshelf/src/Topshelf/Configuration/CommandLineParser/ICommandLineElementParser.cs<|end_filename|> // Copyright 2007-2012 <NAME>, <NAME>, <NAME>, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace Topshelf.CommandLineParser { using System; using System.Collections.Generic; /// <summary> /// Used to configure the command line element parser /// </summary> /// <typeparam name="TResult"> The type of object returned as a result of the parse </typeparam> interface ICommandLineElementParser<TResult> { /// <summary> /// Adds a new pattern to the parser /// </summary> /// <param name="parser"> The pattern to match and return the resulting object </param> void Add(Parser<IEnumerable<ICommandLineElement>, TResult> parser); Parser<IEnumerable<ICommandLineElement>, IArgumentElement> Argument(); Parser<IEnumerable<ICommandLineElement>, IArgumentElement> Argument(string value); Parser<IEnumerable<ICommandLineElement>, IArgumentElement> Argument(Predicate<IArgumentElement> pred); Parser<IEnumerable<ICommandLineElement>, IDefinitionElement> Definition(); Parser<IEnumerable<ICommandLineElement>, IDefinitionElement> Definition(string key); Parser<IEnumerable<ICommandLineElement>, IDefinitionElement> Definitions(params string[] keys); Parser<IEnumerable<ICommandLineElement>, ISwitchElement> Switch(); Parser<IEnumerable<ICommandLineElement>, ISwitchElement> Switch(string key); Parser<IEnumerable<ICommandLineElement>, ISwitchElement> Switches(params string[] keys); Parser<IEnumerable<ICommandLineElement>, IArgumentElement> ValidPath(); } } <|start_filename|>Code/Topshelf/src/Topshelf/Configuration/CommandLineParser/MonadParserExtensions.cs<|end_filename|> // Copyright 2007-2012 <NAME>, <NAME>, <NAME>, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace Topshelf.CommandLineParser { using System; using System.Collections.Generic; using System.Linq; static class MonadParserExtensions { public static Parser<TInput, TValue> Where<TInput, TValue>(this Parser<TInput, TValue> parser, Func<TValue, bool> pred) { return input => { Result<TInput, TValue> result = parser(input); if (result == null || !pred(result.Value)) return null; return result; }; } public static Parser<TInput, TSelect> Select<TInput, TValue, TSelect>(this Parser<TInput, TValue> parser, Func<TValue, TSelect> selector) { return input => { Result<TInput, TValue> result = parser(input); if (result == null) return null; return new Result<TInput, TSelect>(selector(result.Value), result.Rest); }; } public static Parser<TInput, TSelect> SelectMany<TInput, TValue, TIntermediate, TSelect>( this Parser<TInput, TValue> parser, Func<TValue, Parser<TInput, TIntermediate>> selector, Func<TValue, TIntermediate, TSelect> projector) { return input => { Result<TInput, TValue> result = parser(input); if (result == null) return null; TValue val = result.Value; Result<TInput, TIntermediate> nextResult = selector(val)(result.Rest); if (nextResult == null) return null; return new Result<TInput, TSelect>(projector(val, nextResult.Value), nextResult.Rest); }; } public static Parser<TInput, TValue> Or<TInput, TValue>(this Parser<TInput, TValue> first, Parser<TInput, TValue> second) { return input => first(input) ?? second(input); } public static Parser<TInput, TValue> FirstMatch<TInput, TValue>(this IEnumerable<Parser<TInput, TValue>> options) { return input => { return options .Select(option => option(input)) .Where(result => result != null) .FirstOrDefault(); }; } public static Parser<TInput, TSecondValue> And<TInput, TFirstValue, TSecondValue>( this Parser<TInput, TFirstValue> first, Parser<TInput, TSecondValue> second) { return input => second(first(input).Rest); } } } <|start_filename|>Code/Topshelf/src/Topshelf/SessionChangeReasonCode.cs<|end_filename|> // Copyright 2007-2013 <NAME>, <NAME>, <NAME>, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace Topshelf { public enum SessionChangeReasonCode { ConsoleConnect = 1, ConsoleDisconnect = 2, RemoteConnect = 3, RemoteDisconnect = 4, SessionLogon = 5, SessionLogoff = 6, SessionLock = 7, SessionUnlock = 8, SessionRemoteControl = 9, } } <|start_filename|>Code/DotNetZip/Zip Tests/ErrorTests.cs<|end_filename|> // ErrorTests.cs // ------------------------------------------------------------------ // // Copyright (c) 2009-2011 <NAME> . // All rights reserved. // // This code module is part of DotNetZip, a zipfile class library. // // ------------------------------------------------------------------ // // This code is licensed under the Microsoft Public License. // See the file License.txt for the license details. // More info on: http://dotnetzip.codeplex.com // // ------------------------------------------------------------------ // // last saved (in emacs): // Time-stamp: <2011-July-28 12:58:36> // // ------------------------------------------------------------------ // // This module defines some "error tests" - tests that the expected // errors or exceptions occur in DotNetZip under exceptional conditions. // These conditions include corrupted zip files, bad input, and so on. // // ------------------------------------------------------------------ using System; using System.Text; using System.IO; using Microsoft.VisualStudio.TestTools.UnitTesting; //using Ionic.Zip; using Ionic.Zip.Tests.Utilities; namespace Ionic.Zip.Tests.Error { /// <summary> /// Summary description for ErrorTests /// </summary> [TestClass] public class ErrorTests : IonicTestClass { public ErrorTests() : base() { } [TestMethod] [ExpectedException(typeof(FileNotFoundException))] public void Error_AddFile_NonExistentFile() { string zipFileToCreate = Path.Combine(TopLevelDir, "Error_AddFile_NonExistentFile.zip"); using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(zipFileToCreate)) { zip.AddFile("ThisFileDoesNotExist.txt"); zip.Comment = "This is a Comment On the Archive"; zip.Save(); } } [TestMethod] [ExpectedException(typeof(System.ArgumentNullException))] public void Error_Read_NullStream() { System.IO.Stream s = null; using (var zip = ZipFile.Read(s)) { foreach (var e in zip) { Console.WriteLine("entry: {0}", e.FileName); } } } [TestMethod] [ExpectedException(typeof(Ionic.Zip.ZipException))] public void CreateZip_AddDirectory_BlankName() { string zipFileToCreate = Path.Combine(TopLevelDir, "CreateZip_AddDirectory_BlankName.zip"); using (ZipFile zip = new ZipFile(zipFileToCreate)) { zip.AddDirectoryByName(""); zip.Save(); } } [TestMethod] [ExpectedException(typeof(Ionic.Zip.ZipException))] public void CreateZip_AddEntry_String_BlankName() { string zipFileToCreate = Path.Combine(TopLevelDir, "CreateZip_AddEntry_String_BlankName.zip"); using (ZipFile zip = new ZipFile()) { zip.AddEntry("", "This is the content."); zip.Save(zipFileToCreate); } } private void OverwriteDecider(object sender, ExtractProgressEventArgs e) { switch (e.EventType) { case ZipProgressEventType.Extracting_ExtractEntryWouldOverwrite: // randomly choose whether to overwrite or not e.CurrentEntry.ExtractExistingFile = (_rnd.Next(2) == 0) ? ExtractExistingFileAction.DoNotOverwrite : ExtractExistingFileAction.OverwriteSilently; break; } } private void _Internal_ExtractExisting(int flavor) { string zipFileToCreate = Path.Combine(TopLevelDir, String.Format("Error-Extract-ExistingFileWithoutOverwrite-{0}.zip", flavor)); string testBin = TestUtilities.GetTestBinDir(CurrentDir); string resourceDir = Path.Combine(testBin, "Resources"); Assert.IsTrue(Directory.Exists(resourceDir)); Directory.SetCurrentDirectory(TopLevelDir); var filenames = Directory.GetFiles(resourceDir); using (ZipFile zip = new ZipFile(zipFileToCreate)) { zip.AddFiles(filenames, ""); zip.Comment = "This is a Comment On the Archive"; zip.Save(); } Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), filenames.Length, "The zip file created has the wrong number of entries."); // Extract twice: the first time should succeed. // The second, should fail, because of a failed file overwrite. // Unless flavor==3, in which case we overwrite silently. for (int k = 0; k < 2; k++) { using (ZipFile zip = ZipFile.Read(zipFileToCreate)) { if (flavor > 10) zip.ExtractProgress += OverwriteDecider; for (int j = 0; j < filenames.Length; j++) { ZipEntry e = zip[Path.GetFileName(filenames[j])]; if (flavor == 4) e.Extract("unpack"); else e.Extract("unpack", (ExtractExistingFileAction) flavor); } } } } [TestMethod] [ExpectedException(typeof(Ionic.Zip.ZipException))] public void Error_Extract_ExistingFileWithoutOverwrite_Throw() { _Internal_ExtractExisting((int)ExtractExistingFileAction.Throw); } [TestMethod] [ExpectedException(typeof(Ionic.Zip.ZipException))] public void Error_Extract_ExistingFileWithoutOverwrite_NoArg() { _Internal_ExtractExisting(4); } // not an error test [TestMethod] public void Extract_ExistingFileWithOverwrite_OverwriteSilently() { _Internal_ExtractExisting((int)ExtractExistingFileAction.OverwriteSilently); } // not an error test [TestMethod] public void Extract_ExistingFileWithOverwrite_DoNotOverwrite() { _Internal_ExtractExisting((int)ExtractExistingFileAction.DoNotOverwrite); } [TestMethod] [ExpectedException(typeof(Ionic.Zip.ZipException))] public void Error_Extract_ExistingFileWithoutOverwrite_InvokeProgress() { _Internal_ExtractExisting((int)ExtractExistingFileAction.InvokeExtractProgressEvent); } [TestMethod] [ExpectedException(typeof(Ionic.Zip.ZipException))] public void Error_Extract_ExistingFileWithoutOverwrite_InvokeProgress_2() { _Internal_ExtractExisting(10+(int)ExtractExistingFileAction.InvokeExtractProgressEvent); } [TestMethod] [ExpectedException(typeof(Ionic.Zip.ZipException))] public void Error_Extract_ExistingFileWithoutOverwrite_7() { // this is a test of the test! _Internal_ExtractExisting(7); } [TestMethod] public void Error_EmptySplitZip() { string zipFileToCreate = "zftc.zip"; using (var zip = new ZipFile()) { zip.MaxOutputSegmentSize = 1024*1024; zip.Save(zipFileToCreate); } string extractDir = "extract"; using (var zip = ZipFile.Read(zipFileToCreate)) { zip.ExtractAll(extractDir); Assert.IsTrue(zip.Entries.Count == 0); } } [TestMethod] [ExpectedException(typeof(ZipException))] public void Error_Read_InvalidZip() { string filename = zipit; // try reading the invalid zipfile - this must fail. using (ZipFile zip = ZipFile.Read(filename)) { foreach (ZipEntry e in zip) { System.Console.WriteLine("name: {0} compressed: {1} has password?: {2}", e.FileName, e.CompressedSize, e.UsesEncryption); } } } [TestMethod] [ExpectedException(typeof(ZipException))] public void Error_NonZipFile_wi11743() { // try reading an empty, extant file as a zip file string zipFileToRead = Path.GetTempFileName(); _FilesToRemove.Add(zipFileToRead); using (ZipFile zip = new ZipFile(zipFileToRead)) { zip.AddEntry("EntryName1.txt", "This is the content"); zip.Save(); } } private void CreateSmallZip(string zipFileToCreate) { string sourceDir = CurrentDir; for (int i = 0; i < 3; i++) sourceDir = Path.GetDirectoryName(sourceDir); // the list of filenames to add to the zip string[] fileNames = { Path.Combine(sourceDir, "Tools\\Zipit\\bin\\Debug\\Zipit.exe"), Path.Combine(sourceDir, "Zip\\bin\\Debug\\Ionic.Zip.xml"), Path.Combine(sourceDir, "Tools\\WinFormsApp\\Icon2.res"), }; using (ZipFile zip = new ZipFile()) { for (int j = 0; j < fileNames.Length; j++) zip.AddFile(fileNames[j], ""); zip.Save(zipFileToCreate); } Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), fileNames.Length, "Wrong number of entries."); } [TestMethod] [ExpectedException(typeof(ZipException))] public void MalformedZip() { string filePath = Path.GetTempFileName(); _FilesToRemove.Add(filePath); File.WriteAllText( filePath , "asdfasdf" ); string outputDirectory = Path.GetTempPath(); using ( ZipFile zipFile = ZipFile.Read( filePath ) ) { zipFile.ExtractAll( outputDirectory ); } } [TestMethod] [ExpectedException(typeof(InvalidOperationException))] public void Error_UseZipEntryExtractWith_ZIS_wi10355() { string zipFileToCreate = "UseOpenReaderWith_ZIS.zip"; CreateSmallZip(zipFileToCreate); // mixing ZipEntry.Extract and ZipInputStream is a no-no!! string extractDir = "extract"; // Use ZipEntry.Extract with ZipInputStream. // This must fail. TestContext.WriteLine("Reading with ZipInputStream"); using (var zip = new ZipInputStream(zipFileToCreate)) { ZipEntry entry; while ((entry = zip.GetNextEntry()) != null) { entry.Extract(extractDir, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently); } } } [TestMethod] [ExpectedException(typeof(InvalidOperationException))] public void Error_UseOpenReaderWith_ZIS_wi10923() { string zipFileToCreate = "UseOpenReaderWith_ZIS.zip"; CreateSmallZip(zipFileToCreate); // mixing OpenReader and ZipInputStream is a no-no!! int n; var buffer = new byte[2048]; // Use OpenReader with ZipInputStream. // This must fail. TestContext.WriteLine("Reading with ZipInputStream"); using (var zip = new ZipInputStream(zipFileToCreate)) { ZipEntry entry; while ((entry = zip.GetNextEntry()) != null) { TestContext.WriteLine(" Entry: {0}", entry.FileName); using (Stream file = entry.OpenReader()) { while((n= file.Read(buffer,0,buffer.Length)) > 0) ; } TestContext.WriteLine(" -- OpenReader() is done. "); } } } [TestMethod] [ExpectedException(typeof(ZipException))] public void Error_Save_InvalidLocation() { string badLocation = "c:\\Windows\\"; Assert.IsTrue(Directory.Exists(badLocation)); // Add an entry to the zipfile, then try saving to a directory. // This must fail. using (ZipFile zip = new ZipFile()) { zip.AddEntry("This is a file.txt", "Content for the file goes here."); zip.Save(badLocation); // fail } } [TestMethod] public void Error_Save_NonExistentFile() { int j; string repeatedLine; string filename; string zipFileToCreate = Path.Combine(TopLevelDir, "Error_Save_NonExistentFile.zip"); // create the subdirectory string Subdir = Path.Combine(TopLevelDir, "DirToZip"); Directory.CreateDirectory(Subdir); int entriesAdded = 0; // create the files int numFilesToCreate = _rnd.Next(20) + 18; for (j = 0; j < numFilesToCreate; j++) { filename = Path.Combine(Subdir, String.Format("file{0:D3}.txt", j)); repeatedLine = String.Format("This line is repeated over and over and over in file {0}", Path.GetFileName(filename)); TestUtilities.CreateAndFillFileText(filename, repeatedLine, _rnd.Next(1800) + 1500); entriesAdded++; } string tempFileFolder = Path.Combine(TopLevelDir, "Temp"); Directory.CreateDirectory(tempFileFolder); TestContext.WriteLine("Using {0} as the temp file folder....", tempFileFolder); String[] tfiles = Directory.GetFiles(tempFileFolder); int nTemp = tfiles.Length; TestContext.WriteLine("There are {0} files in the temp file folder.", nTemp); String[] filenames = Directory.GetFiles(Subdir); var a1 = System.Reflection.Assembly.GetExecutingAssembly(); String myName = a1.GetName().ToString(); string toDay = System.DateTime.Now.ToString("yyyy-MMM-dd"); try { using (ZipFile zip = new ZipFile(zipFileToCreate)) { zip.TempFileFolder = tempFileFolder; zip.CompressionLevel = Ionic.Zlib.CompressionLevel.None; TestContext.WriteLine("Zipping {0} files...", filenames.Length); int count = 0; foreach (string fn in filenames) { count++; TestContext.WriteLine(" {0}", fn); string file = fn; if (count == filenames.Length - 2) { file += "xx"; TestContext.WriteLine("(Injecting a failure...)"); } zip.UpdateFile(file, myName + '-' + toDay + "_done"); } TestContext.WriteLine("\n"); zip.Save(); TestContext.WriteLine("Zip Completed '{0}'", zipFileToCreate); } } catch (Exception ex) { TestContext.WriteLine("Zip Failed (EXPECTED): {0}", ex.Message); } tfiles = Directory.GetFiles(tempFileFolder); Assert.AreEqual<int>(nTemp, tfiles.Length, "There are unexpected files remaining in the TempFileFolder."); } [TestMethod] [ExpectedException(typeof(Ionic.Zip.BadStateException))] public void Error_Save_NoFilename() { string testBin = TestUtilities.GetTestBinDir(CurrentDir); string resourceDir = Path.Combine(testBin, "Resources"); Directory.SetCurrentDirectory(TopLevelDir); string filename = Path.Combine(resourceDir, "TestStrings.txt"); Assert.IsTrue(File.Exists(filename), String.Format("The file '{0}' doesnot exist.", filename)); // add an entry to the zipfile, then try saving, never having specified a filename. This should fail. using (ZipFile zip = new ZipFile()) { zip.AddFile(filename, ""); zip.Save(); // FAIL: don't know where to save! } // should never reach this Assert.IsTrue(false); } [TestMethod] [ExpectedException(typeof(Ionic.Zip.BadStateException))] public void Error_Extract_WithoutSave() { string testBin = TestUtilities.GetTestBinDir(CurrentDir); string resourceDir = Path.Combine(testBin, "Resources"); Directory.SetCurrentDirectory(TopLevelDir); // add a directory to the zipfile, then try // extracting, without a Save. This should fail. using (ZipFile zip = new ZipFile()) { zip.AddDirectory(resourceDir, ""); Assert.IsTrue(zip.Entries.Count > 0); zip[0].Extract(); // FAIL: has not been saved } // should never reach this Assert.IsTrue(false); } [TestMethod] [ExpectedException(typeof(Ionic.Zip.BadStateException))] public void Error_Read_WithoutSave() { string testBin = TestUtilities.GetTestBinDir(CurrentDir); string resourceDir = Path.Combine(testBin, "Resources"); Directory.SetCurrentDirectory(TopLevelDir); // add a directory to the zipfile, then try // extracting, without a Save. This should fail. using (ZipFile zip = new ZipFile()) { zip.AddDirectory(resourceDir, ""); Assert.IsTrue(zip.Entries.Count > 0); using (var s = zip[0].OpenReader()) // FAIL: has not been saved { byte[] buffer= new byte[1024]; int n; while ((n= s.Read(buffer,0,buffer.Length)) > 0) ; } } // should never reach this Assert.IsTrue(false); } [TestMethod] [ExpectedException(typeof(System.IO.IOException))] public void Error_AddDirectory_SpecifyingFile() { string zipFileToCreate = "AddDirectory_SpecifyingFile.zip"; string filename = "ThisIsAFile"; File.Copy(zipit, filename); string baddirname = Path.Combine(TopLevelDir, filename); using (ZipFile zip = new ZipFile()) { zip.AddDirectory(baddirname); // FAIL zip.Save(zipFileToCreate); } } [TestMethod] [ExpectedException(typeof(FileNotFoundException))] public void Error_AddFile_SpecifyingDirectory() { string zipFileToCreate = "AddFile_SpecifyingDirectory.zip"; string badfilename = "ThisIsADirectory.txt"; Directory.CreateDirectory(badfilename); using (ZipFile zip = new ZipFile()) { zip.AddFile(badfilename); // should fail zip.Save(zipFileToCreate); } } private void IntroduceCorruption(string filename) { // now corrupt the zip archive using (FileStream fs = File.OpenWrite(filename)) { byte[] corruption = new byte[_rnd.Next(100) + 12]; int min = 5; int max = (int)fs.Length - 20; int offsetForCorruption, lengthOfCorruption; int numCorruptions = _rnd.Next(2) + 2; for (int i = 0; i < numCorruptions; i++) { _rnd.NextBytes(corruption); offsetForCorruption = _rnd.Next(min, max); lengthOfCorruption = _rnd.Next(2) + 3; fs.Seek(offsetForCorruption, SeekOrigin.Begin); fs.Write(corruption, 0, lengthOfCorruption); } } } [TestMethod] [ExpectedException(typeof(ZipException))] // not sure which exception - could be one of several. public void Error_ReadCorruptedZipFile_Passwords() { string zipFileToCreate = Path.Combine(TopLevelDir, "Read_CorruptedZipFile_Passwords.zip"); string sourceDir = CurrentDir; for (int i = 0; i < 3; i++) sourceDir = Path.GetDirectoryName(sourceDir); Directory.SetCurrentDirectory(TopLevelDir); // the list of filenames to add to the zip string[] filenames = { Path.Combine(sourceDir, "Tools\\Zipit\\bin\\Debug\\Zipit.exe"), Path.Combine(sourceDir, "Zip\\bin\\Debug\\Ionic.Zip.xml"), Path.Combine(sourceDir, "Tools\\WinFormsApp\\Icon2.res"), }; // passwords to use for those entries string[] passwords = { "<PASSWORD>", "<PASSWORD>", }; // create the zipfile, adding the files int j = 0; using (ZipFile zip = new ZipFile()) { for (j = 0; j < filenames.Length; j++) { zip.Password = passwords[j % passwords.Length]; zip.AddFile(filenames[j], ""); } zip.Save(zipFileToCreate); } IntroduceCorruption(zipFileToCreate); try { // read the corrupted zip - this should fail in some way using (ZipFile zip = ZipFile.Read(zipFileToCreate)) { for (j = 0; j < filenames.Length; j++) { ZipEntry e = zip[Path.GetFileName(filenames[j])]; System.Console.WriteLine("name: {0} compressed: {1} has password?: {2}", e.FileName, e.CompressedSize, e.UsesEncryption); Assert.IsTrue(e.UsesEncryption, "The entry does not use encryption"); e.ExtractWithPassword("unpack", passwords[j % passwords.Length]); } } } catch (Exception exc1) { throw new ZipException("expected", exc1); } } [TestMethod] [ExpectedException(typeof(ZipException))] // not sure which exception - could be one of several. public void Error_ReadCorruptedZipFile() { int i; string zipFileToCreate = Path.Combine(TopLevelDir, "Read_CorruptedZipFile.zip"); string sourceDir = CurrentDir; for (i = 0; i < 3; i++) sourceDir = Path.GetDirectoryName(sourceDir); Directory.SetCurrentDirectory(TopLevelDir); // the list of filenames to add to the zip string[] filenames = { Path.Combine(sourceDir, "Tools\\Zipit\\bin\\Debug\\Zipit.exe"), Path.Combine(sourceDir, "Tools\\Unzip\\bin\\Debug\\Unzip.exe"), Path.Combine(sourceDir, "Zip\\bin\\Debug\\Ionic.Zip.xml"), Path.Combine(sourceDir, "Tools\\WinFormsApp\\Icon2.res"), }; // create the zipfile, adding the files using (ZipFile zip = new ZipFile()) { for (i = 0; i < filenames.Length; i++) zip.AddFile(filenames[i], ""); zip.Save(zipFileToCreate); } // now corrupt the zip archive IntroduceCorruption(zipFileToCreate); try { // read the corrupted zip - this should fail in some way using (ZipFile zip = new ZipFile(zipFileToCreate)) { foreach (var e in zip) { System.Console.WriteLine("name: {0} compressed: {1} has password?: {2}", e.FileName, e.CompressedSize, e.UsesEncryption); e.Extract("extract"); } } } catch (Exception exc1) { throw new ZipException("expected", exc1); } } [TestMethod] public void Error_LockedFile_wi13903() { TestContext.WriteLine("==Error_LockedFile_wi13903()"); string fname = Path.GetRandomFileName(); TestContext.WriteLine("create file {0}", fname); TestUtilities.CreateAndFillFileText(fname, _rnd.Next(10000) + 5000); string zipFileToCreate = "wi13903.zip"; var zipErrorHandler = new EventHandler<ZipErrorEventArgs>( (sender, e) => { TestContext.WriteLine("Error reading entry {0}", e.CurrentEntry); TestContext.WriteLine(" (this was expected)"); e.CurrentEntry.ZipErrorAction = ZipErrorAction.Skip; }); // lock the file TestContext.WriteLine("lock file {0}", fname); using (var s = System.IO.File.Open(fname, FileMode.Open, FileAccess.Read, FileShare.None)) { using (var rawOut = File.Create(zipFileToCreate)) { using (var nonSeekableOut = new Ionic.Zip.Tests.NonSeekableOutputStream(rawOut)) { TestContext.WriteLine("create zip file {0}", zipFileToCreate); using (var zip = new ZipFile()) { zip.ZipError += zipErrorHandler; zip.AddFile(fname); // should trigger a read error, // which should be skipped. Result will be // a zero-entry zip file. zip.Save(nonSeekableOut); } } } } TestContext.WriteLine("all done, A-OK"); } [TestMethod] [ExpectedException(typeof(ZipException))] public void Error_Read_EmptyZipFile() { string zipFileToRead = Path.Combine(TopLevelDir, "Read_BadFile.zip"); string newFile = Path.GetTempFileName(); _FilesToRemove.Add(newFile); File.Move(newFile, zipFileToRead); newFile = Path.GetTempFileName(); _FilesToRemove.Add(newFile); string fileToAdd = Path.Combine(TopLevelDir, "EmptyFile.txt"); File.Move(newFile, fileToAdd); try { using (ZipFile zip = ZipFile.Read(zipFileToRead)) { zip.AddFile(fileToAdd, ""); zip.Save(); } } catch (System.Exception exc1) { throw new ZipException("expected", exc1); } } [TestMethod] [ExpectedException(typeof(System.ArgumentException))] public void Error_AddFile_Twice() { int i; // select the name of the zip file string zipFileToCreate = Path.Combine(TopLevelDir, "Error_AddFile_Twice.zip"); // create the subdirectory string subdir = Path.Combine(TopLevelDir, "files"); Directory.CreateDirectory(subdir); // create a bunch of files int numFilesToCreate = _rnd.Next(23) + 14; for (i = 0; i < numFilesToCreate; i++) TestUtilities.CreateUniqueFile("bin", subdir, _rnd.Next(10000) + 5000); // Create the zip archive Directory.SetCurrentDirectory(TopLevelDir); using (ZipFile zip1 = new ZipFile(zipFileToCreate)) { zip1.StatusMessageTextWriter = System.Console.Out; string[] files = Directory.GetFiles(subdir); zip1.AddFiles(files, "files"); zip1.Save(); } // this should fail - adding the same file twice using (ZipFile zip2 = new ZipFile(zipFileToCreate)) { zip2.StatusMessageTextWriter = System.Console.Out; string[] files = Directory.GetFiles(subdir); for (i = 0; i < files.Length; i++) zip2.AddFile(files[i], "files"); zip2.Save(); } } [TestMethod] [ExpectedException(typeof(Ionic.Zip.ZipException))] public void Error_FileNotAvailableFails() { // verify the correct exception is being thrown string zipFileToCreate = Path.Combine(TopLevelDir, "Error_FileNotAvailableFails.zip"); // create a zip file with no entries using (var zipfile = new ZipFile(zipFileToCreate)) { zipfile.Save(); } // open and lock using (new FileStream(zipFileToCreate, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)) { using (new ZipFile(zipFileToCreate)) { } } } [TestMethod] [ExpectedException(typeof(ZipException))] public void IncorrectZipContentTest1_wi10459() { byte[] content = Encoding.UTF8.GetBytes("wrong zipfile content"); using (var ms = new MemoryStream(content)) { using (var zipFile = ZipFile.Read(ms)) { } } } [TestMethod] [ExpectedException(typeof(ZipException))] public void IncorrectZipContentTest2_wi10459() { using (var ms = new MemoryStream()) { using (var zipFile = ZipFile.Read(ms)) { } } } [TestMethod] [ExpectedException(typeof(ZipException))] public void IncorrectZipContentTest3_wi10459() { byte[] content = new byte[8192]; using (var ms = new MemoryStream(content)) { using (var zipFile = ZipFile.Read(ms)) { } } } } } <|start_filename|>Code/Topshelf/src/Topshelf/Configuration/InstallHostConfiguratorExtensions.cs<|end_filename|> // Copyright 2007-2012 <NAME>, <NAME>, <NAME>, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace Topshelf { using System; using HostConfigurators; using Runtime; public static class InstallHostConfiguratorExtensions { public static HostConfigurator BeforeInstall(this HostConfigurator configurator, Action callback) { if (configurator == null) throw new ArgumentNullException("configurator"); configurator.AddConfigurator(new InstallHostConfiguratorAction("BeforeInstall", x => x.BeforeInstall(settings => callback()))); return configurator; } public static HostConfigurator BeforeInstall(this HostConfigurator configurator, Action<InstallHostSettings> callback) { if (configurator == null) throw new ArgumentNullException("configurator"); configurator.AddConfigurator(new InstallHostConfiguratorAction("BeforeInstall", x => x.BeforeInstall(callback))); return configurator; } public static HostConfigurator AfterInstall(this HostConfigurator configurator, Action callback) { if (configurator == null) throw new ArgumentNullException("configurator"); configurator.AddConfigurator(new InstallHostConfiguratorAction("AfterInstall", x => x.AfterInstall(settings => callback()))); return configurator; } public static HostConfigurator AfterInstall(this HostConfigurator configurator, Action<InstallHostSettings> callback) { if (configurator == null) throw new ArgumentNullException("configurator"); configurator.AddConfigurator(new InstallHostConfiguratorAction("AfterInstall", x => x.AfterInstall(callback))); return configurator; } public static HostConfigurator BeforeRollback(this HostConfigurator configurator, Action callback) { if (configurator == null) throw new ArgumentNullException("configurator"); configurator.AddConfigurator(new InstallHostConfiguratorAction("BeforeRollback", x => x.BeforeRollback(settings => callback()))); return configurator; } public static HostConfigurator BeforeRollback(this HostConfigurator configurator, Action<InstallHostSettings> callback) { if (configurator == null) throw new ArgumentNullException("configurator"); configurator.AddConfigurator(new InstallHostConfiguratorAction("BeforeRollback", x => x.BeforeRollback(callback))); return configurator; } public static HostConfigurator AfterRollback(this HostConfigurator configurator, Action callback) { if (configurator == null) throw new ArgumentNullException("configurator"); configurator.AddConfigurator(new InstallHostConfiguratorAction("AfterRollback", x => x.AfterRollback(settings => callback()))); return configurator; } public static HostConfigurator AfterRollback(this HostConfigurator configurator, Action<InstallHostSettings> callback) { if (configurator == null) throw new ArgumentNullException("configurator"); configurator.AddConfigurator(new InstallHostConfiguratorAction("AfterRollback", x => x.AfterRollback(callback))); return configurator; } } } <|start_filename|>Code/Topshelf/src/Topshelf/Configuration/ServiceRecoveryConfigurator.cs<|end_filename|> // Copyright 2007-2012 <NAME>, <NAME>, <NAME>, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace Topshelf { public interface ServiceRecoveryConfigurator { /// <summary> /// Restart the service after waiting the delay period specified /// </summary> /// <param name="delayInMinutes"> </param> ServiceRecoveryConfigurator RestartService(int delayInMinutes); /// <summary> /// Restart the computer after waiting the delay period in minutes /// </summary> /// <param name="delayInMinutes"> </param> /// <param name="message"> </param> ServiceRecoveryConfigurator RestartComputer(int delayInMinutes, string message); /// <summary> /// Run the command specified /// </summary> /// <param name="delayInMinutes"> </param> /// <param name="command"> </param> ServiceRecoveryConfigurator RunProgram(int delayInMinutes, string command); /// <summary> /// Specifies the reset period for the restart options /// </summary> /// <param name="days"> </param> ServiceRecoveryConfigurator SetResetPeriod(int days); /// <summary> /// Specifies that the recovery actions should only be taken on a service crash. If the service exists /// with a non-zero exit code, it will not be restarted. /// </summary> void OnCrashOnly(); } } <|start_filename|>Code/Topshelf/src/Topshelf/Configuration/ServiceExtensions.cs<|end_filename|> // Copyright 2007-2012 <NAME>, <NAME>, <NAME>, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace Topshelf { using System; using System.Linq; using Builders; using Configurators; using HostConfigurators; using Runtime; using ServiceConfigurators; public static class ServiceExtensions { public static HostConfigurator Service<TService>(this HostConfigurator configurator, Func<HostSettings, TService> serviceFactory, Action<ServiceConfigurator> callback) where TService : class, ServiceControl { if (configurator == null) throw new ArgumentNullException("configurator"); ServiceBuilderFactory serviceBuilderFactory = CreateServiceBuilderFactory(serviceFactory, callback); configurator.UseServiceBuilder(serviceBuilderFactory); return configurator; } public static ServiceBuilderFactory CreateServiceBuilderFactory<TService>( Func<HostSettings, TService> serviceFactory, Action<ServiceConfigurator> callback) where TService : class, ServiceControl { if (serviceFactory == null) throw new ArgumentNullException("serviceFactory"); if (callback == null) throw new ArgumentNullException("callback"); var serviceConfigurator = new ControlServiceConfigurator<TService>(serviceFactory); callback(serviceConfigurator); ServiceBuilderFactory serviceBuilderFactory = x => { ConfigurationResult configurationResult = ValidateConfigurationResult.CompileResults(serviceConfigurator.Validate()); if (configurationResult.Results.Any()) throw new HostConfigurationException("The service was not properly configured"); ServiceBuilder serviceBuilder = serviceConfigurator.Build(); return serviceBuilder; }; return serviceBuilderFactory; } public static HostConfigurator Service<T>(this HostConfigurator configurator) where T : class, ServiceControl, new() { return Service(configurator, x => new T(), x => { }); } public static HostConfigurator Service<T>(this HostConfigurator configurator, Func<T> serviceFactory) where T : class, ServiceControl { return Service(configurator, x => serviceFactory(), x => { }); } public static HostConfigurator Service<T>(this HostConfigurator configurator, Func<T> serviceFactory, Action<ServiceConfigurator> callback) where T : class, ServiceControl { return Service(configurator, x => serviceFactory(), callback); } public static HostConfigurator Service<T>(this HostConfigurator configurator, Func<HostSettings, T> serviceFactory) where T : class, ServiceControl { return Service(configurator, serviceFactory, x => { }); } public static HostConfigurator Service<TService>(this HostConfigurator configurator, Action<ServiceConfigurator<TService>> callback) where TService : class { if (configurator == null) throw new ArgumentNullException("configurator"); ServiceBuilderFactory serviceBuilderFactory = CreateServiceBuilderFactory(callback); configurator.UseServiceBuilder(serviceBuilderFactory); return configurator; } public static ServiceBuilderFactory CreateServiceBuilderFactory<TService>(Action<ServiceConfigurator<TService>> callback) where TService : class { if (callback == null) throw new ArgumentNullException("callback"); var serviceConfigurator = new DelegateServiceConfigurator<TService>(); callback(serviceConfigurator); ServiceBuilderFactory serviceBuilderFactory = x => { ConfigurationResult configurationResult = ValidateConfigurationResult.CompileResults(serviceConfigurator.Validate()); if (configurationResult.Results.Any()) throw new HostConfigurationException("The service was not properly configured"); ServiceBuilder serviceBuilder = serviceConfigurator.Build(); return serviceBuilder; }; return serviceBuilderFactory; } } } <|start_filename|>Code/Topshelf/src/Topshelf/Configuration/HostConfigurators/PrefixHelpTextHostConfigurator.cs<|end_filename|> // Copyright 2007-2013 <NAME>, <NAME>, <NAME>, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace Topshelf.HostConfigurators { using System; using System.Collections.Generic; using System.IO; using System.Reflection; using Builders; using Configurators; public class PrefixHelpTextHostConfigurator : HostBuilderConfigurator { public PrefixHelpTextHostConfigurator(Assembly assembly, string resourceName) { Assembly = assembly; ResourceName = resourceName; } public PrefixHelpTextHostConfigurator(string text) { Text = text; } public Assembly Assembly { get; private set; } public string ResourceName { get; private set; } public string Text { get; private set; } public IEnumerable<ValidateResult> Validate() { ValidateResult loadResult = null; if (Assembly != null) { if (ResourceName == null) yield return this.Failure("A resource name must be specified"); try { Stream stream = Assembly.GetManifestResourceStream(ResourceName); if (stream == null) loadResult = this.Failure("Resource", "Unable to load resource stream: " + ResourceName); else { using (TextReader reader = new StreamReader(stream)) { Text = reader.ReadToEnd(); } } } catch (Exception ex) { loadResult = this.Failure("Failed to load help source: " + ex.Message); } if (loadResult != null) yield return loadResult; } if (Text == null) yield return this.Failure("No additional help text was specified"); } public HostBuilder Configure(HostBuilder builder) { builder.Match<HelpBuilder>(x => x.SetAdditionalHelpText(Text)); return builder; } } } <|start_filename|>Code/Topshelf/src/Topshelf/Configuration/ServiceEventConfiguratorExtensions.cs<|end_filename|> // Copyright 2007-2012 <NAME>, <NAME>, <NAME>, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace Topshelf { using System; using ServiceConfigurators; public static class ServiceEventConfiguratorExtensions { /// <summary> /// Registers a callback invoked before the service Start method is called. /// </summary> public static T BeforeStartingService<T>(this T configurator, Action callback) where T : ServiceConfigurator { if (configurator == null) throw new ArgumentNullException("configurator"); configurator.BeforeStartingService(x => callback()); return configurator; } /// <summary> /// Registers a callback invoked after the service Start method is called. /// </summary> public static T AfterStartingService<T>(this T configurator, Action callback) where T : ServiceConfigurator { if (configurator == null) throw new ArgumentNullException("configurator"); configurator.AfterStartingService(x => callback()); return configurator; } /// <summary> /// Registers a callback invoked before the service Stop method is called. /// </summary> public static T BeforeStoppingService<T>(this T configurator, Action callback) where T : ServiceConfigurator { if (configurator == null) throw new ArgumentNullException("configurator"); configurator.BeforeStoppingService(x => callback()); return configurator; } /// <summary> /// Registers a callback invoked after the service Stop method is called. /// </summary> public static T AfterStoppingService<T>(this T configurator, Action callback) where T : ServiceConfigurator { if (configurator == null) throw new ArgumentNullException("configurator"); configurator.AfterStoppingService(x => callback()); return configurator; } } } <|start_filename|>Code/QuartzNetManager/ClickForensics.Quartz.Manager/JobNode.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using Quartz; using Quartz.Impl; namespace ClickForensics.Quartz.Manager { public class JobNode : TreeNode { public JobNode(IJobDetail jobDetail) : base() { this.Text = jobDetail.Key.Name; Detail = jobDetail; } public IJobDetail Detail { get; private set; } } } <|start_filename|>Code/Topshelf/src/Topshelf/Hosts/HelpHost.cs<|end_filename|> // Copyright 2007-2012 <NAME>, <NAME>, <NAME>, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace Topshelf.Hosts { using System; using System.IO; /// <summary> /// Displays the Topshelf command line reference /// </summary> public class HelpHost : Host { readonly string _prefixText; public HelpHost(string prefixText) { _prefixText = prefixText; } public string PrefixText { get { return _prefixText; } } public TopshelfExitCode Run() { if (!string.IsNullOrEmpty(_prefixText)) Console.WriteLine(_prefixText); const string helpText = "Topshelf.HelpText.txt"; Stream stream = typeof(HelpHost).Assembly.GetManifestResourceStream(helpText); if (stream == null) { Console.WriteLine("Unable to load help text"); return TopshelfExitCode.AbnormalExit; } using (TextReader reader = new StreamReader(stream)) { string text = reader.ReadToEnd(); Console.WriteLine(text); } return TopshelfExitCode.Ok; } } }
TrevorDArcyEvans/EllieWare
<|start_filename|>test/api_test.dart<|end_filename|> // Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. // Tests that Win32 API prototypes can be successfully loaded (i.e. that // lookupFunction works for all the APIs generated) // THIS FILE IS GENERATED AUTOMATICALLY AND SHOULD NOT BE EDITED DIRECTLY. @TestOn('windows') import 'dart:ffi'; import 'package:ffi/ffi.dart'; import 'package:test/test.dart'; import 'package:win32/win32.dart'; import 'package:win32/winsock2.dart'; import 'helpers.dart'; void main() { final windowsBuildNumber = getWindowsBuildNumber(); group('Test gdi32 functions', () { test('Can instantiate AbortPath', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final AbortPath = gdi32.lookupFunction<Int32 Function(IntPtr hdc), int Function(int hdc)>('AbortPath'); expect(AbortPath, isA<Function>()); }); test('Can instantiate AddFontResource', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final AddFontResource = gdi32.lookupFunction< Int32 Function(Pointer<Utf16> param0), int Function(Pointer<Utf16> param0)>('AddFontResourceW'); expect(AddFontResource, isA<Function>()); }); test('Can instantiate AddFontResourceEx', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final AddFontResourceEx = gdi32.lookupFunction< Int32 Function(Pointer<Utf16> name, Uint32 fl, Pointer res), int Function( Pointer<Utf16> name, int fl, Pointer res)>('AddFontResourceExW'); expect(AddFontResourceEx, isA<Function>()); }); test('Can instantiate AngleArc', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final AngleArc = gdi32.lookupFunction< Int32 Function(IntPtr hdc, Int32 x, Int32 y, Uint32 r, Float StartAngle, Float SweepAngle), int Function(int hdc, int x, int y, int r, double StartAngle, double SweepAngle)>('AngleArc'); expect(AngleArc, isA<Function>()); }); test('Can instantiate AnimatePalette', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final AnimatePalette = gdi32.lookupFunction< Int32 Function(IntPtr hPal, Uint32 iStartIndex, Uint32 cEntries, Pointer<PALETTEENTRY> ppe), int Function(int hPal, int iStartIndex, int cEntries, Pointer<PALETTEENTRY> ppe)>('AnimatePalette'); expect(AnimatePalette, isA<Function>()); }); test('Can instantiate Arc', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final Arc = gdi32.lookupFunction< Int32 Function(IntPtr hdc, Int32 x1, Int32 y1, Int32 x2, Int32 y2, Int32 x3, Int32 y3, Int32 x4, Int32 y4), int Function(int hdc, int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4)>('Arc'); expect(Arc, isA<Function>()); }); test('Can instantiate ArcTo', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final ArcTo = gdi32.lookupFunction< Int32 Function(IntPtr hdc, Int32 left, Int32 top, Int32 right, Int32 bottom, Int32 xr1, Int32 yr1, Int32 xr2, Int32 yr2), int Function(int hdc, int left, int top, int right, int bottom, int xr1, int yr1, int xr2, int yr2)>('ArcTo'); expect(ArcTo, isA<Function>()); }); test('Can instantiate BeginPath', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final BeginPath = gdi32.lookupFunction<Int32 Function(IntPtr hdc), int Function(int hdc)>('BeginPath'); expect(BeginPath, isA<Function>()); }); test('Can instantiate BitBlt', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final BitBlt = gdi32.lookupFunction< Int32 Function(IntPtr hdc, Int32 x, Int32 y, Int32 cx, Int32 cy, IntPtr hdcSrc, Int32 x1, Int32 y1, Uint32 rop), int Function(int hdc, int x, int y, int cx, int cy, int hdcSrc, int x1, int y1, int rop)>('BitBlt'); expect(BitBlt, isA<Function>()); }); test('Can instantiate CancelDC', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final CancelDC = gdi32.lookupFunction<Int32 Function(IntPtr hdc), int Function(int hdc)>('CancelDC'); expect(CancelDC, isA<Function>()); }); test('Can instantiate Chord', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final Chord = gdi32.lookupFunction< Int32 Function(IntPtr hdc, Int32 x1, Int32 y1, Int32 x2, Int32 y2, Int32 x3, Int32 y3, Int32 x4, Int32 y4), int Function(int hdc, int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4)>('Chord'); expect(Chord, isA<Function>()); }); test('Can instantiate CloseFigure', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final CloseFigure = gdi32.lookupFunction<Int32 Function(IntPtr hdc), int Function(int hdc)>('CloseFigure'); expect(CloseFigure, isA<Function>()); }); test('Can instantiate CreateCompatibleBitmap', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final CreateCompatibleBitmap = gdi32.lookupFunction< IntPtr Function(IntPtr hdc, Int32 cx, Int32 cy), int Function(int hdc, int cx, int cy)>('CreateCompatibleBitmap'); expect(CreateCompatibleBitmap, isA<Function>()); }); test('Can instantiate CreateCompatibleDC', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final CreateCompatibleDC = gdi32.lookupFunction< IntPtr Function(IntPtr hdc), int Function(int hdc)>('CreateCompatibleDC'); expect(CreateCompatibleDC, isA<Function>()); }); test('Can instantiate CreateDC', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final CreateDC = gdi32.lookupFunction< IntPtr Function(Pointer<Utf16> pwszDriver, Pointer<Utf16> pwszDevice, Pointer<Utf16> pszPort, Pointer<DEVMODE> pdm), int Function(Pointer<Utf16> pwszDriver, Pointer<Utf16> pwszDevice, Pointer<Utf16> pszPort, Pointer<DEVMODE> pdm)>('CreateDCW'); expect(CreateDC, isA<Function>()); }); test('Can instantiate CreateDIBitmap', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final CreateDIBitmap = gdi32.lookupFunction< IntPtr Function( IntPtr hdc, Pointer<BITMAPINFOHEADER> pbmih, Uint32 flInit, Pointer pjBits, Pointer<BITMAPINFO> pbmi, Uint32 iUsage), int Function( int hdc, Pointer<BITMAPINFOHEADER> pbmih, int flInit, Pointer pjBits, Pointer<BITMAPINFO> pbmi, int iUsage)>('CreateDIBitmap'); expect(CreateDIBitmap, isA<Function>()); }); test('Can instantiate CreateDIBPatternBrushPt', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final CreateDIBPatternBrushPt = gdi32.lookupFunction< IntPtr Function(Pointer lpPackedDIB, Uint32 iUsage), int Function( Pointer lpPackedDIB, int iUsage)>('CreateDIBPatternBrushPt'); expect(CreateDIBPatternBrushPt, isA<Function>()); }); test('Can instantiate CreateDIBSection', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final CreateDIBSection = gdi32.lookupFunction< IntPtr Function(IntPtr hdc, Pointer<BITMAPINFO> pbmi, Uint32 usage, Pointer<Pointer> ppvBits, IntPtr hSection, Uint32 offset), int Function( int hdc, Pointer<BITMAPINFO> pbmi, int usage, Pointer<Pointer> ppvBits, int hSection, int offset)>('CreateDIBSection'); expect(CreateDIBSection, isA<Function>()); }); test('Can instantiate CreateEllipticRgn', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final CreateEllipticRgn = gdi32.lookupFunction< IntPtr Function(Int32 x1, Int32 y1, Int32 x2, Int32 y2), int Function(int x1, int y1, int x2, int y2)>('CreateEllipticRgn'); expect(CreateEllipticRgn, isA<Function>()); }); test('Can instantiate CreateFontIndirect', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final CreateFontIndirect = gdi32.lookupFunction< IntPtr Function(Pointer<LOGFONT> lplf), int Function(Pointer<LOGFONT> lplf)>('CreateFontIndirectW'); expect(CreateFontIndirect, isA<Function>()); }); test('Can instantiate CreateHalftonePalette', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final CreateHalftonePalette = gdi32.lookupFunction< IntPtr Function(IntPtr hdc), int Function(int hdc)>('CreateHalftonePalette'); expect(CreateHalftonePalette, isA<Function>()); }); test('Can instantiate CreateHatchBrush', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final CreateHatchBrush = gdi32.lookupFunction< IntPtr Function(Uint32 iHatch, Uint32 color), int Function(int iHatch, int color)>('CreateHatchBrush'); expect(CreateHatchBrush, isA<Function>()); }); test('Can instantiate CreatePen', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final CreatePen = gdi32.lookupFunction< IntPtr Function(Uint32 iStyle, Int32 cWidth, Uint32 color), int Function(int iStyle, int cWidth, int color)>('CreatePen'); expect(CreatePen, isA<Function>()); }); test('Can instantiate CreateSolidBrush', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final CreateSolidBrush = gdi32.lookupFunction< IntPtr Function(Uint32 color), int Function(int color)>('CreateSolidBrush'); expect(CreateSolidBrush, isA<Function>()); }); test('Can instantiate DeleteDC', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final DeleteDC = gdi32.lookupFunction<Int32 Function(IntPtr hdc), int Function(int hdc)>('DeleteDC'); expect(DeleteDC, isA<Function>()); }); test('Can instantiate DeleteObject', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final DeleteObject = gdi32.lookupFunction<Int32 Function(IntPtr ho), int Function(int ho)>( 'DeleteObject'); expect(DeleteObject, isA<Function>()); }); test('Can instantiate DrawEscape', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final DrawEscape = gdi32.lookupFunction< Int32 Function( IntPtr hdc, Int32 iEscape, Int32 cjIn, Pointer<Utf8> lpIn), int Function(int hdc, int iEscape, int cjIn, Pointer<Utf8> lpIn)>('DrawEscape'); expect(DrawEscape, isA<Function>()); }); test('Can instantiate Ellipse', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final Ellipse = gdi32.lookupFunction< Int32 Function( IntPtr hdc, Int32 left, Int32 top, Int32 right, Int32 bottom), int Function( int hdc, int left, int top, int right, int bottom)>('Ellipse'); expect(Ellipse, isA<Function>()); }); test('Can instantiate EndPath', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final EndPath = gdi32.lookupFunction<Int32 Function(IntPtr hdc), int Function(int hdc)>('EndPath'); expect(EndPath, isA<Function>()); }); test('Can instantiate EnumFontFamiliesEx', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final EnumFontFamiliesEx = gdi32.lookupFunction< Int32 Function( IntPtr hdc, Pointer<LOGFONT> lpLogfont, Pointer<NativeFunction<EnumFontFamExProc>> lpProc, IntPtr lParam, Uint32 dwFlags), int Function( int hdc, Pointer<LOGFONT> lpLogfont, Pointer<NativeFunction<EnumFontFamExProc>> lpProc, int lParam, int dwFlags)>('EnumFontFamiliesExW'); expect(EnumFontFamiliesEx, isA<Function>()); }); test('Can instantiate ExtCreatePen', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final ExtCreatePen = gdi32.lookupFunction< IntPtr Function(Uint32 iPenStyle, Uint32 cWidth, Pointer<LOGBRUSH> plbrush, Uint32 cStyle, Pointer<Uint32> pstyle), int Function(int iPenStyle, int cWidth, Pointer<LOGBRUSH> plbrush, int cStyle, Pointer<Uint32> pstyle)>('ExtCreatePen'); expect(ExtCreatePen, isA<Function>()); }); test('Can instantiate ExtTextOut', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final ExtTextOut = gdi32.lookupFunction< Int32 Function( IntPtr hdc, Int32 x, Int32 y, Uint32 options, Pointer<RECT> lprect, Pointer<Utf16> lpString, Uint32 c, Pointer<Int32> lpDx), int Function( int hdc, int x, int y, int options, Pointer<RECT> lprect, Pointer<Utf16> lpString, int c, Pointer<Int32> lpDx)>('ExtTextOutW'); expect(ExtTextOut, isA<Function>()); }); test('Can instantiate FillPath', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final FillPath = gdi32.lookupFunction<Int32 Function(IntPtr hdc), int Function(int hdc)>('FillPath'); expect(FillPath, isA<Function>()); }); test('Can instantiate FlattenPath', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final FlattenPath = gdi32.lookupFunction<Int32 Function(IntPtr hdc), int Function(int hdc)>('FlattenPath'); expect(FlattenPath, isA<Function>()); }); test('Can instantiate GetDeviceCaps', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final GetDeviceCaps = gdi32.lookupFunction< Int32 Function(IntPtr hdc, Uint32 index), int Function(int hdc, int index)>('GetDeviceCaps'); expect(GetDeviceCaps, isA<Function>()); }); test('Can instantiate GetDIBits', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final GetDIBits = gdi32.lookupFunction< Int32 Function(IntPtr hdc, IntPtr hbm, Uint32 start, Uint32 cLines, Pointer lpvBits, Pointer<BITMAPINFO> lpbmi, Uint32 usage), int Function(int hdc, int hbm, int start, int cLines, Pointer lpvBits, Pointer<BITMAPINFO> lpbmi, int usage)>('GetDIBits'); expect(GetDIBits, isA<Function>()); }); test('Can instantiate GetNearestColor', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final GetNearestColor = gdi32.lookupFunction< Uint32 Function(IntPtr hdc, Uint32 color), int Function(int hdc, int color)>('GetNearestColor'); expect(GetNearestColor, isA<Function>()); }); test('Can instantiate GetObject', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final GetObject = gdi32.lookupFunction< Int32 Function(IntPtr h, Int32 c, Pointer pv), int Function(int h, int c, Pointer pv)>('GetObjectW'); expect(GetObject, isA<Function>()); }); test('Can instantiate GetPath', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final GetPath = gdi32.lookupFunction< Int32 Function( IntPtr hdc, Pointer<POINT> apt, Pointer<Uint8> aj, Int32 cpt), int Function(int hdc, Pointer<POINT> apt, Pointer<Uint8> aj, int cpt)>('GetPath'); expect(GetPath, isA<Function>()); }); test('Can instantiate GetStockObject', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final GetStockObject = gdi32.lookupFunction<IntPtr Function(Uint32 i), int Function(int i)>( 'GetStockObject'); expect(GetStockObject, isA<Function>()); }); test('Can instantiate GetTextMetrics', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final GetTextMetrics = gdi32.lookupFunction< Int32 Function(IntPtr hdc, Pointer<TEXTMETRIC> lptm), int Function(int hdc, Pointer<TEXTMETRIC> lptm)>('GetTextMetricsW'); expect(GetTextMetrics, isA<Function>()); }); test('Can instantiate LineTo', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final LineTo = gdi32.lookupFunction< Int32 Function(IntPtr hdc, Int32 x, Int32 y), int Function(int hdc, int x, int y)>('LineTo'); expect(LineTo, isA<Function>()); }); test('Can instantiate MoveToEx', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final MoveToEx = gdi32.lookupFunction< Int32 Function(IntPtr hdc, Int32 x, Int32 y, Pointer<POINT> lppt), int Function(int hdc, int x, int y, Pointer<POINT> lppt)>('MoveToEx'); expect(MoveToEx, isA<Function>()); }); test('Can instantiate Pie', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final Pie = gdi32.lookupFunction< Int32 Function(IntPtr hdc, Int32 left, Int32 top, Int32 right, Int32 bottom, Int32 xr1, Int32 yr1, Int32 xr2, Int32 yr2), int Function(int hdc, int left, int top, int right, int bottom, int xr1, int yr1, int xr2, int yr2)>('Pie'); expect(Pie, isA<Function>()); }); test('Can instantiate PolyBezier', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final PolyBezier = gdi32.lookupFunction< Int32 Function(IntPtr hdc, Pointer<POINT> apt, Uint32 cpt), int Function(int hdc, Pointer<POINT> apt, int cpt)>('PolyBezier'); expect(PolyBezier, isA<Function>()); }); test('Can instantiate PolyBezierTo', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final PolyBezierTo = gdi32.lookupFunction< Int32 Function(IntPtr hdc, Pointer<POINT> apt, Uint32 cpt), int Function(int hdc, Pointer<POINT> apt, int cpt)>('PolyBezierTo'); expect(PolyBezierTo, isA<Function>()); }); test('Can instantiate PolyDraw', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final PolyDraw = gdi32.lookupFunction< Int32 Function( IntPtr hdc, Pointer<POINT> apt, Pointer<Uint8> aj, Int32 cpt), int Function(int hdc, Pointer<POINT> apt, Pointer<Uint8> aj, int cpt)>('PolyDraw'); expect(PolyDraw, isA<Function>()); }); test('Can instantiate Polygon', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final Polygon = gdi32.lookupFunction< Int32 Function(IntPtr hdc, Pointer<POINT> apt, Int32 cpt), int Function(int hdc, Pointer<POINT> apt, int cpt)>('Polygon'); expect(Polygon, isA<Function>()); }); test('Can instantiate Polyline', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final Polyline = gdi32.lookupFunction< Int32 Function(IntPtr hdc, Pointer<POINT> apt, Int32 cpt), int Function(int hdc, Pointer<POINT> apt, int cpt)>('Polyline'); expect(Polyline, isA<Function>()); }); test('Can instantiate PolylineTo', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final PolylineTo = gdi32.lookupFunction< Int32 Function(IntPtr hdc, Pointer<POINT> apt, Uint32 cpt), int Function(int hdc, Pointer<POINT> apt, int cpt)>('PolylineTo'); expect(PolylineTo, isA<Function>()); }); test('Can instantiate PolyPolygon', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final PolyPolygon = gdi32.lookupFunction< Int32 Function( IntPtr hdc, Pointer<POINT> apt, Pointer<Int32> asz, Int32 csz), int Function(int hdc, Pointer<POINT> apt, Pointer<Int32> asz, int csz)>('PolyPolygon'); expect(PolyPolygon, isA<Function>()); }); test('Can instantiate PolyPolyline', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final PolyPolyline = gdi32.lookupFunction< Int32 Function( IntPtr hdc, Pointer<POINT> apt, Pointer<Uint32> asz, Uint32 csz), int Function(int hdc, Pointer<POINT> apt, Pointer<Uint32> asz, int csz)>('PolyPolyline'); expect(PolyPolyline, isA<Function>()); }); test('Can instantiate PtInRegion', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final PtInRegion = gdi32.lookupFunction< Int32 Function(IntPtr hrgn, Int32 x, Int32 y), int Function(int hrgn, int x, int y)>('PtInRegion'); expect(PtInRegion, isA<Function>()); }); test('Can instantiate Rectangle', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final Rectangle = gdi32.lookupFunction< Int32 Function( IntPtr hdc, Int32 left, Int32 top, Int32 right, Int32 bottom), int Function( int hdc, int left, int top, int right, int bottom)>('Rectangle'); expect(Rectangle, isA<Function>()); }); test('Can instantiate RectInRegion', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final RectInRegion = gdi32.lookupFunction< Int32 Function(IntPtr hrgn, Pointer<RECT> lprect), int Function(int hrgn, Pointer<RECT> lprect)>('RectInRegion'); expect(RectInRegion, isA<Function>()); }); test('Can instantiate RoundRect', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final RoundRect = gdi32.lookupFunction< Int32 Function(IntPtr hdc, Int32 left, Int32 top, Int32 right, Int32 bottom, Int32 width, Int32 height), int Function(int hdc, int left, int top, int right, int bottom, int width, int height)>('RoundRect'); expect(RoundRect, isA<Function>()); }); test('Can instantiate SaveDC', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final SaveDC = gdi32.lookupFunction<Int32 Function(IntPtr hdc), int Function(int hdc)>('SaveDC'); expect(SaveDC, isA<Function>()); }); test('Can instantiate SelectClipPath', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final SelectClipPath = gdi32.lookupFunction< Int32 Function(IntPtr hdc, Int32 mode), int Function(int hdc, int mode)>('SelectClipPath'); expect(SelectClipPath, isA<Function>()); }); test('Can instantiate SelectObject', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final SelectObject = gdi32.lookupFunction< IntPtr Function(IntPtr hdc, IntPtr h), int Function(int hdc, int h)>('SelectObject'); expect(SelectObject, isA<Function>()); }); test('Can instantiate SetBkColor', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final SetBkColor = gdi32.lookupFunction< Uint32 Function(IntPtr hdc, Uint32 color), int Function(int hdc, int color)>('SetBkColor'); expect(SetBkColor, isA<Function>()); }); test('Can instantiate SetBkMode', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final SetBkMode = gdi32.lookupFunction< Int32 Function(IntPtr hdc, Uint32 mode), int Function(int hdc, int mode)>('SetBkMode'); expect(SetBkMode, isA<Function>()); }); test('Can instantiate SetMapMode', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final SetMapMode = gdi32.lookupFunction< Int32 Function(IntPtr hdc, Uint32 iMode), int Function(int hdc, int iMode)>('SetMapMode'); expect(SetMapMode, isA<Function>()); }); test('Can instantiate SetPixel', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final SetPixel = gdi32.lookupFunction< Uint32 Function(IntPtr hdc, Int32 x, Int32 y, Uint32 color), int Function(int hdc, int x, int y, int color)>('SetPixel'); expect(SetPixel, isA<Function>()); }); test('Can instantiate SetStretchBltMode', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final SetStretchBltMode = gdi32.lookupFunction< Int32 Function(IntPtr hdc, Uint32 mode), int Function(int hdc, int mode)>('SetStretchBltMode'); expect(SetStretchBltMode, isA<Function>()); }); test('Can instantiate SetTextColor', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final SetTextColor = gdi32.lookupFunction< Uint32 Function(IntPtr hdc, Uint32 color), int Function(int hdc, int color)>('SetTextColor'); expect(SetTextColor, isA<Function>()); }); test('Can instantiate SetViewportExtEx', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final SetViewportExtEx = gdi32.lookupFunction< Int32 Function(IntPtr hdc, Int32 x, Int32 y, Pointer<SIZE> lpsz), int Function( int hdc, int x, int y, Pointer<SIZE> lpsz)>('SetViewportExtEx'); expect(SetViewportExtEx, isA<Function>()); }); test('Can instantiate SetViewportOrgEx', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final SetViewportOrgEx = gdi32.lookupFunction< Int32 Function(IntPtr hdc, Int32 x, Int32 y, Pointer<POINT> lppt), int Function( int hdc, int x, int y, Pointer<POINT> lppt)>('SetViewportOrgEx'); expect(SetViewportOrgEx, isA<Function>()); }); test('Can instantiate SetWindowExtEx', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final SetWindowExtEx = gdi32.lookupFunction< Int32 Function(IntPtr hdc, Int32 x, Int32 y, Pointer<SIZE> lpsz), int Function( int hdc, int x, int y, Pointer<SIZE> lpsz)>('SetWindowExtEx'); expect(SetWindowExtEx, isA<Function>()); }); test('Can instantiate StretchBlt', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final StretchBlt = gdi32.lookupFunction< Int32 Function( IntPtr hdcDest, Int32 xDest, Int32 yDest, Int32 wDest, Int32 hDest, IntPtr hdcSrc, Int32 xSrc, Int32 ySrc, Int32 wSrc, Int32 hSrc, Uint32 rop), int Function( int hdcDest, int xDest, int yDest, int wDest, int hDest, int hdcSrc, int xSrc, int ySrc, int wSrc, int hSrc, int rop)>('StretchBlt'); expect(StretchBlt, isA<Function>()); }); test('Can instantiate StretchDIBits', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final StretchDIBits = gdi32.lookupFunction< Int32 Function( IntPtr hdc, Int32 xDest, Int32 yDest, Int32 DestWidth, Int32 DestHeight, Int32 xSrc, Int32 ySrc, Int32 SrcWidth, Int32 SrcHeight, Pointer lpBits, Pointer<BITMAPINFO> lpbmi, Uint32 iUsage, Uint32 rop), int Function( int hdc, int xDest, int yDest, int DestWidth, int DestHeight, int xSrc, int ySrc, int SrcWidth, int SrcHeight, Pointer lpBits, Pointer<BITMAPINFO> lpbmi, int iUsage, int rop)>('StretchDIBits'); expect(StretchDIBits, isA<Function>()); }); test('Can instantiate StrokeAndFillPath', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final StrokeAndFillPath = gdi32.lookupFunction<Int32 Function(IntPtr hdc), int Function(int hdc)>('StrokeAndFillPath'); expect(StrokeAndFillPath, isA<Function>()); }); test('Can instantiate StrokePath', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final StrokePath = gdi32.lookupFunction<Int32 Function(IntPtr hdc), int Function(int hdc)>('StrokePath'); expect(StrokePath, isA<Function>()); }); test('Can instantiate TextOut', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final TextOut = gdi32.lookupFunction< Int32 Function( IntPtr hdc, Int32 x, Int32 y, Pointer<Utf16> lpString, Int32 c), int Function(int hdc, int x, int y, Pointer<Utf16> lpString, int c)>('TextOutW'); expect(TextOut, isA<Function>()); }); test('Can instantiate WidenPath', () { final gdi32 = DynamicLibrary.open('gdi32.dll'); final WidenPath = gdi32.lookupFunction<Int32 Function(IntPtr hdc), int Function(int hdc)>('WidenPath'); expect(WidenPath, isA<Function>()); }); }); group('Test spoolss functions', () { test('Can instantiate AbortPrinter', () { final spoolss = DynamicLibrary.open('spoolss.dll'); final AbortPrinter = spoolss.lookupFunction< Int32 Function(IntPtr hPrinter), int Function(int hPrinter)>('AbortPrinter'); expect(AbortPrinter, isA<Function>()); }); test('Can instantiate ClosePrinter', () { final spoolss = DynamicLibrary.open('spoolss.dll'); final ClosePrinter = spoolss.lookupFunction< Int32 Function(IntPtr hPrinter), int Function(int hPrinter)>('ClosePrinter'); expect(ClosePrinter, isA<Function>()); }); test('Can instantiate DeletePrinter', () { final spoolss = DynamicLibrary.open('spoolss.dll'); final DeletePrinter = spoolss.lookupFunction< Int32 Function(IntPtr hPrinter), int Function(int hPrinter)>('DeletePrinter'); expect(DeletePrinter, isA<Function>()); }); test('Can instantiate EndDocPrinter', () { final spoolss = DynamicLibrary.open('spoolss.dll'); final EndDocPrinter = spoolss.lookupFunction< Int32 Function(IntPtr hPrinter), int Function(int hPrinter)>('EndDocPrinter'); expect(EndDocPrinter, isA<Function>()); }); test('Can instantiate EndPagePrinter', () { final spoolss = DynamicLibrary.open('spoolss.dll'); final EndPagePrinter = spoolss.lookupFunction< Int32 Function(IntPtr hPrinter), int Function(int hPrinter)>('EndPagePrinter'); expect(EndPagePrinter, isA<Function>()); }); test('Can instantiate FindClosePrinterChangeNotification', () { final spoolss = DynamicLibrary.open('spoolss.dll'); final FindClosePrinterChangeNotification = spoolss.lookupFunction< Int32 Function(IntPtr hChange), int Function(int hChange)>('FindClosePrinterChangeNotification'); expect(FindClosePrinterChangeNotification, isA<Function>()); }); test('Can instantiate OpenPrinter2', () { final spoolss = DynamicLibrary.open('spoolss.dll'); final OpenPrinter2 = spoolss.lookupFunction< Int32 Function( Pointer<Utf16> pPrinterName, Pointer<IntPtr> phPrinter, Pointer<PRINTER_DEFAULTS> pDefault, Pointer<PRINTER_OPTIONS> pOptions), int Function( Pointer<Utf16> pPrinterName, Pointer<IntPtr> phPrinter, Pointer<PRINTER_DEFAULTS> pDefault, Pointer<PRINTER_OPTIONS> pOptions)>('OpenPrinter2W'); expect(OpenPrinter2, isA<Function>()); }); test('Can instantiate ReadPrinter', () { final spoolss = DynamicLibrary.open('spoolss.dll'); final ReadPrinter = spoolss.lookupFunction< Int32 Function(IntPtr hPrinter, Pointer pBuf, Uint32 cbBuf, Pointer<Uint32> pNoBytesRead), int Function(int hPrinter, Pointer pBuf, int cbBuf, Pointer<Uint32> pNoBytesRead)>('ReadPrinter'); expect(ReadPrinter, isA<Function>()); }); test('Can instantiate ReportJobProcessingProgress', () { final spoolss = DynamicLibrary.open('spoolss.dll'); final ReportJobProcessingProgress = spoolss.lookupFunction< Int32 Function(IntPtr printerHandle, Uint32 jobId, Int32 jobOperation, Int32 jobProgress), int Function(int printerHandle, int jobId, int jobOperation, int jobProgress)>('ReportJobProcessingProgress'); expect(ReportJobProcessingProgress, isA<Function>()); }); test('Can instantiate ScheduleJob', () { final spoolss = DynamicLibrary.open('spoolss.dll'); final ScheduleJob = spoolss.lookupFunction< Int32 Function(IntPtr hPrinter, Uint32 JobId), int Function(int hPrinter, int JobId)>('ScheduleJob'); expect(ScheduleJob, isA<Function>()); }); test('Can instantiate StartPagePrinter', () { final spoolss = DynamicLibrary.open('spoolss.dll'); final StartPagePrinter = spoolss.lookupFunction< Int32 Function(IntPtr hPrinter), int Function(int hPrinter)>('StartPagePrinter'); expect(StartPagePrinter, isA<Function>()); }); test('Can instantiate WritePrinter', () { final spoolss = DynamicLibrary.open('spoolss.dll'); final WritePrinter = spoolss.lookupFunction< Int32 Function(IntPtr hPrinter, Pointer pBuf, Uint32 cbBuf, Pointer<Uint32> pcWritten), int Function(int hPrinter, Pointer pBuf, int cbBuf, Pointer<Uint32> pcWritten)>('WritePrinter'); expect(WritePrinter, isA<Function>()); }); }); group('Test ws2_32 functions', () { if (windowsBuildNumber >= 9600) { test('Can instantiate accept', () { final ws2_32 = DynamicLibrary.open('ws2_32.dll'); final accept = ws2_32.lookupFunction< IntPtr Function( IntPtr s, Pointer<SOCKADDR> addr, Pointer<Int32> addrlen), int Function(int s, Pointer<SOCKADDR> addr, Pointer<Int32> addrlen)>('accept'); expect(accept, isA<Function>()); }); } if (windowsBuildNumber >= 9600) { test('Can instantiate bind', () { final ws2_32 = DynamicLibrary.open('ws2_32.dll'); final bind = ws2_32.lookupFunction< Int32 Function(IntPtr s, Pointer<SOCKADDR> name, Int32 namelen), int Function(int s, Pointer<SOCKADDR> name, int namelen)>('bind'); expect(bind, isA<Function>()); }); } if (windowsBuildNumber >= 9600) { test('Can instantiate closesocket', () { final ws2_32 = DynamicLibrary.open('ws2_32.dll'); final closesocket = ws2_32.lookupFunction<Int32 Function(IntPtr s), int Function(int s)>('closesocket'); expect(closesocket, isA<Function>()); }); } if (windowsBuildNumber >= 9600) { test('Can instantiate connect', () { final ws2_32 = DynamicLibrary.open('ws2_32.dll'); final connect = ws2_32.lookupFunction< Int32 Function(IntPtr s, Pointer<SOCKADDR> name, Int32 namelen), int Function( int s, Pointer<SOCKADDR> name, int namelen)>('connect'); expect(connect, isA<Function>()); }); } if (windowsBuildNumber >= 9600) { test('Can instantiate GetAddrInfoW', () { final ws2_32 = DynamicLibrary.open('ws2_32.dll'); final GetAddrInfoW = ws2_32.lookupFunction< Int32 Function( Pointer<Utf16> pNodeName, Pointer<Utf16> pServiceName, Pointer<addrinfo> pHints, Pointer<Pointer<addrinfo>> ppResult), int Function( Pointer<Utf16> pNodeName, Pointer<Utf16> pServiceName, Pointer<addrinfo> pHints, Pointer<Pointer<addrinfo>> ppResult)>('GetAddrInfoW'); expect(GetAddrInfoW, isA<Function>()); }); } if (windowsBuildNumber >= 9600) { test('Can instantiate gethostbyaddr', () { final ws2_32 = DynamicLibrary.open('ws2_32.dll'); final gethostbyaddr = ws2_32.lookupFunction< Pointer<hostent> Function( Pointer<Utf8> addr, Int32 len, Int32 type), Pointer<hostent> Function( Pointer<Utf8> addr, int len, int type)>('gethostbyaddr'); expect(gethostbyaddr, isA<Function>()); }); } if (windowsBuildNumber >= 9600) { test('Can instantiate gethostbyname', () { final ws2_32 = DynamicLibrary.open('ws2_32.dll'); final gethostbyname = ws2_32.lookupFunction< Pointer<hostent> Function(Pointer<Utf8> name), Pointer<hostent> Function(Pointer<Utf8> name)>('gethostbyname'); expect(gethostbyname, isA<Function>()); }); } if (windowsBuildNumber >= 9600) { test('Can instantiate gethostname', () { final ws2_32 = DynamicLibrary.open('ws2_32.dll'); final gethostname = ws2_32.lookupFunction< Int32 Function(Pointer<Utf8> name, Int32 namelen), int Function(Pointer<Utf8> name, int namelen)>('gethostname'); expect(gethostname, isA<Function>()); }); } if (windowsBuildNumber >= 9600) { test('Can instantiate getnameinfo', () { final ws2_32 = DynamicLibrary.open('ws2_32.dll'); final getnameinfo = ws2_32.lookupFunction< Int32 Function( Pointer<SOCKADDR> pSockaddr, Int32 SockaddrLength, Pointer<Utf8> pNodeBuffer, Uint32 NodeBufferSize, Pointer<Utf8> pServiceBuffer, Uint32 ServiceBufferSize, Int32 Flags), int Function( Pointer<SOCKADDR> pSockaddr, int SockaddrLength, Pointer<Utf8> pNodeBuffer, int NodeBufferSize, Pointer<Utf8> pServiceBuffer, int ServiceBufferSize, int Flags)>('getnameinfo'); expect(getnameinfo, isA<Function>()); }); } if (windowsBuildNumber >= 9600) { test('Can instantiate getpeername', () { final ws2_32 = DynamicLibrary.open('ws2_32.dll'); final getpeername = ws2_32.lookupFunction< Int32 Function( IntPtr s, Pointer<SOCKADDR> name, Pointer<Int32> namelen), int Function(int s, Pointer<SOCKADDR> name, Pointer<Int32> namelen)>('getpeername'); expect(getpeername, isA<Function>()); }); } if (windowsBuildNumber >= 9600) { test('Can instantiate getprotobyname', () { final ws2_32 = DynamicLibrary.open('ws2_32.dll'); final getprotobyname = ws2_32.lookupFunction< Pointer<protoent> Function(Pointer<Utf8> name), Pointer<protoent> Function(Pointer<Utf8> name)>('getprotobyname'); expect(getprotobyname, isA<Function>()); }); } if (windowsBuildNumber >= 9600) { test('Can instantiate getprotobynumber', () { final ws2_32 = DynamicLibrary.open('ws2_32.dll'); final getprotobynumber = ws2_32.lookupFunction< Pointer<protoent> Function(Int32 number), Pointer<protoent> Function(int number)>('getprotobynumber'); expect(getprotobynumber, isA<Function>()); }); } if (windowsBuildNumber >= 9600) { test('Can instantiate getservbyname', () { final ws2_32 = DynamicLibrary.open('ws2_32.dll'); final getservbyname = ws2_32.lookupFunction< Pointer<servent> Function(Pointer<Utf8> name, Pointer<Utf8> proto), Pointer<servent> Function( Pointer<Utf8> name, Pointer<Utf8> proto)>('getservbyname'); expect(getservbyname, isA<Function>()); }); } if (windowsBuildNumber >= 9600) { test('Can instantiate getservbyport', () { final ws2_32 = DynamicLibrary.open('ws2_32.dll'); final getservbyport = ws2_32.lookupFunction< Pointer<servent> Function(Int32 port, Pointer<Utf8> proto), Pointer<servent> Function( int port, Pointer<Utf8> proto)>('getservbyport'); expect(getservbyport, isA<Function>()); }); } if (windowsBuildNumber >= 9600) { test('Can instantiate getsockname', () { final ws2_32 = DynamicLibrary.open('ws2_32.dll'); final getsockname = ws2_32.lookupFunction< Int32 Function( IntPtr s, Pointer<SOCKADDR> name, Pointer<Int32> namelen), int Function(int s, Pointer<SOCKADDR> name, Pointer<Int32> namelen)>('getsockname'); expect(getsockname, isA<Function>()); }); } if (windowsBuildNumber >= 9600) { test('Can instantiate getsockopt', () { final ws2_32 = DynamicLibrary.open('ws2_32.dll'); final getsockopt = ws2_32.lookupFunction< Int32 Function(IntPtr s, Int32 level, Int32 optname, Pointer<Utf8> optval, Pointer<Int32> optlen), int Function(int s, int level, int optname, Pointer<Utf8> optval, Pointer<Int32> optlen)>('getsockopt'); expect(getsockopt, isA<Function>()); }); } if (windowsBuildNumber >= 9600) { test('Can instantiate htonl', () { final ws2_32 = DynamicLibrary.open('ws2_32.dll'); final htonl = ws2_32.lookupFunction<Uint32 Function(Uint32 hostlong), int Function(int hostlong)>('htonl'); expect(htonl, isA<Function>()); }); } if (windowsBuildNumber >= 9600) { test('Can instantiate htons', () { final ws2_32 = DynamicLibrary.open('ws2_32.dll'); final htons = ws2_32.lookupFunction<Uint16 Function(Uint16 hostshort), int Function(int hostshort)>('htons'); expect(htons, isA<Function>()); }); } if (windowsBuildNumber >= 9600) { test('Can instantiate inet_addr', () { final ws2_32 = DynamicLibrary.open('ws2_32.dll'); final inet_addr = ws2_32.lookupFunction< Uint32 Function(Pointer<Utf8> cp), int Function(Pointer<Utf8> cp)>('inet_addr'); expect(inet_addr, isA<Function>()); }); } if (windowsBuildNumber >= 9600) { test('Can instantiate inet_ntoa', () { final ws2_32 = DynamicLibrary.open('ws2_32.dll'); final inet_ntoa = ws2_32.lookupFunction< Pointer<Utf8> Function(IN_ADDR in_), Pointer<Utf8> Function(IN_ADDR in_)>('inet_ntoa'); expect(inet_ntoa, isA<Function>()); }); } if (windowsBuildNumber >= 9600) { test('Can instantiate ioctlsocket', () { final ws2_32 = DynamicLibrary.open('ws2_32.dll'); final ioctlsocket = ws2_32.lookupFunction< Int32 Function(IntPtr s, Int32 cmd, Pointer<Uint32> argp), int Function(int s, int cmd, Pointer<Uint32> argp)>('ioctlsocket'); expect(ioctlsocket, isA<Function>()); }); } if (windowsBuildNumber >= 9600) { test('Can instantiate listen', () { final ws2_32 = DynamicLibrary.open('ws2_32.dll'); final listen = ws2_32.lookupFunction< Int32 Function(IntPtr s, Int32 backlog), int Function(int s, int backlog)>('listen'); expect(listen, isA<Function>()); }); } if (windowsBuildNumber >= 9600) { test('Can instantiate ntohl', () { final ws2_32 = DynamicLibrary.open('ws2_32.dll'); final ntohl = ws2_32.lookupFunction<Uint32 Function(Uint32 netlong), int Function(int netlong)>('ntohl'); expect(ntohl, isA<Function>()); }); } if (windowsBuildNumber >= 9600) { test('Can instantiate ntohs', () { final ws2_32 = DynamicLibrary.open('ws2_32.dll'); final ntohs = ws2_32.lookupFunction<Uint16 Function(Uint16 netshort), int Function(int netshort)>('ntohs'); expect(ntohs, isA<Function>()); }); } if (windowsBuildNumber >= 9600) { test('Can instantiate recv', () { final ws2_32 = DynamicLibrary.open('ws2_32.dll'); final recv = ws2_32.lookupFunction< Int32 Function(IntPtr s, Pointer<Utf8> buf, Int32 len, Int32 flags), int Function(int s, Pointer<Utf8> buf, int len, int flags)>('recv'); expect(recv, isA<Function>()); }); } if (windowsBuildNumber >= 9600) { test('Can instantiate recvfrom', () { final ws2_32 = DynamicLibrary.open('ws2_32.dll'); final recvfrom = ws2_32.lookupFunction< Int32 Function(IntPtr s, Pointer<Utf8> buf, Int32 len, Int32 flags, Pointer<SOCKADDR> from, Pointer<Int32> fromlen), int Function(int s, Pointer<Utf8> buf, int len, int flags, Pointer<SOCKADDR> from, Pointer<Int32> fromlen)>('recvfrom'); expect(recvfrom, isA<Function>()); }); } if (windowsBuildNumber >= 9600) { test('Can instantiate select', () { final ws2_32 = DynamicLibrary.open('ws2_32.dll'); final select = ws2_32.lookupFunction< Int32 Function( Int32 nfds, Pointer<fd_set> readfds, Pointer<fd_set> writefds, Pointer<fd_set> exceptfds, Pointer<timeval> timeout), int Function( int nfds, Pointer<fd_set> readfds, Pointer<fd_set> writefds, Pointer<fd_set> exceptfds, Pointer<timeval> timeout)>('select'); expect(select, isA<Function>()); }); } if (windowsBuildNumber >= 9600) { test('Can instantiate send', () { final ws2_32 = DynamicLibrary.open('ws2_32.dll'); final send = ws2_32.lookupFunction< Int32 Function( IntPtr s, Pointer<Utf8> buf, Int32 len, Uint32 flags), int Function(int s, Pointer<Utf8> buf, int len, int flags)>('send'); expect(send, isA<Function>()); }); } if (windowsBuildNumber >= 9600) { test('Can instantiate sendto', () { final ws2_32 = DynamicLibrary.open('ws2_32.dll'); final sendto = ws2_32.lookupFunction< Int32 Function(IntPtr s, Pointer<Utf8> buf, Int32 len, Int32 flags, Pointer<SOCKADDR> to, Int32 tolen), int Function(int s, Pointer<Utf8> buf, int len, int flags, Pointer<SOCKADDR> to, int tolen)>('sendto'); expect(sendto, isA<Function>()); }); } if (windowsBuildNumber >= 9600) { test('Can instantiate shutdown', () { final ws2_32 = DynamicLibrary.open('ws2_32.dll'); final shutdown = ws2_32.lookupFunction< Int32 Function(IntPtr s, Int32 how), int Function(int s, int how)>('shutdown'); expect(shutdown, isA<Function>()); }); } if (windowsBuildNumber >= 9600) { test('Can instantiate socket', () { final ws2_32 = DynamicLibrary.open('ws2_32.dll'); final socket = ws2_32.lookupFunction< IntPtr Function(Int32 af, Int32 type, Int32 protocol), int Function(int af, int type, int protocol)>('socket'); expect(socket, isA<Function>()); }); } }); group('Test kernel32 functions', () { test('Can instantiate ActivateActCtx', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final ActivateActCtx = kernel32.lookupFunction< Int32 Function(IntPtr hActCtx, Pointer<IntPtr> lpCookie), int Function( int hActCtx, Pointer<IntPtr> lpCookie)>('ActivateActCtx'); expect(ActivateActCtx, isA<Function>()); }); test('Can instantiate AddRefActCtx', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final AddRefActCtx = kernel32.lookupFunction< Void Function(IntPtr hActCtx), void Function(int hActCtx)>('AddRefActCtx'); expect(AddRefActCtx, isA<Function>()); }); test('Can instantiate AllocConsole', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final AllocConsole = kernel32 .lookupFunction<Int32 Function(), int Function()>('AllocConsole'); expect(AllocConsole, isA<Function>()); }); test('Can instantiate AttachConsole', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final AttachConsole = kernel32.lookupFunction< Int32 Function(Uint32 dwProcessId), int Function(int dwProcessId)>('AttachConsole'); expect(AttachConsole, isA<Function>()); }); test('Can instantiate Beep', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final Beep = kernel32.lookupFunction< Int32 Function(Uint32 dwFreq, Uint32 dwDuration), int Function(int dwFreq, int dwDuration)>('Beep'); expect(Beep, isA<Function>()); }); test('Can instantiate BeginUpdateResource', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final BeginUpdateResource = kernel32.lookupFunction< IntPtr Function( Pointer<Utf16> pFileName, Int32 bDeleteExistingResources), int Function(Pointer<Utf16> pFileName, int bDeleteExistingResources)>('BeginUpdateResourceW'); expect(BeginUpdateResource, isA<Function>()); }); test('Can instantiate BuildCommDCB', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final BuildCommDCB = kernel32.lookupFunction< Int32 Function(Pointer<Utf16> lpDef, Pointer<DCB> lpDCB), int Function( Pointer<Utf16> lpDef, Pointer<DCB> lpDCB)>('BuildCommDCBW'); expect(BuildCommDCB, isA<Function>()); }); test('Can instantiate BuildCommDCBAndTimeouts', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final BuildCommDCBAndTimeouts = kernel32.lookupFunction< Int32 Function(Pointer<Utf16> lpDef, Pointer<DCB> lpDCB, Pointer<COMMTIMEOUTS> lpCommTimeouts), int Function(Pointer<Utf16> lpDef, Pointer<DCB> lpDCB, Pointer<COMMTIMEOUTS> lpCommTimeouts)>( 'BuildCommDCBAndTimeoutsW'); expect(BuildCommDCBAndTimeouts, isA<Function>()); }); test('Can instantiate CallNamedPipe', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final CallNamedPipe = kernel32.lookupFunction< Int32 Function( Pointer<Utf16> lpNamedPipeName, Pointer lpInBuffer, Uint32 nInBufferSize, Pointer lpOutBuffer, Uint32 nOutBufferSize, Pointer<Uint32> lpBytesRead, Uint32 nTimeOut), int Function( Pointer<Utf16> lpNamedPipeName, Pointer lpInBuffer, int nInBufferSize, Pointer lpOutBuffer, int nOutBufferSize, Pointer<Uint32> lpBytesRead, int nTimeOut)>('CallNamedPipeW'); expect(CallNamedPipe, isA<Function>()); }); test('Can instantiate CancelIo', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final CancelIo = kernel32.lookupFunction<Int32 Function(IntPtr hFile), int Function(int hFile)>('CancelIo'); expect(CancelIo, isA<Function>()); }); test('Can instantiate CancelIoEx', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final CancelIoEx = kernel32.lookupFunction< Int32 Function(IntPtr hFile, Pointer<OVERLAPPED> lpOverlapped), int Function( int hFile, Pointer<OVERLAPPED> lpOverlapped)>('CancelIoEx'); expect(CancelIoEx, isA<Function>()); }); test('Can instantiate CancelSynchronousIo', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final CancelSynchronousIo = kernel32.lookupFunction< Int32 Function(IntPtr hThread), int Function(int hThread)>('CancelSynchronousIo'); expect(CancelSynchronousIo, isA<Function>()); }); test('Can instantiate CheckRemoteDebuggerPresent', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final CheckRemoteDebuggerPresent = kernel32.lookupFunction< Int32 Function(IntPtr hProcess, Pointer<Int32> pbDebuggerPresent), int Function(int hProcess, Pointer<Int32> pbDebuggerPresent)>('CheckRemoteDebuggerPresent'); expect(CheckRemoteDebuggerPresent, isA<Function>()); }); test('Can instantiate ClearCommBreak', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final ClearCommBreak = kernel32.lookupFunction< Int32 Function(IntPtr hFile), int Function(int hFile)>('ClearCommBreak'); expect(ClearCommBreak, isA<Function>()); }); test('Can instantiate ClearCommError', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final ClearCommError = kernel32.lookupFunction< Int32 Function( IntPtr hFile, Pointer<Uint32> lpErrors, Pointer<COMSTAT> lpStat), int Function(int hFile, Pointer<Uint32> lpErrors, Pointer<COMSTAT> lpStat)>('ClearCommError'); expect(ClearCommError, isA<Function>()); }); test('Can instantiate CloseHandle', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final CloseHandle = kernel32.lookupFunction< Int32 Function(IntPtr hObject), int Function(int hObject)>('CloseHandle'); expect(CloseHandle, isA<Function>()); }); if (windowsBuildNumber >= 17763) { test('Can instantiate ClosePseudoConsole', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final ClosePseudoConsole = kernel32.lookupFunction< Void Function(IntPtr hPC), void Function(int hPC)>('ClosePseudoConsole'); expect(ClosePseudoConsole, isA<Function>()); }); } test('Can instantiate CommConfigDialog', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final CommConfigDialog = kernel32.lookupFunction< Int32 Function( Pointer<Utf16> lpszName, IntPtr hWnd, Pointer<COMMCONFIG> lpCC), int Function(Pointer<Utf16> lpszName, int hWnd, Pointer<COMMCONFIG> lpCC)>('CommConfigDialogW'); expect(CommConfigDialog, isA<Function>()); }); test('Can instantiate ConnectNamedPipe', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final ConnectNamedPipe = kernel32.lookupFunction< Int32 Function(IntPtr hNamedPipe, Pointer<OVERLAPPED> lpOverlapped), int Function(int hNamedPipe, Pointer<OVERLAPPED> lpOverlapped)>('ConnectNamedPipe'); expect(ConnectNamedPipe, isA<Function>()); }); test('Can instantiate ContinueDebugEvent', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final ContinueDebugEvent = kernel32.lookupFunction< Int32 Function( Uint32 dwProcessId, Uint32 dwThreadId, Uint32 dwContinueStatus), int Function(int dwProcessId, int dwThreadId, int dwContinueStatus)>('ContinueDebugEvent'); expect(ContinueDebugEvent, isA<Function>()); }); test('Can instantiate CreateActCtx', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final CreateActCtx = kernel32.lookupFunction< IntPtr Function(Pointer<ACTCTX> pActCtx), int Function(Pointer<ACTCTX> pActCtx)>('CreateActCtxW'); expect(CreateActCtx, isA<Function>()); }); test('Can instantiate CreateConsoleScreenBuffer', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final CreateConsoleScreenBuffer = kernel32.lookupFunction< IntPtr Function( Uint32 dwDesiredAccess, Uint32 dwShareMode, Pointer<SECURITY_ATTRIBUTES> lpSecurityAttributes, Uint32 dwFlags, Pointer lpScreenBufferData), int Function( int dwDesiredAccess, int dwShareMode, Pointer<SECURITY_ATTRIBUTES> lpSecurityAttributes, int dwFlags, Pointer lpScreenBufferData)>('CreateConsoleScreenBuffer'); expect(CreateConsoleScreenBuffer, isA<Function>()); }); test('Can instantiate CreateDirectory', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final CreateDirectory = kernel32.lookupFunction< Int32 Function(Pointer<Utf16> lpPathName, Pointer<SECURITY_ATTRIBUTES> lpSecurityAttributes), int Function(Pointer<Utf16> lpPathName, Pointer<SECURITY_ATTRIBUTES> lpSecurityAttributes)>( 'CreateDirectoryW'); expect(CreateDirectory, isA<Function>()); }); test('Can instantiate CreateEvent', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final CreateEvent = kernel32.lookupFunction< IntPtr Function(Pointer<SECURITY_ATTRIBUTES> lpEventAttributes, Int32 bManualReset, Int32 bInitialState, Pointer<Utf16> lpName), int Function( Pointer<SECURITY_ATTRIBUTES> lpEventAttributes, int bManualReset, int bInitialState, Pointer<Utf16> lpName)>('CreateEventW'); expect(CreateEvent, isA<Function>()); }); test('Can instantiate CreateEventEx', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final CreateEventEx = kernel32.lookupFunction< IntPtr Function(Pointer<SECURITY_ATTRIBUTES> lpEventAttributes, Pointer<Utf16> lpName, Uint32 dwFlags, Uint32 dwDesiredAccess), int Function( Pointer<SECURITY_ATTRIBUTES> lpEventAttributes, Pointer<Utf16> lpName, int dwFlags, int dwDesiredAccess)>('CreateEventExW'); expect(CreateEventEx, isA<Function>()); }); test('Can instantiate CreateFile', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final CreateFile = kernel32.lookupFunction< IntPtr Function( Pointer<Utf16> lpFileName, Uint32 dwDesiredAccess, Uint32 dwShareMode, Pointer<SECURITY_ATTRIBUTES> lpSecurityAttributes, Uint32 dwCreationDisposition, Uint32 dwFlagsAndAttributes, IntPtr hTemplateFile), int Function( Pointer<Utf16> lpFileName, int dwDesiredAccess, int dwShareMode, Pointer<SECURITY_ATTRIBUTES> lpSecurityAttributes, int dwCreationDisposition, int dwFlagsAndAttributes, int hTemplateFile)>('CreateFileW'); expect(CreateFile, isA<Function>()); }); test('Can instantiate CreateIoCompletionPort', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final CreateIoCompletionPort = kernel32.lookupFunction< IntPtr Function(IntPtr FileHandle, IntPtr ExistingCompletionPort, IntPtr CompletionKey, Uint32 NumberOfConcurrentThreads), int Function( int FileHandle, int ExistingCompletionPort, int CompletionKey, int NumberOfConcurrentThreads)>('CreateIoCompletionPort'); expect(CreateIoCompletionPort, isA<Function>()); }); test('Can instantiate CreateNamedPipe', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final CreateNamedPipe = kernel32.lookupFunction< IntPtr Function( Pointer<Utf16> lpName, Uint32 dwOpenMode, Uint32 dwPipeMode, Uint32 nMaxInstances, Uint32 nOutBufferSize, Uint32 nInBufferSize, Uint32 nDefaultTimeOut, Pointer<SECURITY_ATTRIBUTES> lpSecurityAttributes), int Function( Pointer<Utf16> lpName, int dwOpenMode, int dwPipeMode, int nMaxInstances, int nOutBufferSize, int nInBufferSize, int nDefaultTimeOut, Pointer<SECURITY_ATTRIBUTES> lpSecurityAttributes)>( 'CreateNamedPipeW'); expect(CreateNamedPipe, isA<Function>()); }); test('Can instantiate CreatePipe', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final CreatePipe = kernel32.lookupFunction< Int32 Function(Pointer<IntPtr> hReadPipe, Pointer<IntPtr> hWritePipe, Pointer<SECURITY_ATTRIBUTES> lpPipeAttributes, Uint32 nSize), int Function( Pointer<IntPtr> hReadPipe, Pointer<IntPtr> hWritePipe, Pointer<SECURITY_ATTRIBUTES> lpPipeAttributes, int nSize)>('CreatePipe'); expect(CreatePipe, isA<Function>()); }); test('Can instantiate CreateProcess', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final CreateProcess = kernel32.lookupFunction< Int32 Function( Pointer<Utf16> lpApplicationName, Pointer<Utf16> lpCommandLine, Pointer<SECURITY_ATTRIBUTES> lpProcessAttributes, Pointer<SECURITY_ATTRIBUTES> lpThreadAttributes, Int32 bInheritHandles, Uint32 dwCreationFlags, Pointer lpEnvironment, Pointer<Utf16> lpCurrentDirectory, Pointer<STARTUPINFO> lpStartupInfo, Pointer<PROCESS_INFORMATION> lpProcessInformation), int Function( Pointer<Utf16> lpApplicationName, Pointer<Utf16> lpCommandLine, Pointer<SECURITY_ATTRIBUTES> lpProcessAttributes, Pointer<SECURITY_ATTRIBUTES> lpThreadAttributes, int bInheritHandles, int dwCreationFlags, Pointer lpEnvironment, Pointer<Utf16> lpCurrentDirectory, Pointer<STARTUPINFO> lpStartupInfo, Pointer<PROCESS_INFORMATION> lpProcessInformation)>( 'CreateProcessW'); expect(CreateProcess, isA<Function>()); }); if (windowsBuildNumber >= 17763) { test('Can instantiate CreatePseudoConsole', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final CreatePseudoConsole = kernel32.lookupFunction< Int32 Function(COORD size, IntPtr hInput, IntPtr hOutput, Uint32 dwFlags, Pointer<IntPtr> phPC), int Function(COORD size, int hInput, int hOutput, int dwFlags, Pointer<IntPtr> phPC)>('CreatePseudoConsole'); expect(CreatePseudoConsole, isA<Function>()); }); } test('Can instantiate CreateRemoteThread', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final CreateRemoteThread = kernel32.lookupFunction< IntPtr Function( IntPtr hProcess, Pointer<SECURITY_ATTRIBUTES> lpThreadAttributes, IntPtr dwStackSize, Pointer<NativeFunction<ThreadProc>> lpStartAddress, Pointer lpParameter, Uint32 dwCreationFlags, Pointer<Uint32> lpThreadId), int Function( int hProcess, Pointer<SECURITY_ATTRIBUTES> lpThreadAttributes, int dwStackSize, Pointer<NativeFunction<ThreadProc>> lpStartAddress, Pointer lpParameter, int dwCreationFlags, Pointer<Uint32> lpThreadId)>('CreateRemoteThread'); expect(CreateRemoteThread, isA<Function>()); }); test('Can instantiate CreateRemoteThreadEx', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final CreateRemoteThreadEx = kernel32.lookupFunction< IntPtr Function( IntPtr hProcess, Pointer<SECURITY_ATTRIBUTES> lpThreadAttributes, IntPtr dwStackSize, Pointer<NativeFunction<ThreadProc>> lpStartAddress, Pointer lpParameter, Uint32 dwCreationFlags, Pointer lpAttributeList, Pointer<Uint32> lpThreadId), int Function( int hProcess, Pointer<SECURITY_ATTRIBUTES> lpThreadAttributes, int dwStackSize, Pointer<NativeFunction<ThreadProc>> lpStartAddress, Pointer lpParameter, int dwCreationFlags, Pointer lpAttributeList, Pointer<Uint32> lpThreadId)>('CreateRemoteThreadEx'); expect(CreateRemoteThreadEx, isA<Function>()); }); test('Can instantiate CreateThread', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final CreateThread = kernel32.lookupFunction< IntPtr Function( Pointer<SECURITY_ATTRIBUTES> lpThreadAttributes, IntPtr dwStackSize, Pointer<NativeFunction<ThreadProc>> lpStartAddress, Pointer lpParameter, Uint32 dwCreationFlags, Pointer<Uint32> lpThreadId), int Function( Pointer<SECURITY_ATTRIBUTES> lpThreadAttributes, int dwStackSize, Pointer<NativeFunction<ThreadProc>> lpStartAddress, Pointer lpParameter, int dwCreationFlags, Pointer<Uint32> lpThreadId)>('CreateThread'); expect(CreateThread, isA<Function>()); }); test('Can instantiate DeactivateActCtx', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final DeactivateActCtx = kernel32.lookupFunction< Int32 Function(Uint32 dwFlags, IntPtr ulCookie), int Function(int dwFlags, int ulCookie)>('DeactivateActCtx'); expect(DeactivateActCtx, isA<Function>()); }); test('Can instantiate DebugBreak', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final DebugBreak = kernel32 .lookupFunction<Void Function(), void Function()>('DebugBreak'); expect(DebugBreak, isA<Function>()); }); test('Can instantiate DebugBreakProcess', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final DebugBreakProcess = kernel32.lookupFunction< Int32 Function(IntPtr Process), int Function(int Process)>('DebugBreakProcess'); expect(DebugBreakProcess, isA<Function>()); }); test('Can instantiate DebugSetProcessKillOnExit', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final DebugSetProcessKillOnExit = kernel32.lookupFunction< Int32 Function(Int32 KillOnExit), int Function(int KillOnExit)>('DebugSetProcessKillOnExit'); expect(DebugSetProcessKillOnExit, isA<Function>()); }); test('Can instantiate DeleteFile', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final DeleteFile = kernel32.lookupFunction< Int32 Function(Pointer<Utf16> lpFileName), int Function(Pointer<Utf16> lpFileName)>('DeleteFileW'); expect(DeleteFile, isA<Function>()); }); test('Can instantiate DeviceIoControl', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final DeviceIoControl = kernel32.lookupFunction< Int32 Function( IntPtr hDevice, Uint32 dwIoControlCode, Pointer lpInBuffer, Uint32 nInBufferSize, Pointer lpOutBuffer, Uint32 nOutBufferSize, Pointer<Uint32> lpBytesReturned, Pointer<OVERLAPPED> lpOverlapped), int Function( int hDevice, int dwIoControlCode, Pointer lpInBuffer, int nInBufferSize, Pointer lpOutBuffer, int nOutBufferSize, Pointer<Uint32> lpBytesReturned, Pointer<OVERLAPPED> lpOverlapped)>('DeviceIoControl'); expect(DeviceIoControl, isA<Function>()); }); test('Can instantiate DisconnectNamedPipe', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final DisconnectNamedPipe = kernel32.lookupFunction< Int32 Function(IntPtr hNamedPipe), int Function(int hNamedPipe)>('DisconnectNamedPipe'); expect(DisconnectNamedPipe, isA<Function>()); }); test('Can instantiate DnsHostnameToComputerName', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final DnsHostnameToComputerName = kernel32.lookupFunction< Int32 Function(Pointer<Utf16> Hostname, Pointer<Utf16> ComputerName, Pointer<Uint32> nSize), int Function(Pointer<Utf16> Hostname, Pointer<Utf16> ComputerName, Pointer<Uint32> nSize)>('DnsHostnameToComputerNameW'); expect(DnsHostnameToComputerName, isA<Function>()); }); test('Can instantiate DosDateTimeToFileTime', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final DosDateTimeToFileTime = kernel32.lookupFunction< Int32 Function( Uint16 wFatDate, Uint16 wFatTime, Pointer<FILETIME> lpFileTime), int Function(int wFatDate, int wFatTime, Pointer<FILETIME> lpFileTime)>('DosDateTimeToFileTime'); expect(DosDateTimeToFileTime, isA<Function>()); }); test('Can instantiate DuplicateHandle', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final DuplicateHandle = kernel32.lookupFunction< Int32 Function( IntPtr hSourceProcessHandle, IntPtr hSourceHandle, IntPtr hTargetProcessHandle, Pointer<IntPtr> lpTargetHandle, Uint32 dwDesiredAccess, Int32 bInheritHandle, Uint32 dwOptions), int Function( int hSourceProcessHandle, int hSourceHandle, int hTargetProcessHandle, Pointer<IntPtr> lpTargetHandle, int dwDesiredAccess, int bInheritHandle, int dwOptions)>('DuplicateHandle'); expect(DuplicateHandle, isA<Function>()); }); test('Can instantiate EndUpdateResource', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final EndUpdateResource = kernel32.lookupFunction< Int32 Function(IntPtr hUpdate, Int32 fDiscard), int Function(int hUpdate, int fDiscard)>('EndUpdateResourceW'); expect(EndUpdateResource, isA<Function>()); }); test('Can instantiate EnumProcesses', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final EnumProcesses = kernel32.lookupFunction< Int32 Function(Pointer<Uint32> lpidProcess, Uint32 cb, Pointer<Uint32> lpcbNeeded), int Function(Pointer<Uint32> lpidProcess, int cb, Pointer<Uint32> lpcbNeeded)>('K32EnumProcesses'); expect(EnumProcesses, isA<Function>()); }); test('Can instantiate EnumProcessModules', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final EnumProcessModules = kernel32.lookupFunction< Int32 Function(IntPtr hProcess, Pointer<IntPtr> lphModule, Uint32 cb, Pointer<Uint32> lpcbNeeded), int Function(int hProcess, Pointer<IntPtr> lphModule, int cb, Pointer<Uint32> lpcbNeeded)>('K32EnumProcessModules'); expect(EnumProcessModules, isA<Function>()); }); test('Can instantiate EnumProcessModulesEx', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final EnumProcessModulesEx = kernel32.lookupFunction< Int32 Function(IntPtr hProcess, Pointer<IntPtr> lphModule, Uint32 cb, Pointer<Uint32> lpcbNeeded, Uint32 dwFilterFlag), int Function( int hProcess, Pointer<IntPtr> lphModule, int cb, Pointer<Uint32> lpcbNeeded, int dwFilterFlag)>('K32EnumProcessModulesEx'); expect(EnumProcessModulesEx, isA<Function>()); }); test('Can instantiate EnumResourceNames', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final EnumResourceNames = kernel32.lookupFunction< Int32 Function( IntPtr hModule, Pointer<Utf16> lpType, Pointer<NativeFunction<EnumResNameProc>> lpEnumFunc, IntPtr lParam), int Function( int hModule, Pointer<Utf16> lpType, Pointer<NativeFunction<EnumResNameProc>> lpEnumFunc, int lParam)>('EnumResourceNamesW'); expect(EnumResourceNames, isA<Function>()); }); test('Can instantiate EnumResourceTypes', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final EnumResourceTypes = kernel32.lookupFunction< Int32 Function( IntPtr hModule, Pointer<NativeFunction<EnumResTypeProc>> lpEnumFunc, IntPtr lParam), int Function( int hModule, Pointer<NativeFunction<EnumResTypeProc>> lpEnumFunc, int lParam)>('EnumResourceTypesW'); expect(EnumResourceTypes, isA<Function>()); }); test('Can instantiate EscapeCommFunction', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final EscapeCommFunction = kernel32.lookupFunction< Int32 Function(IntPtr hFile, Uint32 dwFunc), int Function(int hFile, int dwFunc)>('EscapeCommFunction'); expect(EscapeCommFunction, isA<Function>()); }); test('Can instantiate ExitProcess', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final ExitProcess = kernel32.lookupFunction< Void Function(Uint32 uExitCode), void Function(int uExitCode)>('ExitProcess'); expect(ExitProcess, isA<Function>()); }); test('Can instantiate ExitThread', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final ExitThread = kernel32.lookupFunction< Void Function(Uint32 dwExitCode), void Function(int dwExitCode)>('ExitThread'); expect(ExitThread, isA<Function>()); }); test('Can instantiate FileTimeToDosDateTime', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final FileTimeToDosDateTime = kernel32.lookupFunction< Int32 Function(Pointer<FILETIME> lpFileTime, Pointer<Uint16> lpFatDate, Pointer<Uint16> lpFatTime), int Function(Pointer<FILETIME> lpFileTime, Pointer<Uint16> lpFatDate, Pointer<Uint16> lpFatTime)>('FileTimeToDosDateTime'); expect(FileTimeToDosDateTime, isA<Function>()); }); test('Can instantiate FillConsoleOutputAttribute', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final FillConsoleOutputAttribute = kernel32.lookupFunction< Int32 Function( IntPtr hConsoleOutput, Uint16 wAttribute, Uint32 nLength, COORD dwWriteCoord, Pointer<Uint32> lpNumberOfAttrsWritten), int Function(int hConsoleOutput, int wAttribute, int nLength, COORD dwWriteCoord, Pointer<Uint32> lpNumberOfAttrsWritten)>( 'FillConsoleOutputAttribute'); expect(FillConsoleOutputAttribute, isA<Function>()); }); test('Can instantiate FillConsoleOutputCharacter', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final FillConsoleOutputCharacter = kernel32.lookupFunction< Int32 Function( IntPtr hConsoleOutput, Uint16 cCharacter, Uint32 nLength, COORD dwWriteCoord, Pointer<Uint32> lpNumberOfCharsWritten), int Function(int hConsoleOutput, int cCharacter, int nLength, COORD dwWriteCoord, Pointer<Uint32> lpNumberOfCharsWritten)>( 'FillConsoleOutputCharacterW'); expect(FillConsoleOutputCharacter, isA<Function>()); }); test('Can instantiate FindClose', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final FindClose = kernel32.lookupFunction< Int32 Function(IntPtr hFindFile), int Function(int hFindFile)>('FindClose'); expect(FindClose, isA<Function>()); }); test('Can instantiate FindCloseChangeNotification', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final FindCloseChangeNotification = kernel32.lookupFunction< Int32 Function(IntPtr hChangeHandle), int Function(int hChangeHandle)>('FindCloseChangeNotification'); expect(FindCloseChangeNotification, isA<Function>()); }); test('Can instantiate FindFirstChangeNotification', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final FindFirstChangeNotification = kernel32.lookupFunction< IntPtr Function(Pointer<Utf16> lpPathName, Int32 bWatchSubtree, Uint32 dwNotifyFilter), int Function(Pointer<Utf16> lpPathName, int bWatchSubtree, int dwNotifyFilter)>('FindFirstChangeNotificationW'); expect(FindFirstChangeNotification, isA<Function>()); }); test('Can instantiate FindFirstFile', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final FindFirstFile = kernel32.lookupFunction< IntPtr Function(Pointer<Utf16> lpFileName, Pointer<WIN32_FIND_DATA> lpFindFileData), int Function(Pointer<Utf16> lpFileName, Pointer<WIN32_FIND_DATA> lpFindFileData)>('FindFirstFileW'); expect(FindFirstFile, isA<Function>()); }); test('Can instantiate FindFirstVolume', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final FindFirstVolume = kernel32.lookupFunction< IntPtr Function( Pointer<Utf16> lpszVolumeName, Uint32 cchBufferLength), int Function(Pointer<Utf16> lpszVolumeName, int cchBufferLength)>('FindFirstVolumeW'); expect(FindFirstVolume, isA<Function>()); }); test('Can instantiate FindNextChangeNotification', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final FindNextChangeNotification = kernel32.lookupFunction< Int32 Function(IntPtr hChangeHandle), int Function(int hChangeHandle)>('FindNextChangeNotification'); expect(FindNextChangeNotification, isA<Function>()); }); test('Can instantiate FindNextFile', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final FindNextFile = kernel32.lookupFunction< Int32 Function( IntPtr hFindFile, Pointer<WIN32_FIND_DATA> lpFindFileData), int Function(int hFindFile, Pointer<WIN32_FIND_DATA> lpFindFileData)>('FindNextFileW'); expect(FindNextFile, isA<Function>()); }); test('Can instantiate FindNextVolume', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final FindNextVolume = kernel32.lookupFunction< Int32 Function(IntPtr hFindVolume, Pointer<Utf16> lpszVolumeName, Uint32 cchBufferLength), int Function(int hFindVolume, Pointer<Utf16> lpszVolumeName, int cchBufferLength)>('FindNextVolumeW'); expect(FindNextVolume, isA<Function>()); }); if (windowsBuildNumber >= 9600) { test('Can instantiate FindPackagesByPackageFamily', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final FindPackagesByPackageFamily = kernel32.lookupFunction< Int32 Function( Pointer<Utf16> packageFamilyName, Uint32 packageFilters, Pointer<Uint32> count, Pointer<Pointer<Utf16>> packageFullNames, Pointer<Uint32> bufferLength, Pointer<Utf16> buffer, Pointer<Uint32> packageProperties), int Function( Pointer<Utf16> packageFamilyName, int packageFilters, Pointer<Uint32> count, Pointer<Pointer<Utf16>> packageFullNames, Pointer<Uint32> bufferLength, Pointer<Utf16> buffer, Pointer<Uint32> packageProperties)>( 'FindPackagesByPackageFamily'); expect(FindPackagesByPackageFamily, isA<Function>()); }); } test('Can instantiate FindResource', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final FindResource = kernel32.lookupFunction< IntPtr Function( IntPtr hModule, Pointer<Utf16> lpName, Pointer<Utf16> lpType), int Function(int hModule, Pointer<Utf16> lpName, Pointer<Utf16> lpType)>('FindResourceW'); expect(FindResource, isA<Function>()); }); test('Can instantiate FindResourceEx', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final FindResourceEx = kernel32.lookupFunction< IntPtr Function(IntPtr hModule, Pointer<Utf16> lpType, Pointer<Utf16> lpName, Uint16 wLanguage), int Function(int hModule, Pointer<Utf16> lpType, Pointer<Utf16> lpName, int wLanguage)>('FindResourceExW'); expect(FindResourceEx, isA<Function>()); }); test('Can instantiate FindVolumeClose', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final FindVolumeClose = kernel32.lookupFunction< Int32 Function(IntPtr hFindVolume), int Function(int hFindVolume)>('FindVolumeClose'); expect(FindVolumeClose, isA<Function>()); }); test('Can instantiate FlushConsoleInputBuffer', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final FlushConsoleInputBuffer = kernel32.lookupFunction< Int32 Function(IntPtr hConsoleInput), int Function(int hConsoleInput)>('FlushConsoleInputBuffer'); expect(FlushConsoleInputBuffer, isA<Function>()); }); test('Can instantiate FormatMessage', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final FormatMessage = kernel32.lookupFunction< Uint32 Function( Uint32 dwFlags, Pointer lpSource, Uint32 dwMessageId, Uint32 dwLanguageId, Pointer<Utf16> lpBuffer, Uint32 nSize, Pointer<Pointer<Int8>> Arguments), int Function( int dwFlags, Pointer lpSource, int dwMessageId, int dwLanguageId, Pointer<Utf16> lpBuffer, int nSize, Pointer<Pointer<Int8>> Arguments)>('FormatMessageW'); expect(FormatMessage, isA<Function>()); }); test('Can instantiate FreeConsole', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final FreeConsole = kernel32 .lookupFunction<Int32 Function(), int Function()>('FreeConsole'); expect(FreeConsole, isA<Function>()); }); test('Can instantiate FreeLibrary', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final FreeLibrary = kernel32.lookupFunction< Int32 Function(IntPtr hLibModule), int Function(int hLibModule)>('FreeLibrary'); expect(FreeLibrary, isA<Function>()); }); test('Can instantiate GetActiveProcessorCount', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetActiveProcessorCount = kernel32.lookupFunction< Uint32 Function(Uint16 GroupNumber), int Function(int GroupNumber)>('GetActiveProcessorCount'); expect(GetActiveProcessorCount, isA<Function>()); }); test('Can instantiate GetActiveProcessorGroupCount', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetActiveProcessorGroupCount = kernel32.lookupFunction<Uint16 Function(), int Function()>( 'GetActiveProcessorGroupCount'); expect(GetActiveProcessorGroupCount, isA<Function>()); }); test('Can instantiate GetBinaryType', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetBinaryType = kernel32.lookupFunction< Int32 Function( Pointer<Utf16> lpApplicationName, Pointer<Uint32> lpBinaryType), int Function(Pointer<Utf16> lpApplicationName, Pointer<Uint32> lpBinaryType)>('GetBinaryTypeW'); expect(GetBinaryType, isA<Function>()); }); test('Can instantiate GetCommandLine', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetCommandLine = kernel32.lookupFunction<Pointer<Utf16> Function(), Pointer<Utf16> Function()>('GetCommandLineW'); expect(GetCommandLine, isA<Function>()); }); test('Can instantiate GetCommConfig', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetCommConfig = kernel32.lookupFunction< Int32 Function(IntPtr hCommDev, Pointer<COMMCONFIG> lpCC, Pointer<Uint32> lpdwSize), int Function(int hCommDev, Pointer<COMMCONFIG> lpCC, Pointer<Uint32> lpdwSize)>('GetCommConfig'); expect(GetCommConfig, isA<Function>()); }); test('Can instantiate GetCommMask', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetCommMask = kernel32.lookupFunction< Int32 Function(IntPtr hFile, Pointer<Uint32> lpEvtMask), int Function(int hFile, Pointer<Uint32> lpEvtMask)>('GetCommMask'); expect(GetCommMask, isA<Function>()); }); test('Can instantiate GetCommModemStatus', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetCommModemStatus = kernel32.lookupFunction< Int32 Function(IntPtr hFile, Pointer<Uint32> lpModemStat), int Function( int hFile, Pointer<Uint32> lpModemStat)>('GetCommModemStatus'); expect(GetCommModemStatus, isA<Function>()); }); test('Can instantiate GetCommProperties', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetCommProperties = kernel32.lookupFunction< Int32 Function(IntPtr hFile, Pointer<COMMPROP> lpCommProp), int Function( int hFile, Pointer<COMMPROP> lpCommProp)>('GetCommProperties'); expect(GetCommProperties, isA<Function>()); }); test('Can instantiate GetCommState', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetCommState = kernel32.lookupFunction< Int32 Function(IntPtr hFile, Pointer<DCB> lpDCB), int Function(int hFile, Pointer<DCB> lpDCB)>('GetCommState'); expect(GetCommState, isA<Function>()); }); test('Can instantiate GetCommTimeouts', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetCommTimeouts = kernel32.lookupFunction< Int32 Function(IntPtr hFile, Pointer<COMMTIMEOUTS> lpCommTimeouts), int Function(int hFile, Pointer<COMMTIMEOUTS> lpCommTimeouts)>('GetCommTimeouts'); expect(GetCommTimeouts, isA<Function>()); }); test('Can instantiate GetCompressedFileSize', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetCompressedFileSize = kernel32.lookupFunction< Uint32 Function( Pointer<Utf16> lpFileName, Pointer<Uint32> lpFileSizeHigh), int Function(Pointer<Utf16> lpFileName, Pointer<Uint32> lpFileSizeHigh)>('GetCompressedFileSizeW'); expect(GetCompressedFileSize, isA<Function>()); }); test('Can instantiate GetComputerName', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetComputerName = kernel32.lookupFunction< Int32 Function(Pointer<Utf16> lpBuffer, Pointer<Uint32> nSize), int Function(Pointer<Utf16> lpBuffer, Pointer<Uint32> nSize)>('GetComputerNameW'); expect(GetComputerName, isA<Function>()); }); test('Can instantiate GetComputerNameEx', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetComputerNameEx = kernel32.lookupFunction< Int32 Function( Int32 NameType, Pointer<Utf16> lpBuffer, Pointer<Uint32> nSize), int Function(int NameType, Pointer<Utf16> lpBuffer, Pointer<Uint32> nSize)>('GetComputerNameExW'); expect(GetComputerNameEx, isA<Function>()); }); test('Can instantiate GetConsoleCursorInfo', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetConsoleCursorInfo = kernel32.lookupFunction< Int32 Function(IntPtr hConsoleOutput, Pointer<CONSOLE_CURSOR_INFO> lpConsoleCursorInfo), int Function(int hConsoleOutput, Pointer<CONSOLE_CURSOR_INFO> lpConsoleCursorInfo)>( 'GetConsoleCursorInfo'); expect(GetConsoleCursorInfo, isA<Function>()); }); test('Can instantiate GetConsoleMode', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetConsoleMode = kernel32.lookupFunction< Int32 Function(IntPtr hConsoleHandle, Pointer<Uint32> lpMode), int Function( int hConsoleHandle, Pointer<Uint32> lpMode)>('GetConsoleMode'); expect(GetConsoleMode, isA<Function>()); }); test('Can instantiate GetConsoleScreenBufferInfo', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetConsoleScreenBufferInfo = kernel32.lookupFunction< Int32 Function(IntPtr hConsoleOutput, Pointer<CONSOLE_SCREEN_BUFFER_INFO> lpConsoleScreenBufferInfo), int Function( int hConsoleOutput, Pointer<CONSOLE_SCREEN_BUFFER_INFO> lpConsoleScreenBufferInfo)>('GetConsoleScreenBufferInfo'); expect(GetConsoleScreenBufferInfo, isA<Function>()); }); test('Can instantiate GetConsoleSelectionInfo', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetConsoleSelectionInfo = kernel32.lookupFunction< Int32 Function( Pointer<CONSOLE_SELECTION_INFO> lpConsoleSelectionInfo), int Function( Pointer<CONSOLE_SELECTION_INFO> lpConsoleSelectionInfo)>( 'GetConsoleSelectionInfo'); expect(GetConsoleSelectionInfo, isA<Function>()); }); test('Can instantiate GetConsoleTitle', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetConsoleTitle = kernel32.lookupFunction< Uint32 Function(Pointer<Utf16> lpConsoleTitle, Uint32 nSize), int Function( Pointer<Utf16> lpConsoleTitle, int nSize)>('GetConsoleTitleW'); expect(GetConsoleTitle, isA<Function>()); }); test('Can instantiate GetConsoleWindow', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetConsoleWindow = kernel32.lookupFunction<IntPtr Function(), int Function()>( 'GetConsoleWindow'); expect(GetConsoleWindow, isA<Function>()); }); test('Can instantiate GetCurrentActCtx', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetCurrentActCtx = kernel32.lookupFunction< Int32 Function(Pointer<IntPtr> lphActCtx), int Function(Pointer<IntPtr> lphActCtx)>('GetCurrentActCtx'); expect(GetCurrentActCtx, isA<Function>()); }); test('Can instantiate GetCurrentProcess', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetCurrentProcess = kernel32.lookupFunction<IntPtr Function(), int Function()>( 'GetCurrentProcess'); expect(GetCurrentProcess, isA<Function>()); }); test('Can instantiate GetCurrentProcessId', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetCurrentProcessId = kernel32.lookupFunction<Uint32 Function(), int Function()>( 'GetCurrentProcessId'); expect(GetCurrentProcessId, isA<Function>()); }); test('Can instantiate GetCurrentProcessorNumber', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetCurrentProcessorNumber = kernel32.lookupFunction<Uint32 Function(), int Function()>( 'GetCurrentProcessorNumber'); expect(GetCurrentProcessorNumber, isA<Function>()); }); test('Can instantiate GetCurrentThread', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetCurrentThread = kernel32.lookupFunction<IntPtr Function(), int Function()>( 'GetCurrentThread'); expect(GetCurrentThread, isA<Function>()); }); test('Can instantiate GetCurrentThreadId', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetCurrentThreadId = kernel32.lookupFunction<Uint32 Function(), int Function()>( 'GetCurrentThreadId'); expect(GetCurrentThreadId, isA<Function>()); }); test('Can instantiate GetDefaultCommConfig', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetDefaultCommConfig = kernel32.lookupFunction< Int32 Function(Pointer<Utf16> lpszName, Pointer<COMMCONFIG> lpCC, Pointer<Uint32> lpdwSize), int Function(Pointer<Utf16> lpszName, Pointer<COMMCONFIG> lpCC, Pointer<Uint32> lpdwSize)>('GetDefaultCommConfigW'); expect(GetDefaultCommConfig, isA<Function>()); }); test('Can instantiate GetDiskFreeSpace', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetDiskFreeSpace = kernel32.lookupFunction< Int32 Function( Pointer<Utf16> lpRootPathName, Pointer<Uint32> lpSectorsPerCluster, Pointer<Uint32> lpBytesPerSector, Pointer<Uint32> lpNumberOfFreeClusters, Pointer<Uint32> lpTotalNumberOfClusters), int Function( Pointer<Utf16> lpRootPathName, Pointer<Uint32> lpSectorsPerCluster, Pointer<Uint32> lpBytesPerSector, Pointer<Uint32> lpNumberOfFreeClusters, Pointer<Uint32> lpTotalNumberOfClusters)>('GetDiskFreeSpaceW'); expect(GetDiskFreeSpace, isA<Function>()); }); test('Can instantiate GetDllDirectory', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetDllDirectory = kernel32.lookupFunction< Uint32 Function(Uint32 nBufferLength, Pointer<Utf16> lpBuffer), int Function( int nBufferLength, Pointer<Utf16> lpBuffer)>('GetDllDirectoryW'); expect(GetDllDirectory, isA<Function>()); }); test('Can instantiate GetDriveType', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetDriveType = kernel32.lookupFunction< Uint32 Function(Pointer<Utf16> lpRootPathName), int Function(Pointer<Utf16> lpRootPathName)>('GetDriveTypeW'); expect(GetDriveType, isA<Function>()); }); test('Can instantiate GetExitCodeProcess', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetExitCodeProcess = kernel32.lookupFunction< Int32 Function(IntPtr hProcess, Pointer<Uint32> lpExitCode), int Function( int hProcess, Pointer<Uint32> lpExitCode)>('GetExitCodeProcess'); expect(GetExitCodeProcess, isA<Function>()); }); test('Can instantiate GetFileAttributes', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetFileAttributes = kernel32.lookupFunction< Uint32 Function(Pointer<Utf16> lpFileName), int Function(Pointer<Utf16> lpFileName)>('GetFileAttributesW'); expect(GetFileAttributes, isA<Function>()); }); test('Can instantiate GetFileAttributesEx', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetFileAttributesEx = kernel32.lookupFunction< Int32 Function(Pointer<Utf16> lpFileName, Int32 fInfoLevelId, Pointer lpFileInformation), int Function(Pointer<Utf16> lpFileName, int fInfoLevelId, Pointer lpFileInformation)>('GetFileAttributesExW'); expect(GetFileAttributesEx, isA<Function>()); }); test('Can instantiate GetFileInformationByHandle', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetFileInformationByHandle = kernel32.lookupFunction< Int32 Function(IntPtr hFile, Pointer<BY_HANDLE_FILE_INFORMATION> lpFileInformation), int Function(int hFile, Pointer<BY_HANDLE_FILE_INFORMATION> lpFileInformation)>( 'GetFileInformationByHandle'); expect(GetFileInformationByHandle, isA<Function>()); }); test('Can instantiate GetFileSize', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetFileSize = kernel32.lookupFunction< Uint32 Function(IntPtr hFile, Pointer<Uint32> lpFileSizeHigh), int Function( int hFile, Pointer<Uint32> lpFileSizeHigh)>('GetFileSize'); expect(GetFileSize, isA<Function>()); }); test('Can instantiate GetFileSizeEx', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetFileSizeEx = kernel32.lookupFunction< Int32 Function(IntPtr hFile, Pointer<Int64> lpFileSize), int Function(int hFile, Pointer<Int64> lpFileSize)>('GetFileSizeEx'); expect(GetFileSizeEx, isA<Function>()); }); test('Can instantiate GetFileType', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetFileType = kernel32.lookupFunction<Uint32 Function(IntPtr hFile), int Function(int hFile)>('GetFileType'); expect(GetFileType, isA<Function>()); }); test('Can instantiate GetFinalPathNameByHandle', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetFinalPathNameByHandle = kernel32.lookupFunction< Uint32 Function(IntPtr hFile, Pointer<Utf16> lpszFilePath, Uint32 cchFilePath, Uint32 dwFlags), int Function(int hFile, Pointer<Utf16> lpszFilePath, int cchFilePath, int dwFlags)>('GetFinalPathNameByHandleW'); expect(GetFinalPathNameByHandle, isA<Function>()); }); test('Can instantiate GetFullPathName', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetFullPathName = kernel32.lookupFunction< Uint32 Function(Pointer<Utf16> lpFileName, Uint32 nBufferLength, Pointer<Utf16> lpBuffer, Pointer<Pointer<Utf16>> lpFilePart), int Function( Pointer<Utf16> lpFileName, int nBufferLength, Pointer<Utf16> lpBuffer, Pointer<Pointer<Utf16>> lpFilePart)>('GetFullPathNameW'); expect(GetFullPathName, isA<Function>()); }); test('Can instantiate GetHandleInformation', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetHandleInformation = kernel32.lookupFunction< Int32 Function(IntPtr hObject, Pointer<Uint32> lpdwFlags), int Function( int hObject, Pointer<Uint32> lpdwFlags)>('GetHandleInformation'); expect(GetHandleInformation, isA<Function>()); }); test('Can instantiate GetLargestConsoleWindowSize', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetLargestConsoleWindowSize = kernel32.lookupFunction< COORD Function(IntPtr hConsoleOutput), COORD Function(int hConsoleOutput)>('GetLargestConsoleWindowSize'); expect(GetLargestConsoleWindowSize, isA<Function>()); }); test('Can instantiate GetLastError', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetLastError = kernel32 .lookupFunction<Uint32 Function(), int Function()>('GetLastError'); expect(GetLastError, isA<Function>()); }); test('Can instantiate GetLocaleInfoEx', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetLocaleInfoEx = kernel32.lookupFunction< Int32 Function(Pointer<Utf16> lpLocaleName, Uint32 LCType, Pointer<Utf16> lpLCData, Int32 cchData), int Function(Pointer<Utf16> lpLocaleName, int LCType, Pointer<Utf16> lpLCData, int cchData)>('GetLocaleInfoEx'); expect(GetLocaleInfoEx, isA<Function>()); }); test('Can instantiate GetLocalTime', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetLocalTime = kernel32.lookupFunction< Void Function(Pointer<SYSTEMTIME> lpSystemTime), void Function(Pointer<SYSTEMTIME> lpSystemTime)>('GetLocalTime'); expect(GetLocalTime, isA<Function>()); }); test('Can instantiate GetLogicalDrives', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetLogicalDrives = kernel32.lookupFunction<Uint32 Function(), int Function()>( 'GetLogicalDrives'); expect(GetLogicalDrives, isA<Function>()); }); test('Can instantiate GetLogicalDriveStrings', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetLogicalDriveStrings = kernel32.lookupFunction< Uint32 Function(Uint32 nBufferLength, Pointer<Utf16> lpBuffer), int Function(int nBufferLength, Pointer<Utf16> lpBuffer)>('GetLogicalDriveStringsW'); expect(GetLogicalDriveStrings, isA<Function>()); }); if (windowsBuildNumber >= 22000) { test('Can instantiate GetMachineTypeAttributes', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetMachineTypeAttributes = kernel32.lookupFunction< Int32 Function( Uint16 Machine, Pointer<Uint32> MachineTypeAttributes), int Function( int Machine, Pointer<Uint32> MachineTypeAttributes)>( 'GetMachineTypeAttributes'); expect(GetMachineTypeAttributes, isA<Function>()); }); } test('Can instantiate GetMaximumProcessorCount', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetMaximumProcessorCount = kernel32.lookupFunction< Uint32 Function(Uint16 GroupNumber), int Function(int GroupNumber)>('GetMaximumProcessorCount'); expect(GetMaximumProcessorCount, isA<Function>()); }); test('Can instantiate GetMaximumProcessorGroupCount', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetMaximumProcessorGroupCount = kernel32.lookupFunction<Uint16 Function(), int Function()>( 'GetMaximumProcessorGroupCount'); expect(GetMaximumProcessorGroupCount, isA<Function>()); }); test('Can instantiate GetModuleBaseName', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetModuleBaseName = kernel32.lookupFunction< Uint32 Function(IntPtr hProcess, IntPtr hModule, Pointer<Utf16> lpBaseName, Uint32 nSize), int Function(int hProcess, int hModule, Pointer<Utf16> lpBaseName, int nSize)>('K32GetModuleBaseNameW'); expect(GetModuleBaseName, isA<Function>()); }); test('Can instantiate GetModuleFileName', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetModuleFileName = kernel32.lookupFunction< Uint32 Function( IntPtr hModule, Pointer<Utf16> lpFilename, Uint32 nSize), int Function(int hModule, Pointer<Utf16> lpFilename, int nSize)>('GetModuleFileNameW'); expect(GetModuleFileName, isA<Function>()); }); test('Can instantiate GetModuleFileNameEx', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetModuleFileNameEx = kernel32.lookupFunction< Uint32 Function(IntPtr hProcess, IntPtr hModule, Pointer<Utf16> lpFilename, Uint32 nSize), int Function(int hProcess, int hModule, Pointer<Utf16> lpFilename, int nSize)>('K32GetModuleFileNameExW'); expect(GetModuleFileNameEx, isA<Function>()); }); test('Can instantiate GetModuleHandle', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetModuleHandle = kernel32.lookupFunction< IntPtr Function(Pointer<Utf16> lpModuleName), int Function(Pointer<Utf16> lpModuleName)>('GetModuleHandleW'); expect(GetModuleHandle, isA<Function>()); }); test('Can instantiate GetNamedPipeClientComputerName', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetNamedPipeClientComputerName = kernel32.lookupFunction< Int32 Function(IntPtr Pipe, Pointer<Utf16> ClientComputerName, Uint32 ClientComputerNameLength), int Function(int Pipe, Pointer<Utf16> ClientComputerName, int ClientComputerNameLength)>('GetNamedPipeClientComputerNameW'); expect(GetNamedPipeClientComputerName, isA<Function>()); }); test('Can instantiate GetNamedPipeClientProcessId', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetNamedPipeClientProcessId = kernel32.lookupFunction< Int32 Function(IntPtr Pipe, Pointer<Uint32> ClientProcessId), int Function(int Pipe, Pointer<Uint32> ClientProcessId)>('GetNamedPipeClientProcessId'); expect(GetNamedPipeClientProcessId, isA<Function>()); }); test('Can instantiate GetNamedPipeClientSessionId', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetNamedPipeClientSessionId = kernel32.lookupFunction< Int32 Function(IntPtr Pipe, Pointer<Uint32> ClientSessionId), int Function(int Pipe, Pointer<Uint32> ClientSessionId)>('GetNamedPipeClientSessionId'); expect(GetNamedPipeClientSessionId, isA<Function>()); }); test('Can instantiate GetNamedPipeHandleState', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetNamedPipeHandleState = kernel32.lookupFunction< Int32 Function( IntPtr hNamedPipe, Pointer<Uint32> lpState, Pointer<Uint32> lpCurInstances, Pointer<Uint32> lpMaxCollectionCount, Pointer<Uint32> lpCollectDataTimeout, Pointer<Utf16> lpUserName, Uint32 nMaxUserNameSize), int Function( int hNamedPipe, Pointer<Uint32> lpState, Pointer<Uint32> lpCurInstances, Pointer<Uint32> lpMaxCollectionCount, Pointer<Uint32> lpCollectDataTimeout, Pointer<Utf16> lpUserName, int nMaxUserNameSize)>('GetNamedPipeHandleStateW'); expect(GetNamedPipeHandleState, isA<Function>()); }); test('Can instantiate GetNamedPipeInfo', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetNamedPipeInfo = kernel32.lookupFunction< Int32 Function( IntPtr hNamedPipe, Pointer<Uint32> lpFlags, Pointer<Uint32> lpOutBufferSize, Pointer<Uint32> lpInBufferSize, Pointer<Uint32> lpMaxInstances), int Function( int hNamedPipe, Pointer<Uint32> lpFlags, Pointer<Uint32> lpOutBufferSize, Pointer<Uint32> lpInBufferSize, Pointer<Uint32> lpMaxInstances)>('GetNamedPipeInfo'); expect(GetNamedPipeInfo, isA<Function>()); }); test('Can instantiate GetNativeSystemInfo', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetNativeSystemInfo = kernel32.lookupFunction< Void Function(Pointer<SYSTEM_INFO> lpSystemInfo), void Function( Pointer<SYSTEM_INFO> lpSystemInfo)>('GetNativeSystemInfo'); expect(GetNativeSystemInfo, isA<Function>()); }); test('Can instantiate GetOverlappedResult', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetOverlappedResult = kernel32.lookupFunction< Int32 Function(IntPtr hFile, Pointer<OVERLAPPED> lpOverlapped, Pointer<Uint32> lpNumberOfBytesTransferred, Int32 bWait), int Function( int hFile, Pointer<OVERLAPPED> lpOverlapped, Pointer<Uint32> lpNumberOfBytesTransferred, int bWait)>('GetOverlappedResult'); expect(GetOverlappedResult, isA<Function>()); }); if (windowsBuildNumber >= 9200) { test('Can instantiate GetOverlappedResultEx', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetOverlappedResultEx = kernel32.lookupFunction< Int32 Function( IntPtr hFile, Pointer<OVERLAPPED> lpOverlapped, Pointer<Uint32> lpNumberOfBytesTransferred, Uint32 dwMilliseconds, Int32 bAlertable), int Function( int hFile, Pointer<OVERLAPPED> lpOverlapped, Pointer<Uint32> lpNumberOfBytesTransferred, int dwMilliseconds, int bAlertable)>('GetOverlappedResultEx'); expect(GetOverlappedResultEx, isA<Function>()); }); } test('Can instantiate GetPhysicallyInstalledSystemMemory', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetPhysicallyInstalledSystemMemory = kernel32.lookupFunction< Int32 Function(Pointer<Uint64> TotalMemoryInKilobytes), int Function(Pointer<Uint64> TotalMemoryInKilobytes)>( 'GetPhysicallyInstalledSystemMemory'); expect(GetPhysicallyInstalledSystemMemory, isA<Function>()); }); test('Can instantiate GetProcAddress', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetProcAddress = kernel32.lookupFunction< Pointer Function(IntPtr hModule, Pointer<Utf8> lpProcName), Pointer Function( int hModule, Pointer<Utf8> lpProcName)>('GetProcAddress'); expect(GetProcAddress, isA<Function>()); }); test('Can instantiate GetProcessHeap', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetProcessHeap = kernel32 .lookupFunction<IntPtr Function(), int Function()>('GetProcessHeap'); expect(GetProcessHeap, isA<Function>()); }); test('Can instantiate GetProcessHeaps', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetProcessHeaps = kernel32.lookupFunction< Uint32 Function(Uint32 NumberOfHeaps, Pointer<IntPtr> ProcessHeaps), int Function(int NumberOfHeaps, Pointer<IntPtr> ProcessHeaps)>('GetProcessHeaps'); expect(GetProcessHeaps, isA<Function>()); }); test('Can instantiate GetProcessId', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetProcessId = kernel32.lookupFunction< Uint32 Function(IntPtr Process), int Function(int Process)>('GetProcessId'); expect(GetProcessId, isA<Function>()); }); test('Can instantiate GetProcessShutdownParameters', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetProcessShutdownParameters = kernel32.lookupFunction< Int32 Function(Pointer<Uint32> lpdwLevel, Pointer<Uint32> lpdwFlags), int Function(Pointer<Uint32> lpdwLevel, Pointer<Uint32> lpdwFlags)>('GetProcessShutdownParameters'); expect(GetProcessShutdownParameters, isA<Function>()); }); test('Can instantiate GetProcessVersion', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetProcessVersion = kernel32.lookupFunction< Uint32 Function(Uint32 ProcessId), int Function(int ProcessId)>('GetProcessVersion'); expect(GetProcessVersion, isA<Function>()); }); test('Can instantiate GetProcessWorkingSetSize', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetProcessWorkingSetSize = kernel32.lookupFunction< Int32 Function( IntPtr hProcess, Pointer<IntPtr> lpMinimumWorkingSetSize, Pointer<IntPtr> lpMaximumWorkingSetSize), int Function( int hProcess, Pointer<IntPtr> lpMinimumWorkingSetSize, Pointer<IntPtr> lpMaximumWorkingSetSize)>( 'GetProcessWorkingSetSize'); expect(GetProcessWorkingSetSize, isA<Function>()); }); test('Can instantiate GetProductInfo', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetProductInfo = kernel32.lookupFunction< Int32 Function( Uint32 dwOSMajorVersion, Uint32 dwOSMinorVersion, Uint32 dwSpMajorVersion, Uint32 dwSpMinorVersion, Pointer<Uint32> pdwReturnedProductType), int Function( int dwOSMajorVersion, int dwOSMinorVersion, int dwSpMajorVersion, int dwSpMinorVersion, Pointer<Uint32> pdwReturnedProductType)>('GetProductInfo'); expect(GetProductInfo, isA<Function>()); }); test('Can instantiate GetQueuedCompletionStatus', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetQueuedCompletionStatus = kernel32.lookupFunction< Int32 Function( IntPtr CompletionPort, Pointer<Uint32> lpNumberOfBytesTransferred, Pointer<IntPtr> lpCompletionKey, Pointer<Pointer<OVERLAPPED>> lpOverlapped, Uint32 dwMilliseconds), int Function( int CompletionPort, Pointer<Uint32> lpNumberOfBytesTransferred, Pointer<IntPtr> lpCompletionKey, Pointer<Pointer<OVERLAPPED>> lpOverlapped, int dwMilliseconds)>('GetQueuedCompletionStatus'); expect(GetQueuedCompletionStatus, isA<Function>()); }); test('Can instantiate GetQueuedCompletionStatusEx', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetQueuedCompletionStatusEx = kernel32.lookupFunction< Int32 Function( IntPtr CompletionPort, Pointer<OVERLAPPED_ENTRY> lpCompletionPortEntries, Uint32 ulCount, Pointer<Uint32> ulNumEntriesRemoved, Uint32 dwMilliseconds, Int32 fAlertable), int Function( int CompletionPort, Pointer<OVERLAPPED_ENTRY> lpCompletionPortEntries, int ulCount, Pointer<Uint32> ulNumEntriesRemoved, int dwMilliseconds, int fAlertable)>('GetQueuedCompletionStatusEx'); expect(GetQueuedCompletionStatusEx, isA<Function>()); }); test('Can instantiate GetStartupInfo', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetStartupInfo = kernel32.lookupFunction< Void Function(Pointer<STARTUPINFO> lpStartupInfo), void Function(Pointer<STARTUPINFO> lpStartupInfo)>('GetStartupInfoW'); expect(GetStartupInfo, isA<Function>()); }); test('Can instantiate GetStdHandle', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetStdHandle = kernel32.lookupFunction< IntPtr Function(Uint32 nStdHandle), int Function(int nStdHandle)>('GetStdHandle'); expect(GetStdHandle, isA<Function>()); }); test('Can instantiate GetSystemDefaultLangID', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetSystemDefaultLangID = kernel32.lookupFunction<Uint16 Function(), int Function()>( 'GetSystemDefaultLangID'); expect(GetSystemDefaultLangID, isA<Function>()); }); test('Can instantiate GetSystemDefaultLocaleName', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetSystemDefaultLocaleName = kernel32.lookupFunction< Int32 Function(Pointer<Utf16> lpLocaleName, Int32 cchLocaleName), int Function(Pointer<Utf16> lpLocaleName, int cchLocaleName)>('GetSystemDefaultLocaleName'); expect(GetSystemDefaultLocaleName, isA<Function>()); }); test('Can instantiate GetSystemDirectory', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetSystemDirectory = kernel32.lookupFunction< Uint32 Function(Pointer<Utf16> lpBuffer, Uint32 uSize), int Function( Pointer<Utf16> lpBuffer, int uSize)>('GetSystemDirectoryW'); expect(GetSystemDirectory, isA<Function>()); }); test('Can instantiate GetSystemInfo', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetSystemInfo = kernel32.lookupFunction< Void Function(Pointer<SYSTEM_INFO> lpSystemInfo), void Function(Pointer<SYSTEM_INFO> lpSystemInfo)>('GetSystemInfo'); expect(GetSystemInfo, isA<Function>()); }); test('Can instantiate GetSystemPowerStatus', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetSystemPowerStatus = kernel32.lookupFunction< Int32 Function(Pointer<SYSTEM_POWER_STATUS> lpSystemPowerStatus), int Function(Pointer<SYSTEM_POWER_STATUS> lpSystemPowerStatus)>( 'GetSystemPowerStatus'); expect(GetSystemPowerStatus, isA<Function>()); }); test('Can instantiate GetSystemTime', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetSystemTime = kernel32.lookupFunction< Void Function(Pointer<SYSTEMTIME> lpSystemTime), void Function(Pointer<SYSTEMTIME> lpSystemTime)>('GetSystemTime'); expect(GetSystemTime, isA<Function>()); }); test('Can instantiate GetSystemTimes', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetSystemTimes = kernel32.lookupFunction< Int32 Function(Pointer<FILETIME> lpIdleTime, Pointer<FILETIME> lpKernelTime, Pointer<FILETIME> lpUserTime), int Function( Pointer<FILETIME> lpIdleTime, Pointer<FILETIME> lpKernelTime, Pointer<FILETIME> lpUserTime)>('GetSystemTimes'); expect(GetSystemTimes, isA<Function>()); }); test('Can instantiate GetTempPath', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetTempPath = kernel32.lookupFunction< Uint32 Function(Uint32 nBufferLength, Pointer<Utf16> lpBuffer), int Function( int nBufferLength, Pointer<Utf16> lpBuffer)>('GetTempPathW'); expect(GetTempPath, isA<Function>()); }); test('Can instantiate GetThreadId', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetThreadId = kernel32.lookupFunction< Uint32 Function(IntPtr Thread), int Function(int Thread)>('GetThreadId'); expect(GetThreadId, isA<Function>()); }); test('Can instantiate GetThreadLocale', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetThreadLocale = kernel32 .lookupFunction<Uint32 Function(), int Function()>('GetThreadLocale'); expect(GetThreadLocale, isA<Function>()); }); test('Can instantiate GetThreadTimes', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetThreadTimes = kernel32.lookupFunction< Int32 Function( IntPtr hThread, Pointer<FILETIME> lpCreationTime, Pointer<FILETIME> lpExitTime, Pointer<FILETIME> lpKernelTime, Pointer<FILETIME> lpUserTime), int Function( int hThread, Pointer<FILETIME> lpCreationTime, Pointer<FILETIME> lpExitTime, Pointer<FILETIME> lpKernelTime, Pointer<FILETIME> lpUserTime)>('GetThreadTimes'); expect(GetThreadTimes, isA<Function>()); }); test('Can instantiate GetThreadUILanguage', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetThreadUILanguage = kernel32.lookupFunction<Uint16 Function(), int Function()>( 'GetThreadUILanguage'); expect(GetThreadUILanguage, isA<Function>()); }); test('Can instantiate GetUserDefaultLangID', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetUserDefaultLangID = kernel32.lookupFunction<Uint16 Function(), int Function()>( 'GetUserDefaultLangID'); expect(GetUserDefaultLangID, isA<Function>()); }); test('Can instantiate GetUserDefaultLCID', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetUserDefaultLCID = kernel32.lookupFunction<Uint32 Function(), int Function()>( 'GetUserDefaultLCID'); expect(GetUserDefaultLCID, isA<Function>()); }); test('Can instantiate GetUserDefaultLocaleName', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetUserDefaultLocaleName = kernel32.lookupFunction< Int32 Function(Pointer<Utf16> lpLocaleName, Int32 cchLocaleName), int Function(Pointer<Utf16> lpLocaleName, int cchLocaleName)>('GetUserDefaultLocaleName'); expect(GetUserDefaultLocaleName, isA<Function>()); }); test('Can instantiate GetVersionEx', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetVersionEx = kernel32.lookupFunction< Int32 Function(Pointer<OSVERSIONINFO> lpVersionInformation), int Function( Pointer<OSVERSIONINFO> lpVersionInformation)>('GetVersionExW'); expect(GetVersionEx, isA<Function>()); }); test('Can instantiate GetVolumePathName', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetVolumePathName = kernel32.lookupFunction< Int32 Function(Pointer<Utf16> lpszFileName, Pointer<Utf16> lpszVolumePathName, Uint32 cchBufferLength), int Function( Pointer<Utf16> lpszFileName, Pointer<Utf16> lpszVolumePathName, int cchBufferLength)>('GetVolumePathNameW'); expect(GetVolumePathName, isA<Function>()); }); test('Can instantiate GetVolumePathNamesForVolumeName', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GetVolumePathNamesForVolumeName = kernel32.lookupFunction< Int32 Function( Pointer<Utf16> lpszVolumeName, Pointer<Utf16> lpszVolumePathNames, Uint32 cchBufferLength, Pointer<Uint32> lpcchReturnLength), int Function( Pointer<Utf16> lpszVolumeName, Pointer<Utf16> lpszVolumePathNames, int cchBufferLength, Pointer<Uint32> lpcchReturnLength)>( 'GetVolumePathNamesForVolumeNameW'); expect(GetVolumePathNamesForVolumeName, isA<Function>()); }); test('Can instantiate GlobalAlloc', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GlobalAlloc = kernel32.lookupFunction< IntPtr Function(Uint32 uFlags, IntPtr dwBytes), int Function(int uFlags, int dwBytes)>('GlobalAlloc'); expect(GlobalAlloc, isA<Function>()); }); test('Can instantiate GlobalFree', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GlobalFree = kernel32.lookupFunction<IntPtr Function(IntPtr hMem), int Function(int hMem)>('GlobalFree'); expect(GlobalFree, isA<Function>()); }); test('Can instantiate GlobalLock', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GlobalLock = kernel32.lookupFunction<Pointer Function(IntPtr hMem), Pointer Function(int hMem)>('GlobalLock'); expect(GlobalLock, isA<Function>()); }); test('Can instantiate GlobalSize', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GlobalSize = kernel32.lookupFunction<IntPtr Function(IntPtr hMem), int Function(int hMem)>('GlobalSize'); expect(GlobalSize, isA<Function>()); }); test('Can instantiate GlobalUnlock', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final GlobalUnlock = kernel32.lookupFunction<Int32 Function(IntPtr hMem), int Function(int hMem)>('GlobalUnlock'); expect(GlobalUnlock, isA<Function>()); }); test('Can instantiate HeapAlloc', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final HeapAlloc = kernel32.lookupFunction< Pointer Function(IntPtr hHeap, Uint32 dwFlags, IntPtr dwBytes), Pointer Function(int hHeap, int dwFlags, int dwBytes)>('HeapAlloc'); expect(HeapAlloc, isA<Function>()); }); test('Can instantiate HeapCompact', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final HeapCompact = kernel32.lookupFunction< IntPtr Function(IntPtr hHeap, Uint32 dwFlags), int Function(int hHeap, int dwFlags)>('HeapCompact'); expect(HeapCompact, isA<Function>()); }); test('Can instantiate HeapCreate', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final HeapCreate = kernel32.lookupFunction< IntPtr Function( Uint32 flOptions, IntPtr dwInitialSize, IntPtr dwMaximumSize), int Function(int flOptions, int dwInitialSize, int dwMaximumSize)>('HeapCreate'); expect(HeapCreate, isA<Function>()); }); test('Can instantiate HeapDestroy', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final HeapDestroy = kernel32.lookupFunction<Int32 Function(IntPtr hHeap), int Function(int hHeap)>('HeapDestroy'); expect(HeapDestroy, isA<Function>()); }); test('Can instantiate HeapFree', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final HeapFree = kernel32.lookupFunction< Int32 Function(IntPtr hHeap, Uint32 dwFlags, Pointer lpMem), int Function(int hHeap, int dwFlags, Pointer lpMem)>('HeapFree'); expect(HeapFree, isA<Function>()); }); test('Can instantiate HeapLock', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final HeapLock = kernel32.lookupFunction<Int32 Function(IntPtr hHeap), int Function(int hHeap)>('HeapLock'); expect(HeapLock, isA<Function>()); }); test('Can instantiate HeapQueryInformation', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final HeapQueryInformation = kernel32.lookupFunction< Int32 Function( IntPtr HeapHandle, Int32 HeapInformationClass, Pointer HeapInformation, IntPtr HeapInformationLength, Pointer<IntPtr> ReturnLength), int Function( int HeapHandle, int HeapInformationClass, Pointer HeapInformation, int HeapInformationLength, Pointer<IntPtr> ReturnLength)>('HeapQueryInformation'); expect(HeapQueryInformation, isA<Function>()); }); test('Can instantiate HeapReAlloc', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final HeapReAlloc = kernel32.lookupFunction< Pointer Function( IntPtr hHeap, Uint32 dwFlags, Pointer lpMem, IntPtr dwBytes), Pointer Function(int hHeap, int dwFlags, Pointer lpMem, int dwBytes)>('HeapReAlloc'); expect(HeapReAlloc, isA<Function>()); }); test('Can instantiate HeapSetInformation', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final HeapSetInformation = kernel32.lookupFunction< Int32 Function(IntPtr HeapHandle, Int32 HeapInformationClass, Pointer HeapInformation, IntPtr HeapInformationLength), int Function( int HeapHandle, int HeapInformationClass, Pointer HeapInformation, int HeapInformationLength)>('HeapSetInformation'); expect(HeapSetInformation, isA<Function>()); }); test('Can instantiate HeapSize', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final HeapSize = kernel32.lookupFunction< IntPtr Function(IntPtr hHeap, Uint32 dwFlags, Pointer lpMem), int Function(int hHeap, int dwFlags, Pointer lpMem)>('HeapSize'); expect(HeapSize, isA<Function>()); }); test('Can instantiate HeapUnlock', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final HeapUnlock = kernel32.lookupFunction<Int32 Function(IntPtr hHeap), int Function(int hHeap)>('HeapUnlock'); expect(HeapUnlock, isA<Function>()); }); test('Can instantiate HeapValidate', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final HeapValidate = kernel32.lookupFunction< Int32 Function(IntPtr hHeap, Uint32 dwFlags, Pointer lpMem), int Function(int hHeap, int dwFlags, Pointer lpMem)>('HeapValidate'); expect(HeapValidate, isA<Function>()); }); test('Can instantiate HeapWalk', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final HeapWalk = kernel32.lookupFunction< Int32 Function(IntPtr hHeap, Pointer<PROCESS_HEAP_ENTRY> lpEntry), int Function( int hHeap, Pointer<PROCESS_HEAP_ENTRY> lpEntry)>('HeapWalk'); expect(HeapWalk, isA<Function>()); }); test('Can instantiate InitializeProcThreadAttributeList', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final InitializeProcThreadAttributeList = kernel32.lookupFunction< Int32 Function(Pointer lpAttributeList, Uint32 dwAttributeCount, Uint32 dwFlags, Pointer<IntPtr> lpSize), int Function( Pointer lpAttributeList, int dwAttributeCount, int dwFlags, Pointer<IntPtr> lpSize)>('InitializeProcThreadAttributeList'); expect(InitializeProcThreadAttributeList, isA<Function>()); }); test('Can instantiate IsDebuggerPresent', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final IsDebuggerPresent = kernel32.lookupFunction<Int32 Function(), int Function()>( 'IsDebuggerPresent'); expect(IsDebuggerPresent, isA<Function>()); }); if (windowsBuildNumber >= 9200) { test('Can instantiate IsNativeVhdBoot', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final IsNativeVhdBoot = kernel32.lookupFunction< Int32 Function(Pointer<Int32> NativeVhdBoot), int Function(Pointer<Int32> NativeVhdBoot)>('IsNativeVhdBoot'); expect(IsNativeVhdBoot, isA<Function>()); }); } test('Can instantiate IsSystemResumeAutomatic', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final IsSystemResumeAutomatic = kernel32.lookupFunction<Int32 Function(), int Function()>( 'IsSystemResumeAutomatic'); expect(IsSystemResumeAutomatic, isA<Function>()); }); test('Can instantiate IsValidLocaleName', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final IsValidLocaleName = kernel32.lookupFunction< Int32 Function(Pointer<Utf16> lpLocaleName), int Function(Pointer<Utf16> lpLocaleName)>('IsValidLocaleName'); expect(IsValidLocaleName, isA<Function>()); }); if (windowsBuildNumber >= 16299) { test('Can instantiate IsWow64Process2', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final IsWow64Process2 = kernel32.lookupFunction< Int32 Function(IntPtr hProcess, Pointer<Uint16> pProcessMachine, Pointer<Uint16> pNativeMachine), int Function(int hProcess, Pointer<Uint16> pProcessMachine, Pointer<Uint16> pNativeMachine)>('IsWow64Process2'); expect(IsWow64Process2, isA<Function>()); }); } test('Can instantiate LoadLibrary', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final LoadLibrary = kernel32.lookupFunction< IntPtr Function(Pointer<Utf16> lpLibFileName), int Function(Pointer<Utf16> lpLibFileName)>('LoadLibraryW'); expect(LoadLibrary, isA<Function>()); }); test('Can instantiate LoadResource', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final LoadResource = kernel32.lookupFunction< IntPtr Function(IntPtr hModule, IntPtr hResInfo), int Function(int hModule, int hResInfo)>('LoadResource'); expect(LoadResource, isA<Function>()); }); test('Can instantiate LocalFree', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final LocalFree = kernel32.lookupFunction<IntPtr Function(IntPtr hMem), int Function(int hMem)>('LocalFree'); expect(LocalFree, isA<Function>()); }); test('Can instantiate LockResource', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final LockResource = kernel32.lookupFunction< Pointer Function(IntPtr hResData), Pointer Function(int hResData)>('LockResource'); expect(LockResource, isA<Function>()); }); test('Can instantiate MoveFile', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final MoveFile = kernel32.lookupFunction< Int32 Function( Pointer<Utf16> lpExistingFileName, Pointer<Utf16> lpNewFileName), int Function(Pointer<Utf16> lpExistingFileName, Pointer<Utf16> lpNewFileName)>('MoveFileW'); expect(MoveFile, isA<Function>()); }); test('Can instantiate OpenEvent', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final OpenEvent = kernel32.lookupFunction< IntPtr Function(Uint32 dwDesiredAccess, Int32 bInheritHandle, Pointer<Utf16> lpName), int Function(int dwDesiredAccess, int bInheritHandle, Pointer<Utf16> lpName)>('OpenEventW'); expect(OpenEvent, isA<Function>()); }); test('Can instantiate OpenProcess', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final OpenProcess = kernel32.lookupFunction< IntPtr Function( Uint32 dwDesiredAccess, Int32 bInheritHandle, Uint32 dwProcessId), int Function(int dwDesiredAccess, int bInheritHandle, int dwProcessId)>('OpenProcess'); expect(OpenProcess, isA<Function>()); }); test('Can instantiate OutputDebugString', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final OutputDebugString = kernel32.lookupFunction< Void Function(Pointer<Utf16> lpOutputString), void Function(Pointer<Utf16> lpOutputString)>('OutputDebugStringW'); expect(OutputDebugString, isA<Function>()); }); if (windowsBuildNumber >= 9200) { test('Can instantiate PackageFamilyNameFromFullName', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final PackageFamilyNameFromFullName = kernel32.lookupFunction< Int32 Function( Pointer<Utf16> packageFullName, Pointer<Uint32> packageFamilyNameLength, Pointer<Utf16> packageFamilyName), int Function( Pointer<Utf16> packageFullName, Pointer<Uint32> packageFamilyNameLength, Pointer<Utf16> packageFamilyName)>( 'PackageFamilyNameFromFullName'); expect(PackageFamilyNameFromFullName, isA<Function>()); }); } test('Can instantiate PeekNamedPipe', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final PeekNamedPipe = kernel32.lookupFunction< Int32 Function( IntPtr hNamedPipe, Pointer lpBuffer, Uint32 nBufferSize, Pointer<Uint32> lpBytesRead, Pointer<Uint32> lpTotalBytesAvail, Pointer<Uint32> lpBytesLeftThisMessage), int Function( int hNamedPipe, Pointer lpBuffer, int nBufferSize, Pointer<Uint32> lpBytesRead, Pointer<Uint32> lpTotalBytesAvail, Pointer<Uint32> lpBytesLeftThisMessage)>('PeekNamedPipe'); expect(PeekNamedPipe, isA<Function>()); }); test('Can instantiate PostQueuedCompletionStatus', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final PostQueuedCompletionStatus = kernel32.lookupFunction< Int32 Function( IntPtr CompletionPort, Uint32 dwNumberOfBytesTransferred, IntPtr dwCompletionKey, Pointer<OVERLAPPED> lpOverlapped), int Function( int CompletionPort, int dwNumberOfBytesTransferred, int dwCompletionKey, Pointer<OVERLAPPED> lpOverlapped)>('PostQueuedCompletionStatus'); expect(PostQueuedCompletionStatus, isA<Function>()); }); test('Can instantiate PurgeComm', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final PurgeComm = kernel32.lookupFunction< Int32 Function(IntPtr hFile, Uint32 dwFlags), int Function(int hFile, int dwFlags)>('PurgeComm'); expect(PurgeComm, isA<Function>()); }); test('Can instantiate QueryDosDevice', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final QueryDosDevice = kernel32.lookupFunction< Uint32 Function(Pointer<Utf16> lpDeviceName, Pointer<Utf16> lpTargetPath, Uint32 ucchMax), int Function(Pointer<Utf16> lpDeviceName, Pointer<Utf16> lpTargetPath, int ucchMax)>('QueryDosDeviceW'); expect(QueryDosDevice, isA<Function>()); }); test('Can instantiate QueryPerformanceCounter', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final QueryPerformanceCounter = kernel32.lookupFunction< Int32 Function(Pointer<Int64> lpPerformanceCount), int Function( Pointer<Int64> lpPerformanceCount)>('QueryPerformanceCounter'); expect(QueryPerformanceCounter, isA<Function>()); }); test('Can instantiate QueryPerformanceFrequency', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final QueryPerformanceFrequency = kernel32.lookupFunction< Int32 Function(Pointer<Int64> lpFrequency), int Function( Pointer<Int64> lpFrequency)>('QueryPerformanceFrequency'); expect(QueryPerformanceFrequency, isA<Function>()); }); test('Can instantiate ReadConsole', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final ReadConsole = kernel32.lookupFunction< Int32 Function( IntPtr hConsoleInput, Pointer lpBuffer, Uint32 nNumberOfCharsToRead, Pointer<Uint32> lpNumberOfCharsRead, Pointer<CONSOLE_READCONSOLE_CONTROL> pInputControl), int Function( int hConsoleInput, Pointer lpBuffer, int nNumberOfCharsToRead, Pointer<Uint32> lpNumberOfCharsRead, Pointer<CONSOLE_READCONSOLE_CONTROL> pInputControl)>( 'ReadConsoleW'); expect(ReadConsole, isA<Function>()); }); test('Can instantiate ReadFile', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final ReadFile = kernel32.lookupFunction< Int32 Function( IntPtr hFile, Pointer lpBuffer, Uint32 nNumberOfBytesToRead, Pointer<Uint32> lpNumberOfBytesRead, Pointer<OVERLAPPED> lpOverlapped), int Function( int hFile, Pointer lpBuffer, int nNumberOfBytesToRead, Pointer<Uint32> lpNumberOfBytesRead, Pointer<OVERLAPPED> lpOverlapped)>('ReadFile'); expect(ReadFile, isA<Function>()); }); test('Can instantiate ReadProcessMemory', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final ReadProcessMemory = kernel32.lookupFunction< Int32 Function( IntPtr hProcess, Pointer lpBaseAddress, Pointer lpBuffer, IntPtr nSize, Pointer<IntPtr> lpNumberOfBytesRead), int Function( int hProcess, Pointer lpBaseAddress, Pointer lpBuffer, int nSize, Pointer<IntPtr> lpNumberOfBytesRead)>('ReadProcessMemory'); expect(ReadProcessMemory, isA<Function>()); }); test('Can instantiate ReleaseActCtx', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final ReleaseActCtx = kernel32.lookupFunction< Void Function(IntPtr hActCtx), void Function(int hActCtx)>('ReleaseActCtx'); expect(ReleaseActCtx, isA<Function>()); }); test('Can instantiate RemoveDirectory', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final RemoveDirectory = kernel32.lookupFunction< Int32 Function(Pointer<Utf16> lpPathName), int Function(Pointer<Utf16> lpPathName)>('RemoveDirectoryW'); expect(RemoveDirectory, isA<Function>()); }); test('Can instantiate ReOpenFile', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final ReOpenFile = kernel32.lookupFunction< IntPtr Function(IntPtr hOriginalFile, Uint32 dwDesiredAccess, Uint32 dwShareMode, Uint32 dwFlagsAndAttributes), int Function(int hOriginalFile, int dwDesiredAccess, int dwShareMode, int dwFlagsAndAttributes)>('ReOpenFile'); expect(ReOpenFile, isA<Function>()); }); test('Can instantiate ResetEvent', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final ResetEvent = kernel32.lookupFunction<Int32 Function(IntPtr hEvent), int Function(int hEvent)>('ResetEvent'); expect(ResetEvent, isA<Function>()); }); if (windowsBuildNumber >= 17763) { test('Can instantiate ResizePseudoConsole', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final ResizePseudoConsole = kernel32.lookupFunction< Int32 Function(IntPtr hPC, COORD size), int Function(int hPC, COORD size)>('ResizePseudoConsole'); expect(ResizePseudoConsole, isA<Function>()); }); } test('Can instantiate ScrollConsoleScreenBuffer', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final ScrollConsoleScreenBuffer = kernel32.lookupFunction< Int32 Function( IntPtr hConsoleOutput, Pointer<SMALL_RECT> lpScrollRectangle, Pointer<SMALL_RECT> lpClipRectangle, COORD dwDestinationOrigin, Pointer<CHAR_INFO> lpFill), int Function( int hConsoleOutput, Pointer<SMALL_RECT> lpScrollRectangle, Pointer<SMALL_RECT> lpClipRectangle, COORD dwDestinationOrigin, Pointer<CHAR_INFO> lpFill)>('ScrollConsoleScreenBufferW'); expect(ScrollConsoleScreenBuffer, isA<Function>()); }); test('Can instantiate SetCommBreak', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final SetCommBreak = kernel32.lookupFunction<Int32 Function(IntPtr hFile), int Function(int hFile)>('SetCommBreak'); expect(SetCommBreak, isA<Function>()); }); test('Can instantiate SetCommConfig', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final SetCommConfig = kernel32.lookupFunction< Int32 Function( IntPtr hCommDev, Pointer<COMMCONFIG> lpCC, Uint32 dwSize), int Function(int hCommDev, Pointer<COMMCONFIG> lpCC, int dwSize)>('SetCommConfig'); expect(SetCommConfig, isA<Function>()); }); test('Can instantiate SetCommMask', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final SetCommMask = kernel32.lookupFunction< Int32 Function(IntPtr hFile, Uint32 dwEvtMask), int Function(int hFile, int dwEvtMask)>('SetCommMask'); expect(SetCommMask, isA<Function>()); }); test('Can instantiate SetCommState', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final SetCommState = kernel32.lookupFunction< Int32 Function(IntPtr hFile, Pointer<DCB> lpDCB), int Function(int hFile, Pointer<DCB> lpDCB)>('SetCommState'); expect(SetCommState, isA<Function>()); }); test('Can instantiate SetCommTimeouts', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final SetCommTimeouts = kernel32.lookupFunction< Int32 Function(IntPtr hFile, Pointer<COMMTIMEOUTS> lpCommTimeouts), int Function(int hFile, Pointer<COMMTIMEOUTS> lpCommTimeouts)>('SetCommTimeouts'); expect(SetCommTimeouts, isA<Function>()); }); test('Can instantiate SetConsoleCtrlHandler', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final SetConsoleCtrlHandler = kernel32.lookupFunction< Int32 Function(Pointer<NativeFunction<HandlerRoutine>> HandlerRoutine, Int32 Add), int Function(Pointer<NativeFunction<HandlerRoutine>> HandlerRoutine, int Add)>('SetConsoleCtrlHandler'); expect(SetConsoleCtrlHandler, isA<Function>()); }); test('Can instantiate SetConsoleCursorInfo', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final SetConsoleCursorInfo = kernel32.lookupFunction< Int32 Function(IntPtr hConsoleOutput, Pointer<CONSOLE_CURSOR_INFO> lpConsoleCursorInfo), int Function(int hConsoleOutput, Pointer<CONSOLE_CURSOR_INFO> lpConsoleCursorInfo)>( 'SetConsoleCursorInfo'); expect(SetConsoleCursorInfo, isA<Function>()); }); test('Can instantiate SetConsoleCursorPosition', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final SetConsoleCursorPosition = kernel32.lookupFunction< Int32 Function(IntPtr hConsoleOutput, COORD dwCursorPosition), int Function(int hConsoleOutput, COORD dwCursorPosition)>('SetConsoleCursorPosition'); expect(SetConsoleCursorPosition, isA<Function>()); }); test('Can instantiate SetConsoleDisplayMode', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final SetConsoleDisplayMode = kernel32.lookupFunction< Int32 Function(IntPtr hConsoleOutput, Uint32 dwFlags, Pointer<COORD> lpNewScreenBufferDimensions), int Function(int hConsoleOutput, int dwFlags, Pointer<COORD> lpNewScreenBufferDimensions)>( 'SetConsoleDisplayMode'); expect(SetConsoleDisplayMode, isA<Function>()); }); test('Can instantiate SetConsoleMode', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final SetConsoleMode = kernel32.lookupFunction< Int32 Function(IntPtr hConsoleHandle, Uint32 dwMode), int Function(int hConsoleHandle, int dwMode)>('SetConsoleMode'); expect(SetConsoleMode, isA<Function>()); }); test('Can instantiate SetConsoleTextAttribute', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final SetConsoleTextAttribute = kernel32.lookupFunction< Int32 Function(IntPtr hConsoleOutput, Uint16 wAttributes), int Function( int hConsoleOutput, int wAttributes)>('SetConsoleTextAttribute'); expect(SetConsoleTextAttribute, isA<Function>()); }); test('Can instantiate SetConsoleWindowInfo', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final SetConsoleWindowInfo = kernel32.lookupFunction< Int32 Function(IntPtr hConsoleOutput, Int32 bAbsolute, Pointer<SMALL_RECT> lpConsoleWindow), int Function(int hConsoleOutput, int bAbsolute, Pointer<SMALL_RECT> lpConsoleWindow)>('SetConsoleWindowInfo'); expect(SetConsoleWindowInfo, isA<Function>()); }); test('Can instantiate SetCurrentDirectory', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final SetCurrentDirectory = kernel32.lookupFunction< Int32 Function(Pointer<Utf16> lpPathName), int Function(Pointer<Utf16> lpPathName)>('SetCurrentDirectoryW'); expect(SetCurrentDirectory, isA<Function>()); }); test('Can instantiate SetDefaultCommConfig', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final SetDefaultCommConfig = kernel32.lookupFunction< Int32 Function( Pointer<Utf16> lpszName, Pointer<COMMCONFIG> lpCC, Uint32 dwSize), int Function(Pointer<Utf16> lpszName, Pointer<COMMCONFIG> lpCC, int dwSize)>('SetDefaultCommConfigW'); expect(SetDefaultCommConfig, isA<Function>()); }); test('Can instantiate SetFilePointer', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final SetFilePointer = kernel32.lookupFunction< Uint32 Function(IntPtr hFile, Int32 lDistanceToMove, Pointer<Int32> lpDistanceToMoveHigh, Uint32 dwMoveMethod), int Function( int hFile, int lDistanceToMove, Pointer<Int32> lpDistanceToMoveHigh, int dwMoveMethod)>('SetFilePointer'); expect(SetFilePointer, isA<Function>()); }); test('Can instantiate SetFilePointerEx', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final SetFilePointerEx = kernel32.lookupFunction< Int32 Function(IntPtr hFile, Int64 liDistanceToMove, Pointer<Int64> lpNewFilePointer, Uint32 dwMoveMethod), int Function( int hFile, int liDistanceToMove, Pointer<Int64> lpNewFilePointer, int dwMoveMethod)>('SetFilePointerEx'); expect(SetFilePointerEx, isA<Function>()); }); test('Can instantiate SetFileShortName', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final SetFileShortName = kernel32.lookupFunction< Int32 Function(IntPtr hFile, Pointer<Utf16> lpShortName), int Function( int hFile, Pointer<Utf16> lpShortName)>('SetFileShortNameW'); expect(SetFileShortName, isA<Function>()); }); test('Can instantiate SetFirmwareEnvironmentVariable', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final SetFirmwareEnvironmentVariable = kernel32.lookupFunction< Int32 Function(Pointer<Utf16> lpName, Pointer<Utf16> lpGuid, Pointer pValue, Uint32 nSize), int Function(Pointer<Utf16> lpName, Pointer<Utf16> lpGuid, Pointer pValue, int nSize)>('SetFirmwareEnvironmentVariableW'); expect(SetFirmwareEnvironmentVariable, isA<Function>()); }); if (windowsBuildNumber >= 9200) { test('Can instantiate SetFirmwareEnvironmentVariableEx', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final SetFirmwareEnvironmentVariableEx = kernel32.lookupFunction< Int32 Function(Pointer<Utf16> lpName, Pointer<Utf16> lpGuid, Pointer pValue, Uint32 nSize, Uint32 dwAttributes), int Function( Pointer<Utf16> lpName, Pointer<Utf16> lpGuid, Pointer pValue, int nSize, int dwAttributes)>('SetFirmwareEnvironmentVariableExW'); expect(SetFirmwareEnvironmentVariableEx, isA<Function>()); }); } test('Can instantiate SetHandleInformation', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final SetHandleInformation = kernel32.lookupFunction< Int32 Function(IntPtr hObject, Uint32 dwMask, Uint32 dwFlags), int Function( int hObject, int dwMask, int dwFlags)>('SetHandleInformation'); expect(SetHandleInformation, isA<Function>()); }); test('Can instantiate SetNamedPipeHandleState', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final SetNamedPipeHandleState = kernel32.lookupFunction< Int32 Function( IntPtr hNamedPipe, Pointer<Uint32> lpMode, Pointer<Uint32> lpMaxCollectionCount, Pointer<Uint32> lpCollectDataTimeout), int Function( int hNamedPipe, Pointer<Uint32> lpMode, Pointer<Uint32> lpMaxCollectionCount, Pointer<Uint32> lpCollectDataTimeout)>('SetNamedPipeHandleState'); expect(SetNamedPipeHandleState, isA<Function>()); }); test('Can instantiate SetProcessAffinityMask', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final SetProcessAffinityMask = kernel32.lookupFunction< Int32 Function(IntPtr hProcess, IntPtr dwProcessAffinityMask), int Function(int hProcess, int dwProcessAffinityMask)>('SetProcessAffinityMask'); expect(SetProcessAffinityMask, isA<Function>()); }); test('Can instantiate SetProcessPriorityBoost', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final SetProcessPriorityBoost = kernel32.lookupFunction< Int32 Function(IntPtr hProcess, Int32 bDisablePriorityBoost), int Function(int hProcess, int bDisablePriorityBoost)>('SetProcessPriorityBoost'); expect(SetProcessPriorityBoost, isA<Function>()); }); test('Can instantiate SetProcessWorkingSetSize', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final SetProcessWorkingSetSize = kernel32.lookupFunction< Int32 Function(IntPtr hProcess, IntPtr dwMinimumWorkingSetSize, IntPtr dwMaximumWorkingSetSize), int Function(int hProcess, int dwMinimumWorkingSetSize, int dwMaximumWorkingSetSize)>('SetProcessWorkingSetSize'); expect(SetProcessWorkingSetSize, isA<Function>()); }); test('Can instantiate SetStdHandle', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final SetStdHandle = kernel32.lookupFunction< Int32 Function(Uint32 nStdHandle, IntPtr hHandle), int Function(int nStdHandle, int hHandle)>('SetStdHandle'); expect(SetStdHandle, isA<Function>()); }); test('Can instantiate SetThreadAffinityMask', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final SetThreadAffinityMask = kernel32.lookupFunction< IntPtr Function(IntPtr hThread, IntPtr dwThreadAffinityMask), int Function( int hThread, int dwThreadAffinityMask)>('SetThreadAffinityMask'); expect(SetThreadAffinityMask, isA<Function>()); }); test('Can instantiate SetThreadExecutionState', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final SetThreadExecutionState = kernel32.lookupFunction< Uint32 Function(Uint32 esFlags), int Function(int esFlags)>('SetThreadExecutionState'); expect(SetThreadExecutionState, isA<Function>()); }); test('Can instantiate SetThreadUILanguage', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final SetThreadUILanguage = kernel32.lookupFunction< Uint16 Function(Uint16 LangId), int Function(int LangId)>('SetThreadUILanguage'); expect(SetThreadUILanguage, isA<Function>()); }); test('Can instantiate SetupComm', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final SetupComm = kernel32.lookupFunction< Int32 Function(IntPtr hFile, Uint32 dwInQueue, Uint32 dwOutQueue), int Function(int hFile, int dwInQueue, int dwOutQueue)>('SetupComm'); expect(SetupComm, isA<Function>()); }); test('Can instantiate SetVolumeLabel', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final SetVolumeLabel = kernel32.lookupFunction< Int32 Function( Pointer<Utf16> lpRootPathName, Pointer<Utf16> lpVolumeName), int Function(Pointer<Utf16> lpRootPathName, Pointer<Utf16> lpVolumeName)>('SetVolumeLabelW'); expect(SetVolumeLabel, isA<Function>()); }); test('Can instantiate Sleep', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final Sleep = kernel32.lookupFunction< Void Function(Uint32 dwMilliseconds), void Function(int dwMilliseconds)>('Sleep'); expect(Sleep, isA<Function>()); }); test('Can instantiate SleepEx', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final SleepEx = kernel32.lookupFunction< Uint32 Function(Uint32 dwMilliseconds, Int32 bAlertable), int Function(int dwMilliseconds, int bAlertable)>('SleepEx'); expect(SleepEx, isA<Function>()); }); test('Can instantiate TerminateProcess', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final TerminateProcess = kernel32.lookupFunction< Int32 Function(IntPtr hProcess, Uint32 uExitCode), int Function(int hProcess, int uExitCode)>('TerminateProcess'); expect(TerminateProcess, isA<Function>()); }); test('Can instantiate TerminateThread', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final TerminateThread = kernel32.lookupFunction< Int32 Function(IntPtr hThread, Uint32 dwExitCode), int Function(int hThread, int dwExitCode)>('TerminateThread'); expect(TerminateThread, isA<Function>()); }); test('Can instantiate TransactNamedPipe', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final TransactNamedPipe = kernel32.lookupFunction< Int32 Function( IntPtr hNamedPipe, Pointer lpInBuffer, Uint32 nInBufferSize, Pointer lpOutBuffer, Uint32 nOutBufferSize, Pointer<Uint32> lpBytesRead, Pointer<OVERLAPPED> lpOverlapped), int Function( int hNamedPipe, Pointer lpInBuffer, int nInBufferSize, Pointer lpOutBuffer, int nOutBufferSize, Pointer<Uint32> lpBytesRead, Pointer<OVERLAPPED> lpOverlapped)>('TransactNamedPipe'); expect(TransactNamedPipe, isA<Function>()); }); test('Can instantiate TransmitCommChar', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final TransmitCommChar = kernel32.lookupFunction< Int32 Function(IntPtr hFile, Uint8 cChar), int Function(int hFile, int cChar)>('TransmitCommChar'); expect(TransmitCommChar, isA<Function>()); }); test('Can instantiate UpdateProcThreadAttribute', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final UpdateProcThreadAttribute = kernel32.lookupFunction< Int32 Function( Pointer lpAttributeList, Uint32 dwFlags, IntPtr Attribute, Pointer lpValue, IntPtr cbSize, Pointer lpPreviousValue, Pointer<IntPtr> lpReturnSize), int Function( Pointer lpAttributeList, int dwFlags, int Attribute, Pointer lpValue, int cbSize, Pointer lpPreviousValue, Pointer<IntPtr> lpReturnSize)>('UpdateProcThreadAttribute'); expect(UpdateProcThreadAttribute, isA<Function>()); }); test('Can instantiate UpdateResource', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final UpdateResource = kernel32.lookupFunction< Int32 Function( IntPtr hUpdate, Pointer<Utf16> lpType, Pointer<Utf16> lpName, Uint16 wLanguage, Pointer lpData, Uint32 cb), int Function( int hUpdate, Pointer<Utf16> lpType, Pointer<Utf16> lpName, int wLanguage, Pointer lpData, int cb)>('UpdateResourceW'); expect(UpdateResource, isA<Function>()); }); test('Can instantiate VerLanguageName', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final VerLanguageName = kernel32.lookupFunction< Uint32 Function(Uint32 wLang, Pointer<Utf16> szLang, Uint32 cchLang), int Function(int wLang, Pointer<Utf16> szLang, int cchLang)>('VerLanguageNameW'); expect(VerLanguageName, isA<Function>()); }); test('Can instantiate VirtualAlloc', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final VirtualAlloc = kernel32.lookupFunction< Pointer Function(Pointer lpAddress, IntPtr dwSize, Uint32 flAllocationType, Uint32 flProtect), Pointer Function(Pointer lpAddress, int dwSize, int flAllocationType, int flProtect)>('VirtualAlloc'); expect(VirtualAlloc, isA<Function>()); }); test('Can instantiate VirtualAllocEx', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final VirtualAllocEx = kernel32.lookupFunction< Pointer Function(IntPtr hProcess, Pointer lpAddress, IntPtr dwSize, Uint32 flAllocationType, Uint32 flProtect), Pointer Function(int hProcess, Pointer lpAddress, int dwSize, int flAllocationType, int flProtect)>('VirtualAllocEx'); expect(VirtualAllocEx, isA<Function>()); }); test('Can instantiate VirtualFree', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final VirtualFree = kernel32.lookupFunction< Int32 Function(Pointer lpAddress, IntPtr dwSize, Uint32 dwFreeType), int Function( Pointer lpAddress, int dwSize, int dwFreeType)>('VirtualFree'); expect(VirtualFree, isA<Function>()); }); test('Can instantiate VirtualFreeEx', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final VirtualFreeEx = kernel32.lookupFunction< Int32 Function(IntPtr hProcess, Pointer lpAddress, IntPtr dwSize, Uint32 dwFreeType), int Function(int hProcess, Pointer lpAddress, int dwSize, int dwFreeType)>('VirtualFreeEx'); expect(VirtualFreeEx, isA<Function>()); }); test('Can instantiate VirtualLock', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final VirtualLock = kernel32.lookupFunction< Int32 Function(Pointer lpAddress, IntPtr dwSize), int Function(Pointer lpAddress, int dwSize)>('VirtualLock'); expect(VirtualLock, isA<Function>()); }); test('Can instantiate VirtualUnlock', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final VirtualUnlock = kernel32.lookupFunction< Int32 Function(Pointer lpAddress, IntPtr dwSize), int Function(Pointer lpAddress, int dwSize)>('VirtualUnlock'); expect(VirtualUnlock, isA<Function>()); }); test('Can instantiate WaitCommEvent', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final WaitCommEvent = kernel32.lookupFunction< Int32 Function(IntPtr hFile, Pointer<Uint32> lpEvtMask, Pointer<OVERLAPPED> lpOverlapped), int Function(int hFile, Pointer<Uint32> lpEvtMask, Pointer<OVERLAPPED> lpOverlapped)>('WaitCommEvent'); expect(WaitCommEvent, isA<Function>()); }); test('Can instantiate WaitForSingleObject', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final WaitForSingleObject = kernel32.lookupFunction< Uint32 Function(IntPtr hHandle, Uint32 dwMilliseconds), int Function(int hHandle, int dwMilliseconds)>('WaitForSingleObject'); expect(WaitForSingleObject, isA<Function>()); }); test('Can instantiate WideCharToMultiByte', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final WideCharToMultiByte = kernel32.lookupFunction< Int32 Function( Uint32 CodePage, Uint32 dwFlags, Pointer<Utf16> lpWideCharStr, Int32 cchWideChar, Pointer<Utf8> lpMultiByteStr, Int32 cbMultiByte, Pointer<Utf8> lpDefaultChar, Pointer<Int32> lpUsedDefaultChar), int Function( int CodePage, int dwFlags, Pointer<Utf16> lpWideCharStr, int cchWideChar, Pointer<Utf8> lpMultiByteStr, int cbMultiByte, Pointer<Utf8> lpDefaultChar, Pointer<Int32> lpUsedDefaultChar)>('WideCharToMultiByte'); expect(WideCharToMultiByte, isA<Function>()); }); test('Can instantiate Wow64SuspendThread', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final Wow64SuspendThread = kernel32.lookupFunction< Uint32 Function(IntPtr hThread), int Function(int hThread)>('Wow64SuspendThread'); expect(Wow64SuspendThread, isA<Function>()); }); test('Can instantiate WriteConsole', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final WriteConsole = kernel32.lookupFunction< Int32 Function( IntPtr hConsoleOutput, Pointer lpBuffer, Uint32 nNumberOfCharsToWrite, Pointer<Uint32> lpNumberOfCharsWritten, Pointer lpReserved), int Function( int hConsoleOutput, Pointer lpBuffer, int nNumberOfCharsToWrite, Pointer<Uint32> lpNumberOfCharsWritten, Pointer lpReserved)>('WriteConsoleW'); expect(WriteConsole, isA<Function>()); }); test('Can instantiate WriteFile', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final WriteFile = kernel32.lookupFunction< Int32 Function( IntPtr hFile, Pointer lpBuffer, Uint32 nNumberOfBytesToWrite, Pointer<Uint32> lpNumberOfBytesWritten, Pointer<OVERLAPPED> lpOverlapped), int Function( int hFile, Pointer lpBuffer, int nNumberOfBytesToWrite, Pointer<Uint32> lpNumberOfBytesWritten, Pointer<OVERLAPPED> lpOverlapped)>('WriteFile'); expect(WriteFile, isA<Function>()); }); test('Can instantiate WriteProcessMemory', () { final kernel32 = DynamicLibrary.open('kernel32.dll'); final WriteProcessMemory = kernel32.lookupFunction< Int32 Function( IntPtr hProcess, Pointer lpBaseAddress, Pointer lpBuffer, IntPtr nSize, Pointer<IntPtr> lpNumberOfBytesWritten), int Function( int hProcess, Pointer lpBaseAddress, Pointer lpBuffer, int nSize, Pointer<IntPtr> lpNumberOfBytesWritten)>('WriteProcessMemory'); expect(WriteProcessMemory, isA<Function>()); }); }); group('Test user32 functions', () { test('Can instantiate ActivateKeyboardLayout', () { final user32 = DynamicLibrary.open('user32.dll'); final ActivateKeyboardLayout = user32.lookupFunction< IntPtr Function(IntPtr hkl, Uint32 Flags), int Function(int hkl, int Flags)>('ActivateKeyboardLayout'); expect(ActivateKeyboardLayout, isA<Function>()); }); test('Can instantiate AddClipboardFormatListener', () { final user32 = DynamicLibrary.open('user32.dll'); final AddClipboardFormatListener = user32.lookupFunction< Int32 Function(IntPtr hwnd), int Function(int hwnd)>('AddClipboardFormatListener'); expect(AddClipboardFormatListener, isA<Function>()); }); test('Can instantiate AdjustWindowRect', () { final user32 = DynamicLibrary.open('user32.dll'); final AdjustWindowRect = user32.lookupFunction< Int32 Function(Pointer<RECT> lpRect, Uint32 dwStyle, Int32 bMenu), int Function(Pointer<RECT> lpRect, int dwStyle, int bMenu)>('AdjustWindowRect'); expect(AdjustWindowRect, isA<Function>()); }); test('Can instantiate AdjustWindowRectEx', () { final user32 = DynamicLibrary.open('user32.dll'); final AdjustWindowRectEx = user32.lookupFunction< Int32 Function(Pointer<RECT> lpRect, Uint32 dwStyle, Int32 bMenu, Uint32 dwExStyle), int Function(Pointer<RECT> lpRect, int dwStyle, int bMenu, int dwExStyle)>('AdjustWindowRectEx'); expect(AdjustWindowRectEx, isA<Function>()); }); if (windowsBuildNumber >= 14393) { test('Can instantiate AdjustWindowRectExForDpi', () { final user32 = DynamicLibrary.open('user32.dll'); final AdjustWindowRectExForDpi = user32.lookupFunction< Int32 Function(Pointer<RECT> lpRect, Uint32 dwStyle, Int32 bMenu, Uint32 dwExStyle, Uint32 dpi), int Function(Pointer<RECT> lpRect, int dwStyle, int bMenu, int dwExStyle, int dpi)>('AdjustWindowRectExForDpi'); expect(AdjustWindowRectExForDpi, isA<Function>()); }); } test('Can instantiate AllowSetForegroundWindow', () { final user32 = DynamicLibrary.open('user32.dll'); final AllowSetForegroundWindow = user32.lookupFunction< Int32 Function(Uint32 dwProcessId), int Function(int dwProcessId)>('AllowSetForegroundWindow'); expect(AllowSetForegroundWindow, isA<Function>()); }); test('Can instantiate AnimateWindow', () { final user32 = DynamicLibrary.open('user32.dll'); final AnimateWindow = user32.lookupFunction< Int32 Function(IntPtr hWnd, Uint32 dwTime, Uint32 dwFlags), int Function(int hWnd, int dwTime, int dwFlags)>('AnimateWindow'); expect(AnimateWindow, isA<Function>()); }); test('Can instantiate AnyPopup', () { final user32 = DynamicLibrary.open('user32.dll'); final AnyPopup = user32.lookupFunction<Int32 Function(), int Function()>('AnyPopup'); expect(AnyPopup, isA<Function>()); }); test('Can instantiate AppendMenu', () { final user32 = DynamicLibrary.open('user32.dll'); final AppendMenu = user32.lookupFunction< Int32 Function(IntPtr hMenu, Uint32 uFlags, IntPtr uIDNewItem, Pointer<Utf16> lpNewItem), int Function(int hMenu, int uFlags, int uIDNewItem, Pointer<Utf16> lpNewItem)>('AppendMenuW'); expect(AppendMenu, isA<Function>()); }); if (windowsBuildNumber >= 14393) { test('Can instantiate AreDpiAwarenessContextsEqual', () { final user32 = DynamicLibrary.open('user32.dll'); final AreDpiAwarenessContextsEqual = user32.lookupFunction< Int32 Function(IntPtr dpiContextA, IntPtr dpiContextB), int Function(int dpiContextA, int dpiContextB)>('AreDpiAwarenessContextsEqual'); expect(AreDpiAwarenessContextsEqual, isA<Function>()); }); } test('Can instantiate ArrangeIconicWindows', () { final user32 = DynamicLibrary.open('user32.dll'); final ArrangeIconicWindows = user32.lookupFunction< Uint32 Function(IntPtr hWnd), int Function(int hWnd)>('ArrangeIconicWindows'); expect(ArrangeIconicWindows, isA<Function>()); }); test('Can instantiate AttachThreadInput', () { final user32 = DynamicLibrary.open('user32.dll'); final AttachThreadInput = user32.lookupFunction< Int32 Function(Uint32 idAttach, Uint32 idAttachTo, Int32 fAttach), int Function( int idAttach, int idAttachTo, int fAttach)>('AttachThreadInput'); expect(AttachThreadInput, isA<Function>()); }); test('Can instantiate BeginDeferWindowPos', () { final user32 = DynamicLibrary.open('user32.dll'); final BeginDeferWindowPos = user32.lookupFunction< IntPtr Function(Int32 nNumWindows), int Function(int nNumWindows)>('BeginDeferWindowPos'); expect(BeginDeferWindowPos, isA<Function>()); }); test('Can instantiate BeginPaint', () { final user32 = DynamicLibrary.open('user32.dll'); final BeginPaint = user32.lookupFunction< IntPtr Function(IntPtr hWnd, Pointer<PAINTSTRUCT> lpPaint), int Function(int hWnd, Pointer<PAINTSTRUCT> lpPaint)>('BeginPaint'); expect(BeginPaint, isA<Function>()); }); test('Can instantiate BlockInput', () { final user32 = DynamicLibrary.open('user32.dll'); final BlockInput = user32.lookupFunction<Int32 Function(Int32 fBlockIt), int Function(int fBlockIt)>('BlockInput'); expect(BlockInput, isA<Function>()); }); test('Can instantiate BringWindowToTop', () { final user32 = DynamicLibrary.open('user32.dll'); final BringWindowToTop = user32.lookupFunction< Int32 Function(IntPtr hWnd), int Function(int hWnd)>('BringWindowToTop'); expect(BringWindowToTop, isA<Function>()); }); test('Can instantiate BroadcastSystemMessage', () { final user32 = DynamicLibrary.open('user32.dll'); final BroadcastSystemMessage = user32.lookupFunction< Int32 Function(Uint32 flags, Pointer<Uint32> lpInfo, Uint32 Msg, IntPtr wParam, IntPtr lParam), int Function(int flags, Pointer<Uint32> lpInfo, int Msg, int wParam, int lParam)>('BroadcastSystemMessageW'); expect(BroadcastSystemMessage, isA<Function>()); }); test('Can instantiate BroadcastSystemMessageEx', () { final user32 = DynamicLibrary.open('user32.dll'); final BroadcastSystemMessageEx = user32.lookupFunction< Int32 Function(Uint32 flags, Pointer<Uint32> lpInfo, Uint32 Msg, IntPtr wParam, IntPtr lParam, Pointer<BSMINFO> pbsmInfo), int Function( int flags, Pointer<Uint32> lpInfo, int Msg, int wParam, int lParam, Pointer<BSMINFO> pbsmInfo)>('BroadcastSystemMessageExW'); expect(BroadcastSystemMessageEx, isA<Function>()); }); test('Can instantiate CalculatePopupWindowPosition', () { final user32 = DynamicLibrary.open('user32.dll'); final CalculatePopupWindowPosition = user32.lookupFunction< Int32 Function( Pointer<POINT> anchorPoint, Pointer<SIZE> windowSize, Uint32 flags, Pointer<RECT> excludeRect, Pointer<RECT> popupWindowPosition), int Function( Pointer<POINT> anchorPoint, Pointer<SIZE> windowSize, int flags, Pointer<RECT> excludeRect, Pointer<RECT> popupWindowPosition)>( 'CalculatePopupWindowPosition'); expect(CalculatePopupWindowPosition, isA<Function>()); }); test('Can instantiate CallMsgFilter', () { final user32 = DynamicLibrary.open('user32.dll'); final CallMsgFilter = user32.lookupFunction< Int32 Function(Pointer<MSG> lpMsg, Int32 nCode), int Function(Pointer<MSG> lpMsg, int nCode)>('CallMsgFilterW'); expect(CallMsgFilter, isA<Function>()); }); test('Can instantiate CallNextHookEx', () { final user32 = DynamicLibrary.open('user32.dll'); final CallNextHookEx = user32.lookupFunction< IntPtr Function( IntPtr hhk, Int32 nCode, IntPtr wParam, IntPtr lParam), int Function( int hhk, int nCode, int wParam, int lParam)>('CallNextHookEx'); expect(CallNextHookEx, isA<Function>()); }); test('Can instantiate CallWindowProc', () { final user32 = DynamicLibrary.open('user32.dll'); final CallWindowProc = user32.lookupFunction< IntPtr Function(Pointer<NativeFunction<WindowProc>> lpPrevWndFunc, IntPtr hWnd, Uint32 Msg, IntPtr wParam, IntPtr lParam), int Function(Pointer<NativeFunction<WindowProc>> lpPrevWndFunc, int hWnd, int Msg, int wParam, int lParam)>('CallWindowProcW'); expect(CallWindowProc, isA<Function>()); }); test('Can instantiate CascadeWindows', () { final user32 = DynamicLibrary.open('user32.dll'); final CascadeWindows = user32.lookupFunction< Uint16 Function(IntPtr hwndParent, Uint32 wHow, Pointer<RECT> lpRect, Uint32 cKids, Pointer<IntPtr> lpKids), int Function(int hwndParent, int wHow, Pointer<RECT> lpRect, int cKids, Pointer<IntPtr> lpKids)>('CascadeWindows'); expect(CascadeWindows, isA<Function>()); }); test('Can instantiate ChangeClipboardChain', () { final user32 = DynamicLibrary.open('user32.dll'); final ChangeClipboardChain = user32.lookupFunction< Int32 Function(IntPtr hWndRemove, IntPtr hWndNewNext), int Function( int hWndRemove, int hWndNewNext)>('ChangeClipboardChain'); expect(ChangeClipboardChain, isA<Function>()); }); test('Can instantiate ChangeDisplaySettings', () { final user32 = DynamicLibrary.open('user32.dll'); final ChangeDisplaySettings = user32.lookupFunction< Int32 Function(Pointer<DEVMODE> lpDevMode, Uint32 dwFlags), int Function(Pointer<DEVMODE> lpDevMode, int dwFlags)>('ChangeDisplaySettingsW'); expect(ChangeDisplaySettings, isA<Function>()); }); test('Can instantiate ChangeDisplaySettingsEx', () { final user32 = DynamicLibrary.open('user32.dll'); final ChangeDisplaySettingsEx = user32.lookupFunction< Int32 Function( Pointer<Utf16> lpszDeviceName, Pointer<DEVMODE> lpDevMode, IntPtr hwnd, Uint32 dwflags, Pointer lParam), int Function( Pointer<Utf16> lpszDeviceName, Pointer<DEVMODE> lpDevMode, int hwnd, int dwflags, Pointer lParam)>('ChangeDisplaySettingsExW'); expect(ChangeDisplaySettingsEx, isA<Function>()); }); test('Can instantiate ChangeWindowMessageFilter', () { final user32 = DynamicLibrary.open('user32.dll'); final ChangeWindowMessageFilter = user32.lookupFunction< Int32 Function(Uint32 message, Uint32 dwFlag), int Function(int message, int dwFlag)>('ChangeWindowMessageFilter'); expect(ChangeWindowMessageFilter, isA<Function>()); }); test('Can instantiate ChangeWindowMessageFilterEx', () { final user32 = DynamicLibrary.open('user32.dll'); final ChangeWindowMessageFilterEx = user32.lookupFunction< Int32 Function(IntPtr hwnd, Uint32 message, Uint32 action, Pointer<CHANGEFILTERSTRUCT> pChangeFilterStruct), int Function(int hwnd, int message, int action, Pointer<CHANGEFILTERSTRUCT> pChangeFilterStruct)>( 'ChangeWindowMessageFilterEx'); expect(ChangeWindowMessageFilterEx, isA<Function>()); }); test('Can instantiate CheckDlgButton', () { final user32 = DynamicLibrary.open('user32.dll'); final CheckDlgButton = user32.lookupFunction< Int32 Function(IntPtr hDlg, Int32 nIDButton, Uint32 uCheck), int Function(int hDlg, int nIDButton, int uCheck)>('CheckDlgButton'); expect(CheckDlgButton, isA<Function>()); }); test('Can instantiate CheckRadioButton', () { final user32 = DynamicLibrary.open('user32.dll'); final CheckRadioButton = user32.lookupFunction< Int32 Function(IntPtr hDlg, Int32 nIDFirstButton, Int32 nIDLastButton, Int32 nIDCheckButton), int Function(int hDlg, int nIDFirstButton, int nIDLastButton, int nIDCheckButton)>('CheckRadioButton'); expect(CheckRadioButton, isA<Function>()); }); test('Can instantiate ChildWindowFromPoint', () { final user32 = DynamicLibrary.open('user32.dll'); final ChildWindowFromPoint = user32.lookupFunction< IntPtr Function(IntPtr hWndParent, POINT Point), int Function(int hWndParent, POINT Point)>('ChildWindowFromPoint'); expect(ChildWindowFromPoint, isA<Function>()); }); test('Can instantiate ChildWindowFromPointEx', () { final user32 = DynamicLibrary.open('user32.dll'); final ChildWindowFromPointEx = user32.lookupFunction< IntPtr Function(IntPtr hwnd, POINT pt, Uint32 flags), int Function( int hwnd, POINT pt, int flags)>('ChildWindowFromPointEx'); expect(ChildWindowFromPointEx, isA<Function>()); }); test('Can instantiate ClientToScreen', () { final user32 = DynamicLibrary.open('user32.dll'); final ClientToScreen = user32.lookupFunction< Int32 Function(IntPtr hWnd, Pointer<POINT> lpPoint), int Function(int hWnd, Pointer<POINT> lpPoint)>('ClientToScreen'); expect(ClientToScreen, isA<Function>()); }); test('Can instantiate ClipCursor', () { final user32 = DynamicLibrary.open('user32.dll'); final ClipCursor = user32.lookupFunction< Int32 Function(Pointer<RECT> lpRect), int Function(Pointer<RECT> lpRect)>('ClipCursor'); expect(ClipCursor, isA<Function>()); }); test('Can instantiate CloseClipboard', () { final user32 = DynamicLibrary.open('user32.dll'); final CloseClipboard = user32 .lookupFunction<Int32 Function(), int Function()>('CloseClipboard'); expect(CloseClipboard, isA<Function>()); }); test('Can instantiate CloseGestureInfoHandle', () { final user32 = DynamicLibrary.open('user32.dll'); final CloseGestureInfoHandle = user32.lookupFunction< Int32 Function(IntPtr hGestureInfo), int Function(int hGestureInfo)>('CloseGestureInfoHandle'); expect(CloseGestureInfoHandle, isA<Function>()); }); test('Can instantiate CloseTouchInputHandle', () { final user32 = DynamicLibrary.open('user32.dll'); final CloseTouchInputHandle = user32.lookupFunction< Int32 Function(IntPtr hTouchInput), int Function(int hTouchInput)>('CloseTouchInputHandle'); expect(CloseTouchInputHandle, isA<Function>()); }); test('Can instantiate CloseWindow', () { final user32 = DynamicLibrary.open('user32.dll'); final CloseWindow = user32.lookupFunction<Int32 Function(IntPtr hWnd), int Function(int hWnd)>('CloseWindow'); expect(CloseWindow, isA<Function>()); }); test('Can instantiate CopyAcceleratorTable', () { final user32 = DynamicLibrary.open('user32.dll'); final CopyAcceleratorTable = user32.lookupFunction< Int32 Function( IntPtr hAccelSrc, Pointer<ACCEL> lpAccelDst, Int32 cAccelEntries), int Function(int hAccelSrc, Pointer<ACCEL> lpAccelDst, int cAccelEntries)>('CopyAcceleratorTableW'); expect(CopyAcceleratorTable, isA<Function>()); }); test('Can instantiate CopyIcon', () { final user32 = DynamicLibrary.open('user32.dll'); final CopyIcon = user32.lookupFunction<IntPtr Function(IntPtr hIcon), int Function(int hIcon)>('CopyIcon'); expect(CopyIcon, isA<Function>()); }); test('Can instantiate CopyImage', () { final user32 = DynamicLibrary.open('user32.dll'); final CopyImage = user32.lookupFunction< IntPtr Function( IntPtr h, Uint32 type, Int32 cx, Int32 cy, Uint32 flags), int Function( int h, int type, int cx, int cy, int flags)>('CopyImage'); expect(CopyImage, isA<Function>()); }); test('Can instantiate CopyRect', () { final user32 = DynamicLibrary.open('user32.dll'); final CopyRect = user32.lookupFunction< Int32 Function(Pointer<RECT> lprcDst, Pointer<RECT> lprcSrc), int Function( Pointer<RECT> lprcDst, Pointer<RECT> lprcSrc)>('CopyRect'); expect(CopyRect, isA<Function>()); }); test('Can instantiate CountClipboardFormats', () { final user32 = DynamicLibrary.open('user32.dll'); final CountClipboardFormats = user32.lookupFunction<Int32 Function(), int Function()>( 'CountClipboardFormats'); expect(CountClipboardFormats, isA<Function>()); }); test('Can instantiate CreateAcceleratorTable', () { final user32 = DynamicLibrary.open('user32.dll'); final CreateAcceleratorTable = user32.lookupFunction< IntPtr Function(Pointer<ACCEL> paccel, Int32 cAccel), int Function( Pointer<ACCEL> paccel, int cAccel)>('CreateAcceleratorTableW'); expect(CreateAcceleratorTable, isA<Function>()); }); test('Can instantiate CreateDesktop', () { final user32 = DynamicLibrary.open('user32.dll'); final CreateDesktop = user32.lookupFunction< IntPtr Function( Pointer<Utf16> lpszDesktop, Pointer<Utf16> lpszDevice, Pointer<DEVMODE> pDevmode, Uint32 dwFlags, Uint32 dwDesiredAccess, Pointer<SECURITY_ATTRIBUTES> lpsa), int Function( Pointer<Utf16> lpszDesktop, Pointer<Utf16> lpszDevice, Pointer<DEVMODE> pDevmode, int dwFlags, int dwDesiredAccess, Pointer<SECURITY_ATTRIBUTES> lpsa)>('CreateDesktopW'); expect(CreateDesktop, isA<Function>()); }); test('Can instantiate CreateDesktopEx', () { final user32 = DynamicLibrary.open('user32.dll'); final CreateDesktopEx = user32.lookupFunction< IntPtr Function( Pointer<Utf16> lpszDesktop, Pointer<Utf16> lpszDevice, Pointer<DEVMODE> pDevmode, Uint32 dwFlags, Uint32 dwDesiredAccess, Pointer<SECURITY_ATTRIBUTES> lpsa, Uint32 ulHeapSize, Pointer pvoid), int Function( Pointer<Utf16> lpszDesktop, Pointer<Utf16> lpszDevice, Pointer<DEVMODE> pDevmode, int dwFlags, int dwDesiredAccess, Pointer<SECURITY_ATTRIBUTES> lpsa, int ulHeapSize, Pointer pvoid)>('CreateDesktopExW'); expect(CreateDesktopEx, isA<Function>()); }); test('Can instantiate CreateDialogIndirectParam', () { final user32 = DynamicLibrary.open('user32.dll'); final CreateDialogIndirectParam = user32.lookupFunction< IntPtr Function( IntPtr hInstance, Pointer<DLGTEMPLATE> lpTemplate, IntPtr hWndParent, Pointer<NativeFunction<DlgProc>> lpDialogFunc, IntPtr dwInitParam), int Function( int hInstance, Pointer<DLGTEMPLATE> lpTemplate, int hWndParent, Pointer<NativeFunction<DlgProc>> lpDialogFunc, int dwInitParam)>('CreateDialogIndirectParamW'); expect(CreateDialogIndirectParam, isA<Function>()); }); test('Can instantiate CreateMDIWindow', () { final user32 = DynamicLibrary.open('user32.dll'); final CreateMDIWindow = user32.lookupFunction< IntPtr Function( Pointer<Utf16> lpClassName, Pointer<Utf16> lpWindowName, Uint32 dwStyle, Int32 X, Int32 Y, Int32 nWidth, Int32 nHeight, IntPtr hWndParent, IntPtr hInstance, IntPtr lParam), int Function( Pointer<Utf16> lpClassName, Pointer<Utf16> lpWindowName, int dwStyle, int X, int Y, int nWidth, int nHeight, int hWndParent, int hInstance, int lParam)>('CreateMDIWindowW'); expect(CreateMDIWindow, isA<Function>()); }); test('Can instantiate CreateMenu', () { final user32 = DynamicLibrary.open('user32.dll'); final CreateMenu = user32 .lookupFunction<IntPtr Function(), int Function()>('CreateMenu'); expect(CreateMenu, isA<Function>()); }); test('Can instantiate CreateWindowEx', () { final user32 = DynamicLibrary.open('user32.dll'); final CreateWindowEx = user32.lookupFunction< IntPtr Function( Uint32 dwExStyle, Pointer<Utf16> lpClassName, Pointer<Utf16> lpWindowName, Uint32 dwStyle, Int32 X, Int32 Y, Int32 nWidth, Int32 nHeight, IntPtr hWndParent, IntPtr hMenu, IntPtr hInstance, Pointer lpParam), int Function( int dwExStyle, Pointer<Utf16> lpClassName, Pointer<Utf16> lpWindowName, int dwStyle, int X, int Y, int nWidth, int nHeight, int hWndParent, int hMenu, int hInstance, Pointer lpParam)>('CreateWindowExW'); expect(CreateWindowEx, isA<Function>()); }); test('Can instantiate CreateWindowStation', () { final user32 = DynamicLibrary.open('user32.dll'); final CreateWindowStation = user32.lookupFunction< IntPtr Function(Pointer<Utf16> lpwinsta, Uint32 dwFlags, Uint32 dwDesiredAccess, Pointer<SECURITY_ATTRIBUTES> lpsa), int Function( Pointer<Utf16> lpwinsta, int dwFlags, int dwDesiredAccess, Pointer<SECURITY_ATTRIBUTES> lpsa)>('CreateWindowStationW'); expect(CreateWindowStation, isA<Function>()); }); test('Can instantiate DeferWindowPos', () { final user32 = DynamicLibrary.open('user32.dll'); final DeferWindowPos = user32.lookupFunction< IntPtr Function( IntPtr hWinPosInfo, IntPtr hWnd, IntPtr hWndInsertAfter, Int32 x, Int32 y, Int32 cx, Int32 cy, Uint32 uFlags), int Function(int hWinPosInfo, int hWnd, int hWndInsertAfter, int x, int y, int cx, int cy, int uFlags)>('DeferWindowPos'); expect(DeferWindowPos, isA<Function>()); }); test('Can instantiate DefMDIChildProc', () { final user32 = DynamicLibrary.open('user32.dll'); final DefMDIChildProc = user32.lookupFunction< IntPtr Function( IntPtr hWnd, Uint32 uMsg, IntPtr wParam, IntPtr lParam), int Function( int hWnd, int uMsg, int wParam, int lParam)>('DefMDIChildProcW'); expect(DefMDIChildProc, isA<Function>()); }); test('Can instantiate DefRawInputProc', () { final user32 = DynamicLibrary.open('user32.dll'); final DefRawInputProc = user32.lookupFunction< IntPtr Function(Pointer<Pointer<RAWINPUT>> paRawInput, Int32 nInput, Uint32 cbSizeHeader), int Function(Pointer<Pointer<RAWINPUT>> paRawInput, int nInput, int cbSizeHeader)>('DefRawInputProc'); expect(DefRawInputProc, isA<Function>()); }); test('Can instantiate DefWindowProc', () { final user32 = DynamicLibrary.open('user32.dll'); final DefWindowProc = user32.lookupFunction< IntPtr Function( IntPtr hWnd, Uint32 Msg, IntPtr wParam, IntPtr lParam), int Function( int hWnd, int Msg, int wParam, int lParam)>('DefWindowProcW'); expect(DefWindowProc, isA<Function>()); }); test('Can instantiate DeleteMenu', () { final user32 = DynamicLibrary.open('user32.dll'); final DeleteMenu = user32.lookupFunction< Int32 Function(IntPtr hMenu, Uint32 uPosition, Uint32 uFlags), int Function(int hMenu, int uPosition, int uFlags)>('DeleteMenu'); expect(DeleteMenu, isA<Function>()); }); test('Can instantiate DestroyCursor', () { final user32 = DynamicLibrary.open('user32.dll'); final DestroyCursor = user32.lookupFunction< Int32 Function(IntPtr hCursor), int Function(int hCursor)>('DestroyCursor'); expect(DestroyCursor, isA<Function>()); }); test('Can instantiate DestroyIcon', () { final user32 = DynamicLibrary.open('user32.dll'); final DestroyIcon = user32.lookupFunction<Int32 Function(IntPtr hIcon), int Function(int hIcon)>('DestroyIcon'); expect(DestroyIcon, isA<Function>()); }); test('Can instantiate DestroyMenu', () { final user32 = DynamicLibrary.open('user32.dll'); final DestroyMenu = user32.lookupFunction<Int32 Function(IntPtr hMenu), int Function(int hMenu)>('DestroyMenu'); expect(DestroyMenu, isA<Function>()); }); test('Can instantiate DestroyWindow', () { final user32 = DynamicLibrary.open('user32.dll'); final DestroyWindow = user32.lookupFunction<Int32 Function(IntPtr hWnd), int Function(int hWnd)>('DestroyWindow'); expect(DestroyWindow, isA<Function>()); }); test('Can instantiate DialogBoxIndirectParam', () { final user32 = DynamicLibrary.open('user32.dll'); final DialogBoxIndirectParam = user32.lookupFunction< IntPtr Function( IntPtr hInstance, Pointer<DLGTEMPLATE> hDialogTemplate, IntPtr hWndParent, Pointer<NativeFunction<DlgProc>> lpDialogFunc, IntPtr dwInitParam), int Function( int hInstance, Pointer<DLGTEMPLATE> hDialogTemplate, int hWndParent, Pointer<NativeFunction<DlgProc>> lpDialogFunc, int dwInitParam)>('DialogBoxIndirectParamW'); expect(DialogBoxIndirectParam, isA<Function>()); }); test('Can instantiate DisableProcessWindowsGhosting', () { final user32 = DynamicLibrary.open('user32.dll'); final DisableProcessWindowsGhosting = user32.lookupFunction<Void Function(), void Function()>( 'DisableProcessWindowsGhosting'); expect(DisableProcessWindowsGhosting, isA<Function>()); }); test('Can instantiate DispatchMessage', () { final user32 = DynamicLibrary.open('user32.dll'); final DispatchMessage = user32.lookupFunction< IntPtr Function(Pointer<MSG> lpMsg), int Function(Pointer<MSG> lpMsg)>('DispatchMessageW'); expect(DispatchMessage, isA<Function>()); }); test('Can instantiate DragDetect', () { final user32 = DynamicLibrary.open('user32.dll'); final DragDetect = user32.lookupFunction< Int32 Function(IntPtr hwnd, POINT pt), int Function(int hwnd, POINT pt)>('DragDetect'); expect(DragDetect, isA<Function>()); }); test('Can instantiate DrawAnimatedRects', () { final user32 = DynamicLibrary.open('user32.dll'); final DrawAnimatedRects = user32.lookupFunction< Int32 Function(IntPtr hwnd, Int32 idAni, Pointer<RECT> lprcFrom, Pointer<RECT> lprcTo), int Function(int hwnd, int idAni, Pointer<RECT> lprcFrom, Pointer<RECT> lprcTo)>('DrawAnimatedRects'); expect(DrawAnimatedRects, isA<Function>()); }); test('Can instantiate DrawCaption', () { final user32 = DynamicLibrary.open('user32.dll'); final DrawCaption = user32.lookupFunction< Int32 Function( IntPtr hwnd, IntPtr hdc, Pointer<RECT> lprect, Uint32 flags), int Function(int hwnd, int hdc, Pointer<RECT> lprect, int flags)>('DrawCaption'); expect(DrawCaption, isA<Function>()); }); test('Can instantiate DrawEdge', () { final user32 = DynamicLibrary.open('user32.dll'); final DrawEdge = user32.lookupFunction< Int32 Function( IntPtr hdc, Pointer<RECT> qrc, Uint32 edge, Uint32 grfFlags), int Function( int hdc, Pointer<RECT> qrc, int edge, int grfFlags)>('DrawEdge'); expect(DrawEdge, isA<Function>()); }); test('Can instantiate DrawFocusRect', () { final user32 = DynamicLibrary.open('user32.dll'); final DrawFocusRect = user32.lookupFunction< Int32 Function(IntPtr hDC, Pointer<RECT> lprc), int Function(int hDC, Pointer<RECT> lprc)>('DrawFocusRect'); expect(DrawFocusRect, isA<Function>()); }); test('Can instantiate DrawFrameControl', () { final user32 = DynamicLibrary.open('user32.dll'); final DrawFrameControl = user32.lookupFunction< Int32 Function(IntPtr param0, Pointer<RECT> param1, Uint32 param2, Uint32 param3), int Function(int param0, Pointer<RECT> param1, int param2, int param3)>('DrawFrameControl'); expect(DrawFrameControl, isA<Function>()); }); test('Can instantiate DrawIcon', () { final user32 = DynamicLibrary.open('user32.dll'); final DrawIcon = user32.lookupFunction< Int32 Function(IntPtr hDC, Int32 X, Int32 Y, IntPtr hIcon), int Function(int hDC, int X, int Y, int hIcon)>('DrawIcon'); expect(DrawIcon, isA<Function>()); }); test('Can instantiate DrawState', () { final user32 = DynamicLibrary.open('user32.dll'); final DrawState = user32.lookupFunction< Int32 Function( IntPtr hdc, IntPtr hbrFore, Pointer<NativeFunction<DrawStateProc>> qfnCallBack, IntPtr lData, IntPtr wData, Int32 x, Int32 y, Int32 cx, Int32 cy, Uint32 uFlags), int Function( int hdc, int hbrFore, Pointer<NativeFunction<DrawStateProc>> qfnCallBack, int lData, int wData, int x, int y, int cx, int cy, int uFlags)>('DrawStateW'); expect(DrawState, isA<Function>()); }); test('Can instantiate DrawText', () { final user32 = DynamicLibrary.open('user32.dll'); final DrawText = user32.lookupFunction< Int32 Function(IntPtr hdc, Pointer<Utf16> lpchText, Int32 cchText, Pointer<RECT> lprc, Uint32 format), int Function(int hdc, Pointer<Utf16> lpchText, int cchText, Pointer<RECT> lprc, int format)>('DrawTextW'); expect(DrawText, isA<Function>()); }); test('Can instantiate DrawTextEx', () { final user32 = DynamicLibrary.open('user32.dll'); final DrawTextEx = user32.lookupFunction< Int32 Function(IntPtr hdc, Pointer<Utf16> lpchText, Int32 cchText, Pointer<RECT> lprc, Uint32 format, Pointer<DRAWTEXTPARAMS> lpdtp), int Function( int hdc, Pointer<Utf16> lpchText, int cchText, Pointer<RECT> lprc, int format, Pointer<DRAWTEXTPARAMS> lpdtp)>('DrawTextExW'); expect(DrawTextEx, isA<Function>()); }); test('Can instantiate EmptyClipboard', () { final user32 = DynamicLibrary.open('user32.dll'); final EmptyClipboard = user32 .lookupFunction<Int32 Function(), int Function()>('EmptyClipboard'); expect(EmptyClipboard, isA<Function>()); }); test('Can instantiate EnableMenuItem', () { final user32 = DynamicLibrary.open('user32.dll'); final EnableMenuItem = user32.lookupFunction< Int32 Function(IntPtr hMenu, Uint32 uIDEnableItem, Uint32 uEnable), int Function( int hMenu, int uIDEnableItem, int uEnable)>('EnableMenuItem'); expect(EnableMenuItem, isA<Function>()); }); if (windowsBuildNumber >= 14393) { test('Can instantiate EnableNonClientDpiScaling', () { final user32 = DynamicLibrary.open('user32.dll'); final EnableNonClientDpiScaling = user32.lookupFunction< Int32 Function(IntPtr hwnd), int Function(int hwnd)>('EnableNonClientDpiScaling'); expect(EnableNonClientDpiScaling, isA<Function>()); }); } test('Can instantiate EnableScrollBar', () { final user32 = DynamicLibrary.open('user32.dll'); final EnableScrollBar = user32.lookupFunction< Int32 Function(IntPtr hWnd, Uint32 wSBflags, Uint32 wArrows), int Function(int hWnd, int wSBflags, int wArrows)>('EnableScrollBar'); expect(EnableScrollBar, isA<Function>()); }); test('Can instantiate EnableWindow', () { final user32 = DynamicLibrary.open('user32.dll'); final EnableWindow = user32.lookupFunction< Int32 Function(IntPtr hWnd, Int32 bEnable), int Function(int hWnd, int bEnable)>('EnableWindow'); expect(EnableWindow, isA<Function>()); }); test('Can instantiate EndDeferWindowPos', () { final user32 = DynamicLibrary.open('user32.dll'); final EndDeferWindowPos = user32.lookupFunction< Int32 Function(IntPtr hWinPosInfo), int Function(int hWinPosInfo)>('EndDeferWindowPos'); expect(EndDeferWindowPos, isA<Function>()); }); test('Can instantiate EndDialog', () { final user32 = DynamicLibrary.open('user32.dll'); final EndDialog = user32.lookupFunction< Int32 Function(IntPtr hDlg, IntPtr nResult), int Function(int hDlg, int nResult)>('EndDialog'); expect(EndDialog, isA<Function>()); }); test('Can instantiate EndMenu', () { final user32 = DynamicLibrary.open('user32.dll'); final EndMenu = user32.lookupFunction<Int32 Function(), int Function()>('EndMenu'); expect(EndMenu, isA<Function>()); }); test('Can instantiate EndPaint', () { final user32 = DynamicLibrary.open('user32.dll'); final EndPaint = user32.lookupFunction< Int32 Function(IntPtr hWnd, Pointer<PAINTSTRUCT> lpPaint), int Function(int hWnd, Pointer<PAINTSTRUCT> lpPaint)>('EndPaint'); expect(EndPaint, isA<Function>()); }); test('Can instantiate EnumChildWindows', () { final user32 = DynamicLibrary.open('user32.dll'); final EnumChildWindows = user32.lookupFunction< Int32 Function( IntPtr hWndParent, Pointer<NativeFunction<EnumWindowsProc>> lpEnumFunc, IntPtr lParam), int Function( int hWndParent, Pointer<NativeFunction<EnumWindowsProc>> lpEnumFunc, int lParam)>('EnumChildWindows'); expect(EnumChildWindows, isA<Function>()); }); test('Can instantiate EnumClipboardFormats', () { final user32 = DynamicLibrary.open('user32.dll'); final EnumClipboardFormats = user32.lookupFunction< Uint32 Function(Uint32 format), int Function(int format)>('EnumClipboardFormats'); expect(EnumClipboardFormats, isA<Function>()); }); test('Can instantiate EnumDesktopWindows', () { final user32 = DynamicLibrary.open('user32.dll'); final EnumDesktopWindows = user32.lookupFunction< Int32 Function(IntPtr hDesktop, Pointer<NativeFunction<EnumWindowsProc>> lpfn, IntPtr lParam), int Function( int hDesktop, Pointer<NativeFunction<EnumWindowsProc>> lpfn, int lParam)>('EnumDesktopWindows'); expect(EnumDesktopWindows, isA<Function>()); }); test('Can instantiate EnumDisplayMonitors', () { final user32 = DynamicLibrary.open('user32.dll'); final EnumDisplayMonitors = user32.lookupFunction< Int32 Function(IntPtr hdc, Pointer<RECT> lprcClip, Pointer<NativeFunction<MonitorEnumProc>> lpfnEnum, IntPtr dwData), int Function( int hdc, Pointer<RECT> lprcClip, Pointer<NativeFunction<MonitorEnumProc>> lpfnEnum, int dwData)>('EnumDisplayMonitors'); expect(EnumDisplayMonitors, isA<Function>()); }); test('Can instantiate EnumThreadWindows', () { final user32 = DynamicLibrary.open('user32.dll'); final EnumThreadWindows = user32.lookupFunction< Int32 Function(Uint32 dwThreadId, Pointer<NativeFunction<EnumWindowsProc>> lpfn, IntPtr lParam), int Function( int dwThreadId, Pointer<NativeFunction<EnumWindowsProc>> lpfn, int lParam)>('EnumThreadWindows'); expect(EnumThreadWindows, isA<Function>()); }); test('Can instantiate EnumWindows', () { final user32 = DynamicLibrary.open('user32.dll'); final EnumWindows = user32.lookupFunction< Int32 Function(Pointer<NativeFunction<EnumWindowsProc>> lpEnumFunc, IntPtr lParam), int Function(Pointer<NativeFunction<EnumWindowsProc>> lpEnumFunc, int lParam)>('EnumWindows'); expect(EnumWindows, isA<Function>()); }); test('Can instantiate EqualRect', () { final user32 = DynamicLibrary.open('user32.dll'); final EqualRect = user32.lookupFunction< Int32 Function(Pointer<RECT> lprc1, Pointer<RECT> lprc2), int Function(Pointer<RECT> lprc1, Pointer<RECT> lprc2)>('EqualRect'); expect(EqualRect, isA<Function>()); }); test('Can instantiate ExcludeUpdateRgn', () { final user32 = DynamicLibrary.open('user32.dll'); final ExcludeUpdateRgn = user32.lookupFunction< Int32 Function(IntPtr hDC, IntPtr hWnd), int Function(int hDC, int hWnd)>('ExcludeUpdateRgn'); expect(ExcludeUpdateRgn, isA<Function>()); }); test('Can instantiate FillRect', () { final user32 = DynamicLibrary.open('user32.dll'); final FillRect = user32.lookupFunction< Int32 Function(IntPtr hDC, Pointer<RECT> lprc, IntPtr hbr), int Function(int hDC, Pointer<RECT> lprc, int hbr)>('FillRect'); expect(FillRect, isA<Function>()); }); test('Can instantiate FindWindow', () { final user32 = DynamicLibrary.open('user32.dll'); final FindWindow = user32.lookupFunction< IntPtr Function( Pointer<Utf16> lpClassName, Pointer<Utf16> lpWindowName), int Function(Pointer<Utf16> lpClassName, Pointer<Utf16> lpWindowName)>('FindWindowW'); expect(FindWindow, isA<Function>()); }); test('Can instantiate FindWindowEx', () { final user32 = DynamicLibrary.open('user32.dll'); final FindWindowEx = user32.lookupFunction< IntPtr Function(IntPtr hWndParent, IntPtr hWndChildAfter, Pointer<Utf16> lpszClass, Pointer<Utf16> lpszWindow), int Function( int hWndParent, int hWndChildAfter, Pointer<Utf16> lpszClass, Pointer<Utf16> lpszWindow)>('FindWindowExW'); expect(FindWindowEx, isA<Function>()); }); test('Can instantiate FrameRect', () { final user32 = DynamicLibrary.open('user32.dll'); final FrameRect = user32.lookupFunction< Int32 Function(IntPtr hDC, Pointer<RECT> lprc, IntPtr hbr), int Function(int hDC, Pointer<RECT> lprc, int hbr)>('FrameRect'); expect(FrameRect, isA<Function>()); }); test('Can instantiate GetActiveWindow', () { final user32 = DynamicLibrary.open('user32.dll'); final GetActiveWindow = user32 .lookupFunction<IntPtr Function(), int Function()>('GetActiveWindow'); expect(GetActiveWindow, isA<Function>()); }); test('Can instantiate GetAncestor', () { final user32 = DynamicLibrary.open('user32.dll'); final GetAncestor = user32.lookupFunction< IntPtr Function(IntPtr hwnd, Uint32 gaFlags), int Function(int hwnd, int gaFlags)>('GetAncestor'); expect(GetAncestor, isA<Function>()); }); test('Can instantiate GetAsyncKeyState', () { final user32 = DynamicLibrary.open('user32.dll'); final GetAsyncKeyState = user32.lookupFunction<Int16 Function(Int32 vKey), int Function(int vKey)>('GetAsyncKeyState'); expect(GetAsyncKeyState, isA<Function>()); }); if (windowsBuildNumber >= 14393) { test('Can instantiate GetAwarenessFromDpiAwarenessContext', () { final user32 = DynamicLibrary.open('user32.dll'); final GetAwarenessFromDpiAwarenessContext = user32.lookupFunction< Int32 Function(IntPtr value), int Function(int value)>('GetAwarenessFromDpiAwarenessContext'); expect(GetAwarenessFromDpiAwarenessContext, isA<Function>()); }); } test('Can instantiate GetCapture', () { final user32 = DynamicLibrary.open('user32.dll'); final GetCapture = user32 .lookupFunction<IntPtr Function(), int Function()>('GetCapture'); expect(GetCapture, isA<Function>()); }); test('Can instantiate GetCaretBlinkTime', () { final user32 = DynamicLibrary.open('user32.dll'); final GetCaretBlinkTime = user32.lookupFunction<Uint32 Function(), int Function()>( 'GetCaretBlinkTime'); expect(GetCaretBlinkTime, isA<Function>()); }); test('Can instantiate GetCaretPos', () { final user32 = DynamicLibrary.open('user32.dll'); final GetCaretPos = user32.lookupFunction< Int32 Function(Pointer<POINT> lpPoint), int Function(Pointer<POINT> lpPoint)>('GetCaretPos'); expect(GetCaretPos, isA<Function>()); }); test('Can instantiate GetClassInfo', () { final user32 = DynamicLibrary.open('user32.dll'); final GetClassInfo = user32.lookupFunction< Int32 Function(IntPtr hInstance, Pointer<Utf16> lpClassName, Pointer<WNDCLASS> lpWndClass), int Function(int hInstance, Pointer<Utf16> lpClassName, Pointer<WNDCLASS> lpWndClass)>('GetClassInfoW'); expect(GetClassInfo, isA<Function>()); }); test('Can instantiate GetClassInfoEx', () { final user32 = DynamicLibrary.open('user32.dll'); final GetClassInfoEx = user32.lookupFunction< Int32 Function(IntPtr hInstance, Pointer<Utf16> lpszClass, Pointer<WNDCLASSEX> lpwcx), int Function(int hInstance, Pointer<Utf16> lpszClass, Pointer<WNDCLASSEX> lpwcx)>('GetClassInfoExW'); expect(GetClassInfoEx, isA<Function>()); }); test('Can instantiate GetClassLongPtr', () { final user32 = DynamicLibrary.open('user32.dll'); final GetClassLongPtr = user32.lookupFunction< IntPtr Function(IntPtr hWnd, Int32 nIndex), int Function(int hWnd, int nIndex)>('GetClassLongPtrW'); expect(GetClassLongPtr, isA<Function>()); }); test('Can instantiate GetClientRect', () { final user32 = DynamicLibrary.open('user32.dll'); final GetClientRect = user32.lookupFunction< Int32 Function(IntPtr hWnd, Pointer<RECT> lpRect), int Function(int hWnd, Pointer<RECT> lpRect)>('GetClientRect'); expect(GetClientRect, isA<Function>()); }); test('Can instantiate GetClipboardData', () { final user32 = DynamicLibrary.open('user32.dll'); final GetClipboardData = user32.lookupFunction< IntPtr Function(Uint32 uFormat), int Function(int uFormat)>('GetClipboardData'); expect(GetClipboardData, isA<Function>()); }); test('Can instantiate GetClipboardFormatName', () { final user32 = DynamicLibrary.open('user32.dll'); final GetClipboardFormatName = user32.lookupFunction< Int32 Function( Uint32 format, Pointer<Utf16> lpszFormatName, Int32 cchMaxCount), int Function(int format, Pointer<Utf16> lpszFormatName, int cchMaxCount)>('GetClipboardFormatNameW'); expect(GetClipboardFormatName, isA<Function>()); }); test('Can instantiate GetClipboardOwner', () { final user32 = DynamicLibrary.open('user32.dll'); final GetClipboardOwner = user32.lookupFunction<IntPtr Function(), int Function()>( 'GetClipboardOwner'); expect(GetClipboardOwner, isA<Function>()); }); test('Can instantiate GetClipboardSequenceNumber', () { final user32 = DynamicLibrary.open('user32.dll'); final GetClipboardSequenceNumber = user32.lookupFunction<Uint32 Function(), int Function()>( 'GetClipboardSequenceNumber'); expect(GetClipboardSequenceNumber, isA<Function>()); }); test('Can instantiate GetClipboardViewer', () { final user32 = DynamicLibrary.open('user32.dll'); final GetClipboardViewer = user32.lookupFunction<IntPtr Function(), int Function()>( 'GetClipboardViewer'); expect(GetClipboardViewer, isA<Function>()); }); test('Can instantiate GetClipCursor', () { final user32 = DynamicLibrary.open('user32.dll'); final GetClipCursor = user32.lookupFunction< Int32 Function(Pointer<RECT> lpRect), int Function(Pointer<RECT> lpRect)>('GetClipCursor'); expect(GetClipCursor, isA<Function>()); }); test('Can instantiate GetCursor', () { final user32 = DynamicLibrary.open('user32.dll'); final GetCursor = user32.lookupFunction<IntPtr Function(), int Function()>('GetCursor'); expect(GetCursor, isA<Function>()); }); test('Can instantiate GetCursorInfo', () { final user32 = DynamicLibrary.open('user32.dll'); final GetCursorInfo = user32.lookupFunction< Int32 Function(Pointer<CURSORINFO> pci), int Function(Pointer<CURSORINFO> pci)>('GetCursorInfo'); expect(GetCursorInfo, isA<Function>()); }); test('Can instantiate GetCursorPos', () { final user32 = DynamicLibrary.open('user32.dll'); final GetCursorPos = user32.lookupFunction< Int32 Function(Pointer<POINT> lpPoint), int Function(Pointer<POINT> lpPoint)>('GetCursorPos'); expect(GetCursorPos, isA<Function>()); }); test('Can instantiate GetDC', () { final user32 = DynamicLibrary.open('user32.dll'); final GetDC = user32.lookupFunction<IntPtr Function(IntPtr hWnd), int Function(int hWnd)>('GetDC'); expect(GetDC, isA<Function>()); }); test('Can instantiate GetDCEx', () { final user32 = DynamicLibrary.open('user32.dll'); final GetDCEx = user32.lookupFunction< IntPtr Function(IntPtr hWnd, IntPtr hrgnClip, Uint32 flags), int Function(int hWnd, int hrgnClip, int flags)>('GetDCEx'); expect(GetDCEx, isA<Function>()); }); test('Can instantiate GetDesktopWindow', () { final user32 = DynamicLibrary.open('user32.dll'); final GetDesktopWindow = user32.lookupFunction<IntPtr Function(), int Function()>( 'GetDesktopWindow'); expect(GetDesktopWindow, isA<Function>()); }); test('Can instantiate GetDialogBaseUnits', () { final user32 = DynamicLibrary.open('user32.dll'); final GetDialogBaseUnits = user32.lookupFunction<Int32 Function(), int Function()>( 'GetDialogBaseUnits'); expect(GetDialogBaseUnits, isA<Function>()); }); if (windowsBuildNumber >= 15063) { test('Can instantiate GetDialogControlDpiChangeBehavior', () { final user32 = DynamicLibrary.open('user32.dll'); final GetDialogControlDpiChangeBehavior = user32.lookupFunction< Uint32 Function(IntPtr hWnd), int Function(int hWnd)>('GetDialogControlDpiChangeBehavior'); expect(GetDialogControlDpiChangeBehavior, isA<Function>()); }); } if (windowsBuildNumber >= 15063) { test('Can instantiate GetDialogDpiChangeBehavior', () { final user32 = DynamicLibrary.open('user32.dll'); final GetDialogDpiChangeBehavior = user32.lookupFunction< Uint32 Function(IntPtr hDlg), int Function(int hDlg)>('GetDialogDpiChangeBehavior'); expect(GetDialogDpiChangeBehavior, isA<Function>()); }); } if (windowsBuildNumber >= 9200) { test('Can instantiate GetDisplayAutoRotationPreferences', () { final user32 = DynamicLibrary.open('user32.dll'); final GetDisplayAutoRotationPreferences = user32.lookupFunction< Int32 Function(Pointer<Int32> pOrientation), int Function(Pointer<Int32> pOrientation)>( 'GetDisplayAutoRotationPreferences'); expect(GetDisplayAutoRotationPreferences, isA<Function>()); }); } test('Can instantiate GetDlgItem', () { final user32 = DynamicLibrary.open('user32.dll'); final GetDlgItem = user32.lookupFunction< IntPtr Function(IntPtr hDlg, Int32 nIDDlgItem), int Function(int hDlg, int nIDDlgItem)>('GetDlgItem'); expect(GetDlgItem, isA<Function>()); }); test('Can instantiate GetDlgItemInt', () { final user32 = DynamicLibrary.open('user32.dll'); final GetDlgItemInt = user32.lookupFunction< Uint32 Function(IntPtr hDlg, Int32 nIDDlgItem, Pointer<Int32> lpTranslated, Int32 bSigned), int Function(int hDlg, int nIDDlgItem, Pointer<Int32> lpTranslated, int bSigned)>('GetDlgItemInt'); expect(GetDlgItemInt, isA<Function>()); }); test('Can instantiate GetDlgItemText', () { final user32 = DynamicLibrary.open('user32.dll'); final GetDlgItemText = user32.lookupFunction< Uint32 Function(IntPtr hDlg, Int32 nIDDlgItem, Pointer<Utf16> lpString, Int32 cchMax), int Function(int hDlg, int nIDDlgItem, Pointer<Utf16> lpString, int cchMax)>('GetDlgItemTextW'); expect(GetDlgItemText, isA<Function>()); }); test('Can instantiate GetDoubleClickTime', () { final user32 = DynamicLibrary.open('user32.dll'); final GetDoubleClickTime = user32.lookupFunction<Uint32 Function(), int Function()>( 'GetDoubleClickTime'); expect(GetDoubleClickTime, isA<Function>()); }); if (windowsBuildNumber >= 14393) { test('Can instantiate GetDpiForSystem', () { final user32 = DynamicLibrary.open('user32.dll'); final GetDpiForSystem = user32.lookupFunction<Uint32 Function(), int Function()>( 'GetDpiForSystem'); expect(GetDpiForSystem, isA<Function>()); }); } if (windowsBuildNumber >= 14393) { test('Can instantiate GetDpiForWindow', () { final user32 = DynamicLibrary.open('user32.dll'); final GetDpiForWindow = user32.lookupFunction< Uint32 Function(IntPtr hwnd), int Function(int hwnd)>('GetDpiForWindow'); expect(GetDpiForWindow, isA<Function>()); }); } if (windowsBuildNumber >= 17134) { test('Can instantiate GetDpiFromDpiAwarenessContext', () { final user32 = DynamicLibrary.open('user32.dll'); final GetDpiFromDpiAwarenessContext = user32.lookupFunction< Uint32 Function(IntPtr value), int Function(int value)>('GetDpiFromDpiAwarenessContext'); expect(GetDpiFromDpiAwarenessContext, isA<Function>()); }); } test('Can instantiate GetFocus', () { final user32 = DynamicLibrary.open('user32.dll'); final GetFocus = user32.lookupFunction<IntPtr Function(), int Function()>('GetFocus'); expect(GetFocus, isA<Function>()); }); test('Can instantiate GetForegroundWindow', () { final user32 = DynamicLibrary.open('user32.dll'); final GetForegroundWindow = user32.lookupFunction<IntPtr Function(), int Function()>( 'GetForegroundWindow'); expect(GetForegroundWindow, isA<Function>()); }); test('Can instantiate GetGestureConfig', () { final user32 = DynamicLibrary.open('user32.dll'); final GetGestureConfig = user32.lookupFunction< Int32 Function( IntPtr hwnd, Uint32 dwReserved, Uint32 dwFlags, Pointer<Uint32> pcIDs, Pointer<GESTURECONFIG> pGestureConfig, Uint32 cbSize), int Function( int hwnd, int dwReserved, int dwFlags, Pointer<Uint32> pcIDs, Pointer<GESTURECONFIG> pGestureConfig, int cbSize)>('GetGestureConfig'); expect(GetGestureConfig, isA<Function>()); }); test('Can instantiate GetGestureExtraArgs', () { final user32 = DynamicLibrary.open('user32.dll'); final GetGestureExtraArgs = user32.lookupFunction< Int32 Function(IntPtr hGestureInfo, Uint32 cbExtraArgs, Pointer<Uint8> pExtraArgs), int Function(int hGestureInfo, int cbExtraArgs, Pointer<Uint8> pExtraArgs)>('GetGestureExtraArgs'); expect(GetGestureExtraArgs, isA<Function>()); }); test('Can instantiate GetGestureInfo', () { final user32 = DynamicLibrary.open('user32.dll'); final GetGestureInfo = user32.lookupFunction< Int32 Function( IntPtr hGestureInfo, Pointer<GESTUREINFO> pGestureInfo), int Function(int hGestureInfo, Pointer<GESTUREINFO> pGestureInfo)>('GetGestureInfo'); expect(GetGestureInfo, isA<Function>()); }); test('Can instantiate GetIconInfo', () { final user32 = DynamicLibrary.open('user32.dll'); final GetIconInfo = user32.lookupFunction< Int32 Function(IntPtr hIcon, Pointer<ICONINFO> piconinfo), int Function(int hIcon, Pointer<ICONINFO> piconinfo)>('GetIconInfo'); expect(GetIconInfo, isA<Function>()); }); test('Can instantiate GetIconInfoEx', () { final user32 = DynamicLibrary.open('user32.dll'); final GetIconInfoEx = user32.lookupFunction< Int32 Function(IntPtr hicon, Pointer<ICONINFOEX> piconinfo), int Function( int hicon, Pointer<ICONINFOEX> piconinfo)>('GetIconInfoExW'); expect(GetIconInfoEx, isA<Function>()); }); test('Can instantiate GetInputState', () { final user32 = DynamicLibrary.open('user32.dll'); final GetInputState = user32 .lookupFunction<Int32 Function(), int Function()>('GetInputState'); expect(GetInputState, isA<Function>()); }); test('Can instantiate GetKeyboardLayout', () { final user32 = DynamicLibrary.open('user32.dll'); final GetKeyboardLayout = user32.lookupFunction< IntPtr Function(Uint32 idThread), int Function(int idThread)>('GetKeyboardLayout'); expect(GetKeyboardLayout, isA<Function>()); }); test('Can instantiate GetKeyboardLayoutList', () { final user32 = DynamicLibrary.open('user32.dll'); final GetKeyboardLayoutList = user32.lookupFunction< Int32 Function(Int32 nBuff, Pointer<IntPtr> lpList), int Function( int nBuff, Pointer<IntPtr> lpList)>('GetKeyboardLayoutList'); expect(GetKeyboardLayoutList, isA<Function>()); }); test('Can instantiate GetKeyboardLayoutName', () { final user32 = DynamicLibrary.open('user32.dll'); final GetKeyboardLayoutName = user32.lookupFunction< Int32 Function(Pointer<Utf16> pwszKLID), int Function(Pointer<Utf16> pwszKLID)>('GetKeyboardLayoutNameW'); expect(GetKeyboardLayoutName, isA<Function>()); }); test('Can instantiate GetKeyboardState', () { final user32 = DynamicLibrary.open('user32.dll'); final GetKeyboardState = user32.lookupFunction< Int32 Function(Pointer<Uint8> lpKeyState), int Function(Pointer<Uint8> lpKeyState)>('GetKeyboardState'); expect(GetKeyboardState, isA<Function>()); }); test('Can instantiate GetKeyboardType', () { final user32 = DynamicLibrary.open('user32.dll'); final GetKeyboardType = user32.lookupFunction< Int32 Function(Int32 nTypeFlag), int Function(int nTypeFlag)>('GetKeyboardType'); expect(GetKeyboardType, isA<Function>()); }); test('Can instantiate GetKeyNameText', () { final user32 = DynamicLibrary.open('user32.dll'); final GetKeyNameText = user32.lookupFunction< Int32 Function(Int32 lParam, Pointer<Utf16> lpString, Int32 cchSize), int Function(int lParam, Pointer<Utf16> lpString, int cchSize)>('GetKeyNameTextW'); expect(GetKeyNameText, isA<Function>()); }); test('Can instantiate GetKeyState', () { final user32 = DynamicLibrary.open('user32.dll'); final GetKeyState = user32.lookupFunction<Int16 Function(Int32 nVirtKey), int Function(int nVirtKey)>('GetKeyState'); expect(GetKeyState, isA<Function>()); }); test('Can instantiate GetLastInputInfo', () { final user32 = DynamicLibrary.open('user32.dll'); final GetLastInputInfo = user32.lookupFunction< Int32 Function(Pointer<LASTINPUTINFO> plii), int Function(Pointer<LASTINPUTINFO> plii)>('GetLastInputInfo'); expect(GetLastInputInfo, isA<Function>()); }); test('Can instantiate GetLayeredWindowAttributes', () { final user32 = DynamicLibrary.open('user32.dll'); final GetLayeredWindowAttributes = user32.lookupFunction< Int32 Function(IntPtr hwnd, Pointer<Uint32> pcrKey, Pointer<Uint8> pbAlpha, Pointer<Uint32> pdwFlags), int Function(int hwnd, Pointer<Uint32> pcrKey, Pointer<Uint8> pbAlpha, Pointer<Uint32> pdwFlags)>('GetLayeredWindowAttributes'); expect(GetLayeredWindowAttributes, isA<Function>()); }); test('Can instantiate GetMenu', () { final user32 = DynamicLibrary.open('user32.dll'); final GetMenu = user32.lookupFunction<IntPtr Function(IntPtr hWnd), int Function(int hWnd)>('GetMenu'); expect(GetMenu, isA<Function>()); }); test('Can instantiate GetMenuInfo', () { final user32 = DynamicLibrary.open('user32.dll'); final GetMenuInfo = user32.lookupFunction< Int32 Function(IntPtr param0, Pointer<MENUINFO> param1), int Function(int param0, Pointer<MENUINFO> param1)>('GetMenuInfo'); expect(GetMenuInfo, isA<Function>()); }); test('Can instantiate GetMenuItemCount', () { final user32 = DynamicLibrary.open('user32.dll'); final GetMenuItemCount = user32.lookupFunction< Int32 Function(IntPtr hMenu), int Function(int hMenu)>('GetMenuItemCount'); expect(GetMenuItemCount, isA<Function>()); }); test('Can instantiate GetMenuItemInfo', () { final user32 = DynamicLibrary.open('user32.dll'); final GetMenuItemInfo = user32.lookupFunction< Int32 Function(IntPtr hmenu, Uint32 item, Int32 fByPosition, Pointer<MENUITEMINFO> lpmii), int Function(int hmenu, int item, int fByPosition, Pointer<MENUITEMINFO> lpmii)>('GetMenuItemInfoW'); expect(GetMenuItemInfo, isA<Function>()); }); test('Can instantiate GetMenuItemRect', () { final user32 = DynamicLibrary.open('user32.dll'); final GetMenuItemRect = user32.lookupFunction< Int32 Function( IntPtr hWnd, IntPtr hMenu, Uint32 uItem, Pointer<RECT> lprcItem), int Function(int hWnd, int hMenu, int uItem, Pointer<RECT> lprcItem)>('GetMenuItemRect'); expect(GetMenuItemRect, isA<Function>()); }); test('Can instantiate GetMenuState', () { final user32 = DynamicLibrary.open('user32.dll'); final GetMenuState = user32.lookupFunction< Uint32 Function(IntPtr hMenu, Uint32 uId, Uint32 uFlags), int Function(int hMenu, int uId, int uFlags)>('GetMenuState'); expect(GetMenuState, isA<Function>()); }); test('Can instantiate GetMenuString', () { final user32 = DynamicLibrary.open('user32.dll'); final GetMenuString = user32.lookupFunction< Int32 Function(IntPtr hMenu, Uint32 uIDItem, Pointer<Utf16> lpString, Int32 cchMax, Uint32 flags), int Function(int hMenu, int uIDItem, Pointer<Utf16> lpString, int cchMax, int flags)>('GetMenuStringW'); expect(GetMenuString, isA<Function>()); }); test('Can instantiate GetMessage', () { final user32 = DynamicLibrary.open('user32.dll'); final GetMessage = user32.lookupFunction< Int32 Function(Pointer<MSG> lpMsg, IntPtr hWnd, Uint32 wMsgFilterMin, Uint32 wMsgFilterMax), int Function(Pointer<MSG> lpMsg, int hWnd, int wMsgFilterMin, int wMsgFilterMax)>('GetMessageW'); expect(GetMessage, isA<Function>()); }); test('Can instantiate GetMessageExtraInfo', () { final user32 = DynamicLibrary.open('user32.dll'); final GetMessageExtraInfo = user32.lookupFunction<IntPtr Function(), int Function()>( 'GetMessageExtraInfo'); expect(GetMessageExtraInfo, isA<Function>()); }); test('Can instantiate GetMessagePos', () { final user32 = DynamicLibrary.open('user32.dll'); final GetMessagePos = user32 .lookupFunction<Uint32 Function(), int Function()>('GetMessagePos'); expect(GetMessagePos, isA<Function>()); }); test('Can instantiate GetMessageTime', () { final user32 = DynamicLibrary.open('user32.dll'); final GetMessageTime = user32 .lookupFunction<Int32 Function(), int Function()>('GetMessageTime'); expect(GetMessageTime, isA<Function>()); }); test('Can instantiate GetMonitorInfo', () { final user32 = DynamicLibrary.open('user32.dll'); final GetMonitorInfo = user32.lookupFunction< Int32 Function(IntPtr hMonitor, Pointer<MONITORINFO> lpmi), int Function( int hMonitor, Pointer<MONITORINFO> lpmi)>('GetMonitorInfoW'); expect(GetMonitorInfo, isA<Function>()); }); test('Can instantiate GetMouseMovePointsEx', () { final user32 = DynamicLibrary.open('user32.dll'); final GetMouseMovePointsEx = user32.lookupFunction< Int32 Function( Uint32 cbSize, Pointer<MOUSEMOVEPOINT> lppt, Pointer<MOUSEMOVEPOINT> lpptBuf, Int32 nBufPoints, Uint32 resolution), int Function( int cbSize, Pointer<MOUSEMOVEPOINT> lppt, Pointer<MOUSEMOVEPOINT> lpptBuf, int nBufPoints, int resolution)>('GetMouseMovePointsEx'); expect(GetMouseMovePointsEx, isA<Function>()); }); test('Can instantiate GetNextDlgGroupItem', () { final user32 = DynamicLibrary.open('user32.dll'); final GetNextDlgGroupItem = user32.lookupFunction< IntPtr Function(IntPtr hDlg, IntPtr hCtl, Int32 bPrevious), int Function( int hDlg, int hCtl, int bPrevious)>('GetNextDlgGroupItem'); expect(GetNextDlgGroupItem, isA<Function>()); }); test('Can instantiate GetNextDlgTabItem', () { final user32 = DynamicLibrary.open('user32.dll'); final GetNextDlgTabItem = user32.lookupFunction< IntPtr Function(IntPtr hDlg, IntPtr hCtl, Int32 bPrevious), int Function(int hDlg, int hCtl, int bPrevious)>('GetNextDlgTabItem'); expect(GetNextDlgTabItem, isA<Function>()); }); test('Can instantiate GetOpenClipboardWindow', () { final user32 = DynamicLibrary.open('user32.dll'); final GetOpenClipboardWindow = user32.lookupFunction<IntPtr Function(), int Function()>( 'GetOpenClipboardWindow'); expect(GetOpenClipboardWindow, isA<Function>()); }); test('Can instantiate GetParent', () { final user32 = DynamicLibrary.open('user32.dll'); final GetParent = user32.lookupFunction<IntPtr Function(IntPtr hWnd), int Function(int hWnd)>('GetParent'); expect(GetParent, isA<Function>()); }); test('Can instantiate GetPhysicalCursorPos', () { final user32 = DynamicLibrary.open('user32.dll'); final GetPhysicalCursorPos = user32.lookupFunction< Int32 Function(Pointer<POINT> lpPoint), int Function(Pointer<POINT> lpPoint)>('GetPhysicalCursorPos'); expect(GetPhysicalCursorPos, isA<Function>()); }); test('Can instantiate GetPriorityClipboardFormat', () { final user32 = DynamicLibrary.open('user32.dll'); final GetPriorityClipboardFormat = user32.lookupFunction< Int32 Function(Pointer<Uint32> paFormatPriorityList, Int32 cFormats), int Function(Pointer<Uint32> paFormatPriorityList, int cFormats)>('GetPriorityClipboardFormat'); expect(GetPriorityClipboardFormat, isA<Function>()); }); test('Can instantiate GetProcessWindowStation', () { final user32 = DynamicLibrary.open('user32.dll'); final GetProcessWindowStation = user32.lookupFunction<IntPtr Function(), int Function()>( 'GetProcessWindowStation'); expect(GetProcessWindowStation, isA<Function>()); }); test('Can instantiate GetProp', () { final user32 = DynamicLibrary.open('user32.dll'); final GetProp = user32.lookupFunction< IntPtr Function(IntPtr hWnd, Pointer<Utf16> lpString), int Function(int hWnd, Pointer<Utf16> lpString)>('GetPropW'); expect(GetProp, isA<Function>()); }); test('Can instantiate GetRawInputBuffer', () { final user32 = DynamicLibrary.open('user32.dll'); final GetRawInputBuffer = user32.lookupFunction< Uint32 Function(Pointer<RAWINPUT> pData, Pointer<Uint32> pcbSize, Uint32 cbSizeHeader), int Function(Pointer<RAWINPUT> pData, Pointer<Uint32> pcbSize, int cbSizeHeader)>('GetRawInputBuffer'); expect(GetRawInputBuffer, isA<Function>()); }); test('Can instantiate GetRawInputData', () { final user32 = DynamicLibrary.open('user32.dll'); final GetRawInputData = user32.lookupFunction< Uint32 Function(IntPtr hRawInput, Uint32 uiCommand, Pointer pData, Pointer<Uint32> pcbSize, Uint32 cbSizeHeader), int Function(int hRawInput, int uiCommand, Pointer pData, Pointer<Uint32> pcbSize, int cbSizeHeader)>('GetRawInputData'); expect(GetRawInputData, isA<Function>()); }); test('Can instantiate GetRawInputDeviceInfo', () { final user32 = DynamicLibrary.open('user32.dll'); final GetRawInputDeviceInfo = user32.lookupFunction< Uint32 Function(IntPtr hDevice, Uint32 uiCommand, Pointer pData, Pointer<Uint32> pcbSize), int Function(int hDevice, int uiCommand, Pointer pData, Pointer<Uint32> pcbSize)>('GetRawInputDeviceInfoW'); expect(GetRawInputDeviceInfo, isA<Function>()); }); test('Can instantiate GetRawInputDeviceList', () { final user32 = DynamicLibrary.open('user32.dll'); final GetRawInputDeviceList = user32.lookupFunction< Uint32 Function(Pointer<RAWINPUTDEVICELIST> pRawInputDeviceList, Pointer<Uint32> puiNumDevices, Uint32 cbSize), int Function( Pointer<RAWINPUTDEVICELIST> pRawInputDeviceList, Pointer<Uint32> puiNumDevices, int cbSize)>('GetRawInputDeviceList'); expect(GetRawInputDeviceList, isA<Function>()); }); test('Can instantiate GetRegisteredRawInputDevices', () { final user32 = DynamicLibrary.open('user32.dll'); final GetRegisteredRawInputDevices = user32.lookupFunction< Uint32 Function(Pointer<RAWINPUTDEVICE> pRawInputDevices, Pointer<Uint32> puiNumDevices, Uint32 cbSize), int Function( Pointer<RAWINPUTDEVICE> pRawInputDevices, Pointer<Uint32> puiNumDevices, int cbSize)>('GetRegisteredRawInputDevices'); expect(GetRegisteredRawInputDevices, isA<Function>()); }); test('Can instantiate GetScrollBarInfo', () { final user32 = DynamicLibrary.open('user32.dll'); final GetScrollBarInfo = user32.lookupFunction< Int32 Function( IntPtr hwnd, Int32 idObject, Pointer<SCROLLBARINFO> psbi), int Function(int hwnd, int idObject, Pointer<SCROLLBARINFO> psbi)>('GetScrollBarInfo'); expect(GetScrollBarInfo, isA<Function>()); }); test('Can instantiate GetScrollInfo', () { final user32 = DynamicLibrary.open('user32.dll'); final GetScrollInfo = user32.lookupFunction< Int32 Function(IntPtr hwnd, Uint32 nBar, Pointer<SCROLLINFO> lpsi), int Function( int hwnd, int nBar, Pointer<SCROLLINFO> lpsi)>('GetScrollInfo'); expect(GetScrollInfo, isA<Function>()); }); test('Can instantiate GetShellWindow', () { final user32 = DynamicLibrary.open('user32.dll'); final GetShellWindow = user32 .lookupFunction<IntPtr Function(), int Function()>('GetShellWindow'); expect(GetShellWindow, isA<Function>()); }); test('Can instantiate GetSubMenu', () { final user32 = DynamicLibrary.open('user32.dll'); final GetSubMenu = user32.lookupFunction< IntPtr Function(IntPtr hMenu, Int32 nPos), int Function(int hMenu, int nPos)>('GetSubMenu'); expect(GetSubMenu, isA<Function>()); }); test('Can instantiate GetSysColor', () { final user32 = DynamicLibrary.open('user32.dll'); final GetSysColor = user32.lookupFunction<Uint32 Function(Uint32 nIndex), int Function(int nIndex)>('GetSysColor'); expect(GetSysColor, isA<Function>()); }); test('Can instantiate GetSysColorBrush', () { final user32 = DynamicLibrary.open('user32.dll'); final GetSysColorBrush = user32.lookupFunction< IntPtr Function(Int32 nIndex), int Function(int nIndex)>('GetSysColorBrush'); expect(GetSysColorBrush, isA<Function>()); }); if (windowsBuildNumber >= 17134) { test('Can instantiate GetSystemDpiForProcess', () { final user32 = DynamicLibrary.open('user32.dll'); final GetSystemDpiForProcess = user32.lookupFunction< Uint32 Function(IntPtr hProcess), int Function(int hProcess)>('GetSystemDpiForProcess'); expect(GetSystemDpiForProcess, isA<Function>()); }); } test('Can instantiate GetSystemMenu', () { final user32 = DynamicLibrary.open('user32.dll'); final GetSystemMenu = user32.lookupFunction< IntPtr Function(IntPtr hWnd, Int32 bRevert), int Function(int hWnd, int bRevert)>('GetSystemMenu'); expect(GetSystemMenu, isA<Function>()); }); test('Can instantiate GetSystemMetrics', () { final user32 = DynamicLibrary.open('user32.dll'); final GetSystemMetrics = user32.lookupFunction< Int32 Function(Uint32 nIndex), int Function(int nIndex)>('GetSystemMetrics'); expect(GetSystemMetrics, isA<Function>()); }); if (windowsBuildNumber >= 14393) { test('Can instantiate GetSystemMetricsForDpi', () { final user32 = DynamicLibrary.open('user32.dll'); final GetSystemMetricsForDpi = user32.lookupFunction< Int32 Function(Int32 nIndex, Uint32 dpi), int Function(int nIndex, int dpi)>('GetSystemMetricsForDpi'); expect(GetSystemMetricsForDpi, isA<Function>()); }); } test('Can instantiate GetTabbedTextExtent', () { final user32 = DynamicLibrary.open('user32.dll'); final GetTabbedTextExtent = user32.lookupFunction< Uint32 Function(IntPtr hdc, Pointer<Utf16> lpString, Int32 chCount, Int32 nTabPositions, Pointer<Int32> lpnTabStopPositions), int Function( int hdc, Pointer<Utf16> lpString, int chCount, int nTabPositions, Pointer<Int32> lpnTabStopPositions)>('GetTabbedTextExtentW'); expect(GetTabbedTextExtent, isA<Function>()); }); test('Can instantiate GetThreadDesktop', () { final user32 = DynamicLibrary.open('user32.dll'); final GetThreadDesktop = user32.lookupFunction< IntPtr Function(Uint32 dwThreadId), int Function(int dwThreadId)>('GetThreadDesktop'); expect(GetThreadDesktop, isA<Function>()); }); if (windowsBuildNumber >= 14393) { test('Can instantiate GetThreadDpiAwarenessContext', () { final user32 = DynamicLibrary.open('user32.dll'); final GetThreadDpiAwarenessContext = user32.lookupFunction<IntPtr Function(), int Function()>( 'GetThreadDpiAwarenessContext'); expect(GetThreadDpiAwarenessContext, isA<Function>()); }); } if (windowsBuildNumber >= 17134) { test('Can instantiate GetThreadDpiHostingBehavior', () { final user32 = DynamicLibrary.open('user32.dll'); final GetThreadDpiHostingBehavior = user32.lookupFunction<Int32 Function(), int Function()>( 'GetThreadDpiHostingBehavior'); expect(GetThreadDpiHostingBehavior, isA<Function>()); }); } test('Can instantiate GetTitleBarInfo', () { final user32 = DynamicLibrary.open('user32.dll'); final GetTitleBarInfo = user32.lookupFunction< Int32 Function(IntPtr hwnd, Pointer<TITLEBARINFO> pti), int Function(int hwnd, Pointer<TITLEBARINFO> pti)>('GetTitleBarInfo'); expect(GetTitleBarInfo, isA<Function>()); }); test('Can instantiate GetTopWindow', () { final user32 = DynamicLibrary.open('user32.dll'); final GetTopWindow = user32.lookupFunction<IntPtr Function(IntPtr hWnd), int Function(int hWnd)>('GetTopWindow'); expect(GetTopWindow, isA<Function>()); }); test('Can instantiate GetTouchInputInfo', () { final user32 = DynamicLibrary.open('user32.dll'); final GetTouchInputInfo = user32.lookupFunction< Int32 Function(IntPtr hTouchInput, Uint32 cInputs, Pointer<TOUCHINPUT> pInputs, Int32 cbSize), int Function(int hTouchInput, int cInputs, Pointer<TOUCHINPUT> pInputs, int cbSize)>('GetTouchInputInfo'); expect(GetTouchInputInfo, isA<Function>()); }); test('Can instantiate GetUpdatedClipboardFormats', () { final user32 = DynamicLibrary.open('user32.dll'); final GetUpdatedClipboardFormats = user32.lookupFunction< Int32 Function(Pointer<Uint32> lpuiFormats, Uint32 cFormats, Pointer<Uint32> pcFormatsOut), int Function(Pointer<Uint32> lpuiFormats, int cFormats, Pointer<Uint32> pcFormatsOut)>('GetUpdatedClipboardFormats'); expect(GetUpdatedClipboardFormats, isA<Function>()); }); test('Can instantiate GetUpdateRect', () { final user32 = DynamicLibrary.open('user32.dll'); final GetUpdateRect = user32.lookupFunction< Int32 Function(IntPtr hWnd, Pointer<RECT> lpRect, Int32 bErase), int Function( int hWnd, Pointer<RECT> lpRect, int bErase)>('GetUpdateRect'); expect(GetUpdateRect, isA<Function>()); }); test('Can instantiate GetUpdateRgn', () { final user32 = DynamicLibrary.open('user32.dll'); final GetUpdateRgn = user32.lookupFunction< Int32 Function(IntPtr hWnd, IntPtr hRgn, Int32 bErase), int Function(int hWnd, int hRgn, int bErase)>('GetUpdateRgn'); expect(GetUpdateRgn, isA<Function>()); }); test('Can instantiate GetUserObjectInformation', () { final user32 = DynamicLibrary.open('user32.dll'); final GetUserObjectInformation = user32.lookupFunction< Int32 Function(IntPtr hObj, Uint32 nIndex, Pointer pvInfo, Uint32 nLength, Pointer<Uint32> lpnLengthNeeded), int Function(int hObj, int nIndex, Pointer pvInfo, int nLength, Pointer<Uint32> lpnLengthNeeded)>('GetUserObjectInformationW'); expect(GetUserObjectInformation, isA<Function>()); }); test('Can instantiate GetWindow', () { final user32 = DynamicLibrary.open('user32.dll'); final GetWindow = user32.lookupFunction< IntPtr Function(IntPtr hWnd, Uint32 uCmd), int Function(int hWnd, int uCmd)>('GetWindow'); expect(GetWindow, isA<Function>()); }); test('Can instantiate GetWindowDC', () { final user32 = DynamicLibrary.open('user32.dll'); final GetWindowDC = user32.lookupFunction<IntPtr Function(IntPtr hWnd), int Function(int hWnd)>('GetWindowDC'); expect(GetWindowDC, isA<Function>()); }); test('Can instantiate GetWindowDisplayAffinity', () { final user32 = DynamicLibrary.open('user32.dll'); final GetWindowDisplayAffinity = user32.lookupFunction< Int32 Function(IntPtr hWnd, Pointer<Uint32> pdwAffinity), int Function(int hWnd, Pointer<Uint32> pdwAffinity)>('GetWindowDisplayAffinity'); expect(GetWindowDisplayAffinity, isA<Function>()); }); if (windowsBuildNumber >= 14393) { test('Can instantiate GetWindowDpiAwarenessContext', () { final user32 = DynamicLibrary.open('user32.dll'); final GetWindowDpiAwarenessContext = user32.lookupFunction< IntPtr Function(IntPtr hwnd), int Function(int hwnd)>('GetWindowDpiAwarenessContext'); expect(GetWindowDpiAwarenessContext, isA<Function>()); }); } if (windowsBuildNumber >= 17134) { test('Can instantiate GetWindowDpiHostingBehavior', () { final user32 = DynamicLibrary.open('user32.dll'); final GetWindowDpiHostingBehavior = user32.lookupFunction< Int32 Function(IntPtr hwnd), int Function(int hwnd)>('GetWindowDpiHostingBehavior'); expect(GetWindowDpiHostingBehavior, isA<Function>()); }); } test('Can instantiate GetWindowInfo', () { final user32 = DynamicLibrary.open('user32.dll'); final GetWindowInfo = user32.lookupFunction< Int32 Function(IntPtr hwnd, Pointer<WINDOWINFO> pwi), int Function(int hwnd, Pointer<WINDOWINFO> pwi)>('GetWindowInfo'); expect(GetWindowInfo, isA<Function>()); }); test('Can instantiate GetWindowLongPtr', () { final user32 = DynamicLibrary.open('user32.dll'); final GetWindowLongPtr = user32.lookupFunction< IntPtr Function(IntPtr hWnd, Int32 nIndex), int Function(int hWnd, int nIndex)>('GetWindowLongPtrW'); expect(GetWindowLongPtr, isA<Function>()); }); test('Can instantiate GetWindowModuleFileName', () { final user32 = DynamicLibrary.open('user32.dll'); final GetWindowModuleFileName = user32.lookupFunction< Uint32 Function( IntPtr hwnd, Pointer<Utf16> pszFileName, Uint32 cchFileNameMax), int Function(int hwnd, Pointer<Utf16> pszFileName, int cchFileNameMax)>('GetWindowModuleFileNameW'); expect(GetWindowModuleFileName, isA<Function>()); }); test('Can instantiate GetWindowPlacement', () { final user32 = DynamicLibrary.open('user32.dll'); final GetWindowPlacement = user32.lookupFunction< Int32 Function(IntPtr hWnd, Pointer<WINDOWPLACEMENT> lpwndpl), int Function(int hWnd, Pointer<WINDOWPLACEMENT> lpwndpl)>('GetWindowPlacement'); expect(GetWindowPlacement, isA<Function>()); }); test('Can instantiate GetWindowRect', () { final user32 = DynamicLibrary.open('user32.dll'); final GetWindowRect = user32.lookupFunction< Int32 Function(IntPtr hWnd, Pointer<RECT> lpRect), int Function(int hWnd, Pointer<RECT> lpRect)>('GetWindowRect'); expect(GetWindowRect, isA<Function>()); }); test('Can instantiate GetWindowRgn', () { final user32 = DynamicLibrary.open('user32.dll'); final GetWindowRgn = user32.lookupFunction< Int32 Function(IntPtr hWnd, IntPtr hRgn), int Function(int hWnd, int hRgn)>('GetWindowRgn'); expect(GetWindowRgn, isA<Function>()); }); test('Can instantiate GetWindowRgnBox', () { final user32 = DynamicLibrary.open('user32.dll'); final GetWindowRgnBox = user32.lookupFunction< Int32 Function(IntPtr hWnd, Pointer<RECT> lprc), int Function(int hWnd, Pointer<RECT> lprc)>('GetWindowRgnBox'); expect(GetWindowRgnBox, isA<Function>()); }); test('Can instantiate GetWindowText', () { final user32 = DynamicLibrary.open('user32.dll'); final GetWindowText = user32.lookupFunction< Int32 Function(IntPtr hWnd, Pointer<Utf16> lpString, Int32 nMaxCount), int Function(int hWnd, Pointer<Utf16> lpString, int nMaxCount)>('GetWindowTextW'); expect(GetWindowText, isA<Function>()); }); test('Can instantiate GetWindowTextLength', () { final user32 = DynamicLibrary.open('user32.dll'); final GetWindowTextLength = user32.lookupFunction< Int32 Function(IntPtr hWnd), int Function(int hWnd)>('GetWindowTextLengthW'); expect(GetWindowTextLength, isA<Function>()); }); test('Can instantiate GetWindowThreadProcessId', () { final user32 = DynamicLibrary.open('user32.dll'); final GetWindowThreadProcessId = user32.lookupFunction< Uint32 Function(IntPtr hWnd, Pointer<Uint32> lpdwProcessId), int Function(int hWnd, Pointer<Uint32> lpdwProcessId)>('GetWindowThreadProcessId'); expect(GetWindowThreadProcessId, isA<Function>()); }); test('Can instantiate GrayString', () { final user32 = DynamicLibrary.open('user32.dll'); final GrayString = user32.lookupFunction< Int32 Function( IntPtr hDC, IntPtr hBrush, Pointer<NativeFunction<OutputProc>> lpOutputFunc, IntPtr lpData, Int32 nCount, Int32 X, Int32 Y, Int32 nWidth, Int32 nHeight), int Function( int hDC, int hBrush, Pointer<NativeFunction<OutputProc>> lpOutputFunc, int lpData, int nCount, int X, int Y, int nWidth, int nHeight)>('GrayStringW'); expect(GrayString, isA<Function>()); }); test('Can instantiate HideCaret', () { final user32 = DynamicLibrary.open('user32.dll'); final HideCaret = user32.lookupFunction<Int32 Function(IntPtr hWnd), int Function(int hWnd)>('HideCaret'); expect(HideCaret, isA<Function>()); }); test('Can instantiate InflateRect', () { final user32 = DynamicLibrary.open('user32.dll'); final InflateRect = user32.lookupFunction< Int32 Function(Pointer<RECT> lprc, Int32 dx, Int32 dy), int Function(Pointer<RECT> lprc, int dx, int dy)>('InflateRect'); expect(InflateRect, isA<Function>()); }); test('Can instantiate InSendMessage', () { final user32 = DynamicLibrary.open('user32.dll'); final InSendMessage = user32 .lookupFunction<Int32 Function(), int Function()>('InSendMessage'); expect(InSendMessage, isA<Function>()); }); test('Can instantiate InSendMessageEx', () { final user32 = DynamicLibrary.open('user32.dll'); final InSendMessageEx = user32.lookupFunction< Uint32 Function(Pointer lpReserved), int Function(Pointer lpReserved)>('InSendMessageEx'); expect(InSendMessageEx, isA<Function>()); }); test('Can instantiate InsertMenu', () { final user32 = DynamicLibrary.open('user32.dll'); final InsertMenu = user32.lookupFunction< Int32 Function(IntPtr hMenu, Uint32 uPosition, Uint32 uFlags, IntPtr uIDNewItem, Pointer<Utf16> lpNewItem), int Function(int hMenu, int uPosition, int uFlags, int uIDNewItem, Pointer<Utf16> lpNewItem)>('InsertMenuW'); expect(InsertMenu, isA<Function>()); }); test('Can instantiate InsertMenuItem', () { final user32 = DynamicLibrary.open('user32.dll'); final InsertMenuItem = user32.lookupFunction< Int32 Function(IntPtr hmenu, Uint32 item, Int32 fByPosition, Pointer<MENUITEMINFO> lpmi), int Function(int hmenu, int item, int fByPosition, Pointer<MENUITEMINFO> lpmi)>('InsertMenuItemW'); expect(InsertMenuItem, isA<Function>()); }); test('Can instantiate IntersectRect', () { final user32 = DynamicLibrary.open('user32.dll'); final IntersectRect = user32.lookupFunction< Int32 Function(Pointer<RECT> lprcDst, Pointer<RECT> lprcSrc1, Pointer<RECT> lprcSrc2), int Function(Pointer<RECT> lprcDst, Pointer<RECT> lprcSrc1, Pointer<RECT> lprcSrc2)>('IntersectRect'); expect(IntersectRect, isA<Function>()); }); test('Can instantiate InvalidateRect', () { final user32 = DynamicLibrary.open('user32.dll'); final InvalidateRect = user32.lookupFunction< Int32 Function(IntPtr hWnd, Pointer<RECT> lpRect, Int32 bErase), int Function( int hWnd, Pointer<RECT> lpRect, int bErase)>('InvalidateRect'); expect(InvalidateRect, isA<Function>()); }); test('Can instantiate InvalidateRgn', () { final user32 = DynamicLibrary.open('user32.dll'); final InvalidateRgn = user32.lookupFunction< Int32 Function(IntPtr hWnd, IntPtr hRgn, Int32 bErase), int Function(int hWnd, int hRgn, int bErase)>('InvalidateRgn'); expect(InvalidateRgn, isA<Function>()); }); test('Can instantiate InvertRect', () { final user32 = DynamicLibrary.open('user32.dll'); final InvertRect = user32.lookupFunction< Int32 Function(IntPtr hDC, Pointer<RECT> lprc), int Function(int hDC, Pointer<RECT> lprc)>('InvertRect'); expect(InvertRect, isA<Function>()); }); test('Can instantiate IsChild', () { final user32 = DynamicLibrary.open('user32.dll'); final IsChild = user32.lookupFunction< Int32 Function(IntPtr hWndParent, IntPtr hWnd), int Function(int hWndParent, int hWnd)>('IsChild'); expect(IsChild, isA<Function>()); }); test('Can instantiate IsClipboardFormatAvailable', () { final user32 = DynamicLibrary.open('user32.dll'); final IsClipboardFormatAvailable = user32.lookupFunction< Int32 Function(Uint32 format), int Function(int format)>('IsClipboardFormatAvailable'); expect(IsClipboardFormatAvailable, isA<Function>()); }); test('Can instantiate IsDialogMessage', () { final user32 = DynamicLibrary.open('user32.dll'); final IsDialogMessage = user32.lookupFunction< Int32 Function(IntPtr hDlg, Pointer<MSG> lpMsg), int Function(int hDlg, Pointer<MSG> lpMsg)>('IsDialogMessageW'); expect(IsDialogMessage, isA<Function>()); }); test('Can instantiate IsDlgButtonChecked', () { final user32 = DynamicLibrary.open('user32.dll'); final IsDlgButtonChecked = user32.lookupFunction< Uint32 Function(IntPtr hDlg, Int32 nIDButton), int Function(int hDlg, int nIDButton)>('IsDlgButtonChecked'); expect(IsDlgButtonChecked, isA<Function>()); }); test('Can instantiate IsGUIThread', () { final user32 = DynamicLibrary.open('user32.dll'); final IsGUIThread = user32.lookupFunction<Int32 Function(Int32 bConvert), int Function(int bConvert)>('IsGUIThread'); expect(IsGUIThread, isA<Function>()); }); test('Can instantiate IsHungAppWindow', () { final user32 = DynamicLibrary.open('user32.dll'); final IsHungAppWindow = user32.lookupFunction<Int32 Function(IntPtr hwnd), int Function(int hwnd)>('IsHungAppWindow'); expect(IsHungAppWindow, isA<Function>()); }); test('Can instantiate IsIconic', () { final user32 = DynamicLibrary.open('user32.dll'); final IsIconic = user32.lookupFunction<Int32 Function(IntPtr hWnd), int Function(int hWnd)>('IsIconic'); expect(IsIconic, isA<Function>()); }); if (windowsBuildNumber >= 9200) { test('Can instantiate IsImmersiveProcess', () { final user32 = DynamicLibrary.open('user32.dll'); final IsImmersiveProcess = user32.lookupFunction< Int32 Function(IntPtr hProcess), int Function(int hProcess)>('IsImmersiveProcess'); expect(IsImmersiveProcess, isA<Function>()); }); } test('Can instantiate IsMenu', () { final user32 = DynamicLibrary.open('user32.dll'); final IsMenu = user32.lookupFunction<Int32 Function(IntPtr hMenu), int Function(int hMenu)>('IsMenu'); expect(IsMenu, isA<Function>()); }); test('Can instantiate IsProcessDPIAware', () { final user32 = DynamicLibrary.open('user32.dll'); final IsProcessDPIAware = user32.lookupFunction<Int32 Function(), int Function()>( 'IsProcessDPIAware'); expect(IsProcessDPIAware, isA<Function>()); }); test('Can instantiate IsRectEmpty', () { final user32 = DynamicLibrary.open('user32.dll'); final IsRectEmpty = user32.lookupFunction< Int32 Function(Pointer<RECT> lprc), int Function(Pointer<RECT> lprc)>('IsRectEmpty'); expect(IsRectEmpty, isA<Function>()); }); test('Can instantiate IsTouchWindow', () { final user32 = DynamicLibrary.open('user32.dll'); final IsTouchWindow = user32.lookupFunction< Int32 Function(IntPtr hwnd, Pointer<Uint32> pulFlags), int Function(int hwnd, Pointer<Uint32> pulFlags)>('IsTouchWindow'); expect(IsTouchWindow, isA<Function>()); }); if (windowsBuildNumber >= 14393) { test('Can instantiate IsValidDpiAwarenessContext', () { final user32 = DynamicLibrary.open('user32.dll'); final IsValidDpiAwarenessContext = user32.lookupFunction< Int32 Function(IntPtr value), int Function(int value)>('IsValidDpiAwarenessContext'); expect(IsValidDpiAwarenessContext, isA<Function>()); }); } test('Can instantiate IsWindow', () { final user32 = DynamicLibrary.open('user32.dll'); final IsWindow = user32.lookupFunction<Int32 Function(IntPtr hWnd), int Function(int hWnd)>('IsWindow'); expect(IsWindow, isA<Function>()); }); test('Can instantiate IsWindowEnabled', () { final user32 = DynamicLibrary.open('user32.dll'); final IsWindowEnabled = user32.lookupFunction<Int32 Function(IntPtr hWnd), int Function(int hWnd)>('IsWindowEnabled'); expect(IsWindowEnabled, isA<Function>()); }); test('Can instantiate IsWindowUnicode', () { final user32 = DynamicLibrary.open('user32.dll'); final IsWindowUnicode = user32.lookupFunction<Int32 Function(IntPtr hWnd), int Function(int hWnd)>('IsWindowUnicode'); expect(IsWindowUnicode, isA<Function>()); }); test('Can instantiate IsWindowVisible', () { final user32 = DynamicLibrary.open('user32.dll'); final IsWindowVisible = user32.lookupFunction<Int32 Function(IntPtr hWnd), int Function(int hWnd)>('IsWindowVisible'); expect(IsWindowVisible, isA<Function>()); }); test('Can instantiate IsWow64Message', () { final user32 = DynamicLibrary.open('user32.dll'); final IsWow64Message = user32 .lookupFunction<Int32 Function(), int Function()>('IsWow64Message'); expect(IsWow64Message, isA<Function>()); }); test('Can instantiate IsZoomed', () { final user32 = DynamicLibrary.open('user32.dll'); final IsZoomed = user32.lookupFunction<Int32 Function(IntPtr hWnd), int Function(int hWnd)>('IsZoomed'); expect(IsZoomed, isA<Function>()); }); test('Can instantiate KillTimer', () { final user32 = DynamicLibrary.open('user32.dll'); final KillTimer = user32.lookupFunction< Int32 Function(IntPtr hWnd, IntPtr uIDEvent), int Function(int hWnd, int uIDEvent)>('KillTimer'); expect(KillTimer, isA<Function>()); }); test('Can instantiate LoadAccelerators', () { final user32 = DynamicLibrary.open('user32.dll'); final LoadAccelerators = user32.lookupFunction< IntPtr Function(IntPtr hInstance, Pointer<Utf16> lpTableName), int Function( int hInstance, Pointer<Utf16> lpTableName)>('LoadAcceleratorsW'); expect(LoadAccelerators, isA<Function>()); }); test('Can instantiate LoadCursor', () { final user32 = DynamicLibrary.open('user32.dll'); final LoadCursor = user32.lookupFunction< IntPtr Function(IntPtr hInstance, Pointer<Utf16> lpCursorName), int Function( int hInstance, Pointer<Utf16> lpCursorName)>('LoadCursorW'); expect(LoadCursor, isA<Function>()); }); test('Can instantiate LoadCursorFromFile', () { final user32 = DynamicLibrary.open('user32.dll'); final LoadCursorFromFile = user32.lookupFunction< IntPtr Function(Pointer<Utf16> lpFileName), int Function(Pointer<Utf16> lpFileName)>('LoadCursorFromFileW'); expect(LoadCursorFromFile, isA<Function>()); }); test('Can instantiate LoadIcon', () { final user32 = DynamicLibrary.open('user32.dll'); final LoadIcon = user32.lookupFunction< IntPtr Function(IntPtr hInstance, Pointer<Utf16> lpIconName), int Function(int hInstance, Pointer<Utf16> lpIconName)>('LoadIconW'); expect(LoadIcon, isA<Function>()); }); test('Can instantiate LoadImage', () { final user32 = DynamicLibrary.open('user32.dll'); final LoadImage = user32.lookupFunction< IntPtr Function(IntPtr hInst, Pointer<Utf16> name, Uint32 type, Int32 cx, Int32 cy, Uint32 fuLoad), int Function(int hInst, Pointer<Utf16> name, int type, int cx, int cy, int fuLoad)>('LoadImageW'); expect(LoadImage, isA<Function>()); }); test('Can instantiate LoadKeyboardLayout', () { final user32 = DynamicLibrary.open('user32.dll'); final LoadKeyboardLayout = user32.lookupFunction< IntPtr Function(Pointer<Utf16> pwszKLID, Uint32 Flags), int Function( Pointer<Utf16> pwszKLID, int Flags)>('LoadKeyboardLayoutW'); expect(LoadKeyboardLayout, isA<Function>()); }); test('Can instantiate LoadMenuIndirect', () { final user32 = DynamicLibrary.open('user32.dll'); final LoadMenuIndirect = user32.lookupFunction< IntPtr Function(Pointer lpMenuTemplate), int Function(Pointer lpMenuTemplate)>('LoadMenuIndirectW'); expect(LoadMenuIndirect, isA<Function>()); }); test('Can instantiate LoadString', () { final user32 = DynamicLibrary.open('user32.dll'); final LoadString = user32.lookupFunction< Int32 Function(IntPtr hInstance, Uint32 uID, Pointer<Utf16> lpBuffer, Int32 cchBufferMax), int Function(int hInstance, int uID, Pointer<Utf16> lpBuffer, int cchBufferMax)>('LoadStringW'); expect(LoadString, isA<Function>()); }); test('Can instantiate LockSetForegroundWindow', () { final user32 = DynamicLibrary.open('user32.dll'); final LockSetForegroundWindow = user32.lookupFunction< Int32 Function(Uint32 uLockCode), int Function(int uLockCode)>('LockSetForegroundWindow'); expect(LockSetForegroundWindow, isA<Function>()); }); test('Can instantiate LockWindowUpdate', () { final user32 = DynamicLibrary.open('user32.dll'); final LockWindowUpdate = user32.lookupFunction< Int32 Function(IntPtr hWndLock), int Function(int hWndLock)>('LockWindowUpdate'); expect(LockWindowUpdate, isA<Function>()); }); test('Can instantiate LockWorkStation', () { final user32 = DynamicLibrary.open('user32.dll'); final LockWorkStation = user32 .lookupFunction<Int32 Function(), int Function()>('LockWorkStation'); expect(LockWorkStation, isA<Function>()); }); test('Can instantiate LogicalToPhysicalPoint', () { final user32 = DynamicLibrary.open('user32.dll'); final LogicalToPhysicalPoint = user32.lookupFunction< Int32 Function(IntPtr hWnd, Pointer<POINT> lpPoint), int Function( int hWnd, Pointer<POINT> lpPoint)>('LogicalToPhysicalPoint'); expect(LogicalToPhysicalPoint, isA<Function>()); }); if (windowsBuildNumber >= 9600) { test('Can instantiate LogicalToPhysicalPointForPerMonitorDPI', () { final user32 = DynamicLibrary.open('user32.dll'); final LogicalToPhysicalPointForPerMonitorDPI = user32.lookupFunction< Int32 Function(IntPtr hWnd, Pointer<POINT> lpPoint), int Function(int hWnd, Pointer<POINT> lpPoint)>( 'LogicalToPhysicalPointForPerMonitorDPI'); expect(LogicalToPhysicalPointForPerMonitorDPI, isA<Function>()); }); } test('Can instantiate LookupIconIdFromDirectory', () { final user32 = DynamicLibrary.open('user32.dll'); final LookupIconIdFromDirectory = user32.lookupFunction< Int32 Function(Pointer<Uint8> presbits, Int32 fIcon), int Function( Pointer<Uint8> presbits, int fIcon)>('LookupIconIdFromDirectory'); expect(LookupIconIdFromDirectory, isA<Function>()); }); test('Can instantiate LookupIconIdFromDirectoryEx', () { final user32 = DynamicLibrary.open('user32.dll'); final LookupIconIdFromDirectoryEx = user32.lookupFunction< Int32 Function(Pointer<Uint8> presbits, Int32 fIcon, Int32 cxDesired, Int32 cyDesired, Uint32 Flags), int Function(Pointer<Uint8> presbits, int fIcon, int cxDesired, int cyDesired, int Flags)>('LookupIconIdFromDirectoryEx'); expect(LookupIconIdFromDirectoryEx, isA<Function>()); }); test('Can instantiate MapDialogRect', () { final user32 = DynamicLibrary.open('user32.dll'); final MapDialogRect = user32.lookupFunction< Int32 Function(IntPtr hDlg, Pointer<RECT> lpRect), int Function(int hDlg, Pointer<RECT> lpRect)>('MapDialogRect'); expect(MapDialogRect, isA<Function>()); }); test('Can instantiate MapVirtualKey', () { final user32 = DynamicLibrary.open('user32.dll'); final MapVirtualKey = user32.lookupFunction< Uint32 Function(Uint32 uCode, Uint32 uMapType), int Function(int uCode, int uMapType)>('MapVirtualKeyW'); expect(MapVirtualKey, isA<Function>()); }); test('Can instantiate MapVirtualKeyEx', () { final user32 = DynamicLibrary.open('user32.dll'); final MapVirtualKeyEx = user32.lookupFunction< Uint32 Function(Uint32 uCode, Uint32 uMapType, IntPtr dwhkl), int Function(int uCode, int uMapType, int dwhkl)>('MapVirtualKeyExW'); expect(MapVirtualKeyEx, isA<Function>()); }); test('Can instantiate MapWindowPoints', () { final user32 = DynamicLibrary.open('user32.dll'); final MapWindowPoints = user32.lookupFunction< Int32 Function(IntPtr hWndFrom, IntPtr hWndTo, Pointer<POINT> lpPoints, Uint32 cPoints), int Function(int hWndFrom, int hWndTo, Pointer<POINT> lpPoints, int cPoints)>('MapWindowPoints'); expect(MapWindowPoints, isA<Function>()); }); test('Can instantiate MenuItemFromPoint', () { final user32 = DynamicLibrary.open('user32.dll'); final MenuItemFromPoint = user32.lookupFunction< Int32 Function(IntPtr hWnd, IntPtr hMenu, POINT ptScreen), int Function( int hWnd, int hMenu, POINT ptScreen)>('MenuItemFromPoint'); expect(MenuItemFromPoint, isA<Function>()); }); test('Can instantiate MessageBox', () { final user32 = DynamicLibrary.open('user32.dll'); final MessageBox = user32.lookupFunction< Int32 Function(IntPtr hWnd, Pointer<Utf16> lpText, Pointer<Utf16> lpCaption, Uint32 uType), int Function(int hWnd, Pointer<Utf16> lpText, Pointer<Utf16> lpCaption, int uType)>('MessageBoxW'); expect(MessageBox, isA<Function>()); }); test('Can instantiate MessageBoxEx', () { final user32 = DynamicLibrary.open('user32.dll'); final MessageBoxEx = user32.lookupFunction< Int32 Function(IntPtr hWnd, Pointer<Utf16> lpText, Pointer<Utf16> lpCaption, Uint32 uType, Uint16 wLanguageId), int Function( int hWnd, Pointer<Utf16> lpText, Pointer<Utf16> lpCaption, int uType, int wLanguageId)>('MessageBoxExW'); expect(MessageBoxEx, isA<Function>()); }); test('Can instantiate ModifyMenu', () { final user32 = DynamicLibrary.open('user32.dll'); final ModifyMenu = user32.lookupFunction< Int32 Function(IntPtr hMnu, Uint32 uPosition, Uint32 uFlags, IntPtr uIDNewItem, Pointer<Utf16> lpNewItem), int Function(int hMnu, int uPosition, int uFlags, int uIDNewItem, Pointer<Utf16> lpNewItem)>('ModifyMenuW'); expect(ModifyMenu, isA<Function>()); }); test('Can instantiate MonitorFromPoint', () { final user32 = DynamicLibrary.open('user32.dll'); final MonitorFromPoint = user32.lookupFunction< IntPtr Function(POINT pt, Uint32 dwFlags), int Function(POINT pt, int dwFlags)>('MonitorFromPoint'); expect(MonitorFromPoint, isA<Function>()); }); test('Can instantiate MonitorFromRect', () { final user32 = DynamicLibrary.open('user32.dll'); final MonitorFromRect = user32.lookupFunction< IntPtr Function(Pointer<RECT> lprc, Uint32 dwFlags), int Function(Pointer<RECT> lprc, int dwFlags)>('MonitorFromRect'); expect(MonitorFromRect, isA<Function>()); }); test('Can instantiate MonitorFromWindow', () { final user32 = DynamicLibrary.open('user32.dll'); final MonitorFromWindow = user32.lookupFunction< IntPtr Function(IntPtr hwnd, Uint32 dwFlags), int Function(int hwnd, int dwFlags)>('MonitorFromWindow'); expect(MonitorFromWindow, isA<Function>()); }); test('Can instantiate MoveWindow', () { final user32 = DynamicLibrary.open('user32.dll'); final MoveWindow = user32.lookupFunction< Int32 Function(IntPtr hWnd, Int32 X, Int32 Y, Int32 nWidth, Int32 nHeight, Int32 bRepaint), int Function(int hWnd, int X, int Y, int nWidth, int nHeight, int bRepaint)>('MoveWindow'); expect(MoveWindow, isA<Function>()); }); test('Can instantiate MsgWaitForMultipleObjects', () { final user32 = DynamicLibrary.open('user32.dll'); final MsgWaitForMultipleObjects = user32.lookupFunction< Uint32 Function(Uint32 nCount, Pointer<IntPtr> pHandles, Int32 fWaitAll, Uint32 dwMilliseconds, Uint32 dwWakeMask), int Function(int nCount, Pointer<IntPtr> pHandles, int fWaitAll, int dwMilliseconds, int dwWakeMask)>('MsgWaitForMultipleObjects'); expect(MsgWaitForMultipleObjects, isA<Function>()); }); test('Can instantiate MsgWaitForMultipleObjectsEx', () { final user32 = DynamicLibrary.open('user32.dll'); final MsgWaitForMultipleObjectsEx = user32.lookupFunction< Uint32 Function(Uint32 nCount, Pointer<IntPtr> pHandles, Uint32 dwMilliseconds, Uint32 dwWakeMask, Uint32 dwFlags), int Function(int nCount, Pointer<IntPtr> pHandles, int dwMilliseconds, int dwWakeMask, int dwFlags)>('MsgWaitForMultipleObjectsEx'); expect(MsgWaitForMultipleObjectsEx, isA<Function>()); }); test('Can instantiate NotifyWinEvent', () { final user32 = DynamicLibrary.open('user32.dll'); final NotifyWinEvent = user32.lookupFunction< Void Function( Uint32 event, IntPtr hwnd, Int32 idObject, Int32 idChild), void Function(int event, int hwnd, int idObject, int idChild)>('NotifyWinEvent'); expect(NotifyWinEvent, isA<Function>()); }); test('Can instantiate OemKeyScan', () { final user32 = DynamicLibrary.open('user32.dll'); final OemKeyScan = user32.lookupFunction<Uint32 Function(Uint16 wOemChar), int Function(int wOemChar)>('OemKeyScan'); expect(OemKeyScan, isA<Function>()); }); test('Can instantiate OffsetRect', () { final user32 = DynamicLibrary.open('user32.dll'); final OffsetRect = user32.lookupFunction< Int32 Function(Pointer<RECT> lprc, Int32 dx, Int32 dy), int Function(Pointer<RECT> lprc, int dx, int dy)>('OffsetRect'); expect(OffsetRect, isA<Function>()); }); test('Can instantiate OpenClipboard', () { final user32 = DynamicLibrary.open('user32.dll'); final OpenClipboard = user32.lookupFunction< Int32 Function(IntPtr hWndNewOwner), int Function(int hWndNewOwner)>('OpenClipboard'); expect(OpenClipboard, isA<Function>()); }); test('Can instantiate OpenDesktop', () { final user32 = DynamicLibrary.open('user32.dll'); final OpenDesktop = user32.lookupFunction< IntPtr Function(Pointer<Utf16> lpszDesktop, Uint32 dwFlags, Int32 fInherit, Uint32 dwDesiredAccess), int Function(Pointer<Utf16> lpszDesktop, int dwFlags, int fInherit, int dwDesiredAccess)>('OpenDesktopW'); expect(OpenDesktop, isA<Function>()); }); test('Can instantiate OpenIcon', () { final user32 = DynamicLibrary.open('user32.dll'); final OpenIcon = user32.lookupFunction<Int32 Function(IntPtr hWnd), int Function(int hWnd)>('OpenIcon'); expect(OpenIcon, isA<Function>()); }); test('Can instantiate OpenInputDesktop', () { final user32 = DynamicLibrary.open('user32.dll'); final OpenInputDesktop = user32.lookupFunction< IntPtr Function( Uint32 dwFlags, Int32 fInherit, Uint32 dwDesiredAccess), int Function(int dwFlags, int fInherit, int dwDesiredAccess)>('OpenInputDesktop'); expect(OpenInputDesktop, isA<Function>()); }); test('Can instantiate OpenWindowStation', () { final user32 = DynamicLibrary.open('user32.dll'); final OpenWindowStation = user32.lookupFunction< IntPtr Function(Pointer<Utf16> lpszWinSta, Int32 fInherit, Uint32 dwDesiredAccess), int Function(Pointer<Utf16> lpszWinSta, int fInherit, int dwDesiredAccess)>('OpenWindowStationW'); expect(OpenWindowStation, isA<Function>()); }); test('Can instantiate PaintDesktop', () { final user32 = DynamicLibrary.open('user32.dll'); final PaintDesktop = user32.lookupFunction<Int32 Function(IntPtr hdc), int Function(int hdc)>('PaintDesktop'); expect(PaintDesktop, isA<Function>()); }); test('Can instantiate PeekMessage', () { final user32 = DynamicLibrary.open('user32.dll'); final PeekMessage = user32.lookupFunction< Int32 Function(Pointer<MSG> lpMsg, IntPtr hWnd, Uint32 wMsgFilterMin, Uint32 wMsgFilterMax, Uint32 wRemoveMsg), int Function(Pointer<MSG> lpMsg, int hWnd, int wMsgFilterMin, int wMsgFilterMax, int wRemoveMsg)>('PeekMessageW'); expect(PeekMessage, isA<Function>()); }); test('Can instantiate PhysicalToLogicalPoint', () { final user32 = DynamicLibrary.open('user32.dll'); final PhysicalToLogicalPoint = user32.lookupFunction< Int32 Function(IntPtr hWnd, Pointer<POINT> lpPoint), int Function( int hWnd, Pointer<POINT> lpPoint)>('PhysicalToLogicalPoint'); expect(PhysicalToLogicalPoint, isA<Function>()); }); if (windowsBuildNumber >= 9600) { test('Can instantiate PhysicalToLogicalPointForPerMonitorDPI', () { final user32 = DynamicLibrary.open('user32.dll'); final PhysicalToLogicalPointForPerMonitorDPI = user32.lookupFunction< Int32 Function(IntPtr hWnd, Pointer<POINT> lpPoint), int Function(int hWnd, Pointer<POINT> lpPoint)>( 'PhysicalToLogicalPointForPerMonitorDPI'); expect(PhysicalToLogicalPointForPerMonitorDPI, isA<Function>()); }); } test('Can instantiate PostMessage', () { final user32 = DynamicLibrary.open('user32.dll'); final PostMessage = user32.lookupFunction< Int32 Function(IntPtr hWnd, Uint32 Msg, IntPtr wParam, IntPtr lParam), int Function( int hWnd, int Msg, int wParam, int lParam)>('PostMessageW'); expect(PostMessage, isA<Function>()); }); test('Can instantiate PostQuitMessage', () { final user32 = DynamicLibrary.open('user32.dll'); final PostQuitMessage = user32.lookupFunction< Void Function(Int32 nExitCode), void Function(int nExitCode)>('PostQuitMessage'); expect(PostQuitMessage, isA<Function>()); }); test('Can instantiate PostThreadMessage', () { final user32 = DynamicLibrary.open('user32.dll'); final PostThreadMessage = user32.lookupFunction< Int32 Function( Uint32 idThread, Uint32 Msg, IntPtr wParam, IntPtr lParam), int Function(int idThread, int Msg, int wParam, int lParam)>('PostThreadMessageW'); expect(PostThreadMessage, isA<Function>()); }); test('Can instantiate PrintWindow', () { final user32 = DynamicLibrary.open('user32.dll'); final PrintWindow = user32.lookupFunction< Int32 Function(IntPtr hwnd, IntPtr hdcBlt, Uint32 nFlags), int Function(int hwnd, int hdcBlt, int nFlags)>('PrintWindow'); expect(PrintWindow, isA<Function>()); }); test('Can instantiate PtInRect', () { final user32 = DynamicLibrary.open('user32.dll'); final PtInRect = user32.lookupFunction< Int32 Function(Pointer<RECT> lprc, POINT pt), int Function(Pointer<RECT> lprc, POINT pt)>('PtInRect'); expect(PtInRect, isA<Function>()); }); test('Can instantiate RedrawWindow', () { final user32 = DynamicLibrary.open('user32.dll'); final RedrawWindow = user32.lookupFunction< Int32 Function(IntPtr hWnd, Pointer<RECT> lprcUpdate, IntPtr hrgnUpdate, Uint32 flags), int Function(int hWnd, Pointer<RECT> lprcUpdate, int hrgnUpdate, int flags)>('RedrawWindow'); expect(RedrawWindow, isA<Function>()); }); test('Can instantiate RegisterClass', () { final user32 = DynamicLibrary.open('user32.dll'); final RegisterClass = user32.lookupFunction< Uint16 Function(Pointer<WNDCLASS> lpWndClass), int Function(Pointer<WNDCLASS> lpWndClass)>('RegisterClassW'); expect(RegisterClass, isA<Function>()); }); test('Can instantiate RegisterClassEx', () { final user32 = DynamicLibrary.open('user32.dll'); final RegisterClassEx = user32.lookupFunction< Uint16 Function(Pointer<WNDCLASSEX> param0), int Function(Pointer<WNDCLASSEX> param0)>('RegisterClassExW'); expect(RegisterClassEx, isA<Function>()); }); test('Can instantiate RegisterClipboardFormat', () { final user32 = DynamicLibrary.open('user32.dll'); final RegisterClipboardFormat = user32.lookupFunction< Uint32 Function(Pointer<Utf16> lpszFormat), int Function(Pointer<Utf16> lpszFormat)>('RegisterClipboardFormatW'); expect(RegisterClipboardFormat, isA<Function>()); }); test('Can instantiate RegisterHotKey', () { final user32 = DynamicLibrary.open('user32.dll'); final RegisterHotKey = user32.lookupFunction< Int32 Function(IntPtr hWnd, Int32 id, Uint32 fsModifiers, Uint32 vk), int Function( int hWnd, int id, int fsModifiers, int vk)>('RegisterHotKey'); expect(RegisterHotKey, isA<Function>()); }); test('Can instantiate RegisterPowerSettingNotification', () { final user32 = DynamicLibrary.open('user32.dll'); final RegisterPowerSettingNotification = user32.lookupFunction< IntPtr Function( IntPtr hRecipient, Pointer<GUID> PowerSettingGuid, Uint32 Flags), int Function(int hRecipient, Pointer<GUID> PowerSettingGuid, int Flags)>('RegisterPowerSettingNotification'); expect(RegisterPowerSettingNotification, isA<Function>()); }); test('Can instantiate RegisterRawInputDevices', () { final user32 = DynamicLibrary.open('user32.dll'); final RegisterRawInputDevices = user32.lookupFunction< Int32 Function(Pointer<RAWINPUTDEVICE> pRawInputDevices, Uint32 uiNumDevices, Uint32 cbSize), int Function(Pointer<RAWINPUTDEVICE> pRawInputDevices, int uiNumDevices, int cbSize)>('RegisterRawInputDevices'); expect(RegisterRawInputDevices, isA<Function>()); }); if (windowsBuildNumber >= 9200) { test('Can instantiate RegisterTouchHitTestingWindow', () { final user32 = DynamicLibrary.open('user32.dll'); final RegisterTouchHitTestingWindow = user32.lookupFunction< Int32 Function(IntPtr hwnd, Uint32 value), int Function(int hwnd, int value)>('RegisterTouchHitTestingWindow'); expect(RegisterTouchHitTestingWindow, isA<Function>()); }); } test('Can instantiate RegisterTouchWindow', () { final user32 = DynamicLibrary.open('user32.dll'); final RegisterTouchWindow = user32.lookupFunction< Int32 Function(IntPtr hwnd, Uint32 ulFlags), int Function(int hwnd, int ulFlags)>('RegisterTouchWindow'); expect(RegisterTouchWindow, isA<Function>()); }); test('Can instantiate RegisterWindowMessage', () { final user32 = DynamicLibrary.open('user32.dll'); final RegisterWindowMessage = user32.lookupFunction< Uint32 Function(Pointer<Utf16> lpString), int Function(Pointer<Utf16> lpString)>('RegisterWindowMessageW'); expect(RegisterWindowMessage, isA<Function>()); }); test('Can instantiate ReleaseCapture', () { final user32 = DynamicLibrary.open('user32.dll'); final ReleaseCapture = user32 .lookupFunction<Int32 Function(), int Function()>('ReleaseCapture'); expect(ReleaseCapture, isA<Function>()); }); test('Can instantiate ReleaseDC', () { final user32 = DynamicLibrary.open('user32.dll'); final ReleaseDC = user32.lookupFunction< Int32 Function(IntPtr hWnd, IntPtr hDC), int Function(int hWnd, int hDC)>('ReleaseDC'); expect(ReleaseDC, isA<Function>()); }); test('Can instantiate RemoveClipboardFormatListener', () { final user32 = DynamicLibrary.open('user32.dll'); final RemoveClipboardFormatListener = user32.lookupFunction< Int32 Function(IntPtr hwnd), int Function(int hwnd)>('RemoveClipboardFormatListener'); expect(RemoveClipboardFormatListener, isA<Function>()); }); test('Can instantiate RemoveMenu', () { final user32 = DynamicLibrary.open('user32.dll'); final RemoveMenu = user32.lookupFunction< Int32 Function(IntPtr hMenu, Uint32 uPosition, Uint32 uFlags), int Function(int hMenu, int uPosition, int uFlags)>('RemoveMenu'); expect(RemoveMenu, isA<Function>()); }); test('Can instantiate RemoveProp', () { final user32 = DynamicLibrary.open('user32.dll'); final RemoveProp = user32.lookupFunction< IntPtr Function(IntPtr hWnd, Pointer<Utf16> lpString), int Function(int hWnd, Pointer<Utf16> lpString)>('RemovePropW'); expect(RemoveProp, isA<Function>()); }); test('Can instantiate ReplyMessage', () { final user32 = DynamicLibrary.open('user32.dll'); final ReplyMessage = user32.lookupFunction<Int32 Function(IntPtr lResult), int Function(int lResult)>('ReplyMessage'); expect(ReplyMessage, isA<Function>()); }); test('Can instantiate ScreenToClient', () { final user32 = DynamicLibrary.open('user32.dll'); final ScreenToClient = user32.lookupFunction< Int32 Function(IntPtr hWnd, Pointer<POINT> lpPoint), int Function(int hWnd, Pointer<POINT> lpPoint)>('ScreenToClient'); expect(ScreenToClient, isA<Function>()); }); test('Can instantiate ScrollDC', () { final user32 = DynamicLibrary.open('user32.dll'); final ScrollDC = user32.lookupFunction< Int32 Function( IntPtr hDC, Int32 dx, Int32 dy, Pointer<RECT> lprcScroll, Pointer<RECT> lprcClip, IntPtr hrgnUpdate, Pointer<RECT> lprcUpdate), int Function( int hDC, int dx, int dy, Pointer<RECT> lprcScroll, Pointer<RECT> lprcClip, int hrgnUpdate, Pointer<RECT> lprcUpdate)>('ScrollDC'); expect(ScrollDC, isA<Function>()); }); test('Can instantiate ScrollWindow', () { final user32 = DynamicLibrary.open('user32.dll'); final ScrollWindow = user32.lookupFunction< Int32 Function(IntPtr hWnd, Int32 XAmount, Int32 YAmount, Pointer<RECT> lpRect, Pointer<RECT> lpClipRect), int Function(int hWnd, int XAmount, int YAmount, Pointer<RECT> lpRect, Pointer<RECT> lpClipRect)>('ScrollWindow'); expect(ScrollWindow, isA<Function>()); }); test('Can instantiate ScrollWindowEx', () { final user32 = DynamicLibrary.open('user32.dll'); final ScrollWindowEx = user32.lookupFunction< Int32 Function( IntPtr hWnd, Int32 dx, Int32 dy, Pointer<RECT> prcScroll, Pointer<RECT> prcClip, IntPtr hrgnUpdate, Pointer<RECT> prcUpdate, Uint32 flags), int Function( int hWnd, int dx, int dy, Pointer<RECT> prcScroll, Pointer<RECT> prcClip, int hrgnUpdate, Pointer<RECT> prcUpdate, int flags)>('ScrollWindowEx'); expect(ScrollWindowEx, isA<Function>()); }); test('Can instantiate SendDlgItemMessage', () { final user32 = DynamicLibrary.open('user32.dll'); final SendDlgItemMessage = user32.lookupFunction< IntPtr Function(IntPtr hDlg, Int32 nIDDlgItem, Uint32 Msg, IntPtr wParam, IntPtr lParam), int Function(int hDlg, int nIDDlgItem, int Msg, int wParam, int lParam)>('SendDlgItemMessageW'); expect(SendDlgItemMessage, isA<Function>()); }); test('Can instantiate SendInput', () { final user32 = DynamicLibrary.open('user32.dll'); final SendInput = user32.lookupFunction< Uint32 Function(Uint32 cInputs, Pointer<INPUT> pInputs, Int32 cbSize), int Function( int cInputs, Pointer<INPUT> pInputs, int cbSize)>('SendInput'); expect(SendInput, isA<Function>()); }); test('Can instantiate SendMessage', () { final user32 = DynamicLibrary.open('user32.dll'); final SendMessage = user32.lookupFunction< IntPtr Function( IntPtr hWnd, Uint32 Msg, IntPtr wParam, IntPtr lParam), int Function( int hWnd, int Msg, int wParam, int lParam)>('SendMessageW'); expect(SendMessage, isA<Function>()); }); test('Can instantiate SendMessageCallback', () { final user32 = DynamicLibrary.open('user32.dll'); final SendMessageCallback = user32.lookupFunction< Int32 Function( IntPtr hWnd, Uint32 Msg, IntPtr wParam, IntPtr lParam, Pointer<NativeFunction<SendAsyncProc>> lpResultCallBack, IntPtr dwData), int Function( int hWnd, int Msg, int wParam, int lParam, Pointer<NativeFunction<SendAsyncProc>> lpResultCallBack, int dwData)>('SendMessageCallbackW'); expect(SendMessageCallback, isA<Function>()); }); test('Can instantiate SendMessageTimeout', () { final user32 = DynamicLibrary.open('user32.dll'); final SendMessageTimeout = user32.lookupFunction< IntPtr Function(IntPtr hWnd, Uint32 Msg, IntPtr wParam, IntPtr lParam, Uint32 fuFlags, Uint32 uTimeout, Pointer<IntPtr> lpdwResult), int Function(int hWnd, int Msg, int wParam, int lParam, int fuFlags, int uTimeout, Pointer<IntPtr> lpdwResult)>('SendMessageTimeoutW'); expect(SendMessageTimeout, isA<Function>()); }); test('Can instantiate SendNotifyMessage', () { final user32 = DynamicLibrary.open('user32.dll'); final SendNotifyMessage = user32.lookupFunction< Int32 Function(IntPtr hWnd, Uint32 Msg, IntPtr wParam, IntPtr lParam), int Function( int hWnd, int Msg, int wParam, int lParam)>('SendNotifyMessageW'); expect(SendNotifyMessage, isA<Function>()); }); test('Can instantiate SetActiveWindow', () { final user32 = DynamicLibrary.open('user32.dll'); final SetActiveWindow = user32.lookupFunction< IntPtr Function(IntPtr hWnd), int Function(int hWnd)>('SetActiveWindow'); expect(SetActiveWindow, isA<Function>()); }); test('Can instantiate SetCapture', () { final user32 = DynamicLibrary.open('user32.dll'); final SetCapture = user32.lookupFunction<IntPtr Function(IntPtr hWnd), int Function(int hWnd)>('SetCapture'); expect(SetCapture, isA<Function>()); }); test('Can instantiate SetCaretBlinkTime', () { final user32 = DynamicLibrary.open('user32.dll'); final SetCaretBlinkTime = user32.lookupFunction< Int32 Function(Uint32 uMSeconds), int Function(int uMSeconds)>('SetCaretBlinkTime'); expect(SetCaretBlinkTime, isA<Function>()); }); test('Can instantiate SetCaretPos', () { final user32 = DynamicLibrary.open('user32.dll'); final SetCaretPos = user32.lookupFunction< Int32 Function(Int32 X, Int32 Y), int Function(int X, int Y)>('SetCaretPos'); expect(SetCaretPos, isA<Function>()); }); test('Can instantiate SetClipboardData', () { final user32 = DynamicLibrary.open('user32.dll'); final SetClipboardData = user32.lookupFunction< IntPtr Function(Uint32 uFormat, IntPtr hMem), int Function(int uFormat, int hMem)>('SetClipboardData'); expect(SetClipboardData, isA<Function>()); }); test('Can instantiate SetClipboardViewer', () { final user32 = DynamicLibrary.open('user32.dll'); final SetClipboardViewer = user32.lookupFunction< IntPtr Function(IntPtr hWndNewViewer), int Function(int hWndNewViewer)>('SetClipboardViewer'); expect(SetClipboardViewer, isA<Function>()); }); if (windowsBuildNumber >= 9200) { test('Can instantiate SetCoalescableTimer', () { final user32 = DynamicLibrary.open('user32.dll'); final SetCoalescableTimer = user32.lookupFunction< IntPtr Function( IntPtr hWnd, IntPtr nIDEvent, Uint32 uElapse, Pointer<NativeFunction<TimerProc>> lpTimerFunc, Uint32 uToleranceDelay), int Function( int hWnd, int nIDEvent, int uElapse, Pointer<NativeFunction<TimerProc>> lpTimerFunc, int uToleranceDelay)>('SetCoalescableTimer'); expect(SetCoalescableTimer, isA<Function>()); }); } test('Can instantiate SetCursor', () { final user32 = DynamicLibrary.open('user32.dll'); final SetCursor = user32.lookupFunction<IntPtr Function(IntPtr hCursor), int Function(int hCursor)>('SetCursor'); expect(SetCursor, isA<Function>()); }); test('Can instantiate SetCursorPos', () { final user32 = DynamicLibrary.open('user32.dll'); final SetCursorPos = user32.lookupFunction< Int32 Function(Int32 X, Int32 Y), int Function(int X, int Y)>('SetCursorPos'); expect(SetCursorPos, isA<Function>()); }); if (windowsBuildNumber >= 15063) { test('Can instantiate SetDialogControlDpiChangeBehavior', () { final user32 = DynamicLibrary.open('user32.dll'); final SetDialogControlDpiChangeBehavior = user32.lookupFunction< Int32 Function(IntPtr hWnd, Uint32 mask, Uint32 values), int Function(int hWnd, int mask, int values)>('SetDialogControlDpiChangeBehavior'); expect(SetDialogControlDpiChangeBehavior, isA<Function>()); }); } if (windowsBuildNumber >= 15063) { test('Can instantiate SetDialogDpiChangeBehavior', () { final user32 = DynamicLibrary.open('user32.dll'); final SetDialogDpiChangeBehavior = user32.lookupFunction< Int32 Function(IntPtr hDlg, Uint32 mask, Uint32 values), int Function( int hDlg, int mask, int values)>('SetDialogDpiChangeBehavior'); expect(SetDialogDpiChangeBehavior, isA<Function>()); }); } if (windowsBuildNumber >= 9200) { test('Can instantiate SetDisplayAutoRotationPreferences', () { final user32 = DynamicLibrary.open('user32.dll'); final SetDisplayAutoRotationPreferences = user32.lookupFunction< Int32 Function(Int32 orientation), int Function(int orientation)>('SetDisplayAutoRotationPreferences'); expect(SetDisplayAutoRotationPreferences, isA<Function>()); }); } test('Can instantiate SetDlgItemInt', () { final user32 = DynamicLibrary.open('user32.dll'); final SetDlgItemInt = user32.lookupFunction< Int32 Function( IntPtr hDlg, Int32 nIDDlgItem, Uint32 uValue, Int32 bSigned), int Function(int hDlg, int nIDDlgItem, int uValue, int bSigned)>('SetDlgItemInt'); expect(SetDlgItemInt, isA<Function>()); }); test('Can instantiate SetDlgItemText', () { final user32 = DynamicLibrary.open('user32.dll'); final SetDlgItemText = user32.lookupFunction< Int32 Function( IntPtr hDlg, Int32 nIDDlgItem, Pointer<Utf16> lpString), int Function(int hDlg, int nIDDlgItem, Pointer<Utf16> lpString)>('SetDlgItemTextW'); expect(SetDlgItemText, isA<Function>()); }); test('Can instantiate SetDoubleClickTime', () { final user32 = DynamicLibrary.open('user32.dll'); final SetDoubleClickTime = user32.lookupFunction< Int32 Function(Uint32 param0), int Function(int param0)>('SetDoubleClickTime'); expect(SetDoubleClickTime, isA<Function>()); }); test('Can instantiate SetFocus', () { final user32 = DynamicLibrary.open('user32.dll'); final SetFocus = user32.lookupFunction<IntPtr Function(IntPtr hWnd), int Function(int hWnd)>('SetFocus'); expect(SetFocus, isA<Function>()); }); test('Can instantiate SetForegroundWindow', () { final user32 = DynamicLibrary.open('user32.dll'); final SetForegroundWindow = user32.lookupFunction< Int32 Function(IntPtr hWnd), int Function(int hWnd)>('SetForegroundWindow'); expect(SetForegroundWindow, isA<Function>()); }); test('Can instantiate SetGestureConfig', () { final user32 = DynamicLibrary.open('user32.dll'); final SetGestureConfig = user32.lookupFunction< Int32 Function(IntPtr hwnd, Uint32 dwReserved, Uint32 cIDs, Pointer<GESTURECONFIG> pGestureConfig, Uint32 cbSize), int Function( int hwnd, int dwReserved, int cIDs, Pointer<GESTURECONFIG> pGestureConfig, int cbSize)>('SetGestureConfig'); expect(SetGestureConfig, isA<Function>()); }); test('Can instantiate SetKeyboardState', () { final user32 = DynamicLibrary.open('user32.dll'); final SetKeyboardState = user32.lookupFunction< Int32 Function(Pointer<Uint8> lpKeyState), int Function(Pointer<Uint8> lpKeyState)>('SetKeyboardState'); expect(SetKeyboardState, isA<Function>()); }); test('Can instantiate SetLayeredWindowAttributes', () { final user32 = DynamicLibrary.open('user32.dll'); final SetLayeredWindowAttributes = user32.lookupFunction< Int32 Function( IntPtr hwnd, Uint32 crKey, Uint8 bAlpha, Uint32 dwFlags), int Function(int hwnd, int crKey, int bAlpha, int dwFlags)>('SetLayeredWindowAttributes'); expect(SetLayeredWindowAttributes, isA<Function>()); }); test('Can instantiate SetMenuInfo', () { final user32 = DynamicLibrary.open('user32.dll'); final SetMenuInfo = user32.lookupFunction< Int32 Function(IntPtr param0, Pointer<MENUINFO> param1), int Function(int param0, Pointer<MENUINFO> param1)>('SetMenuInfo'); expect(SetMenuInfo, isA<Function>()); }); test('Can instantiate SetMenuItemBitmaps', () { final user32 = DynamicLibrary.open('user32.dll'); final SetMenuItemBitmaps = user32.lookupFunction< Int32 Function(IntPtr hMenu, Uint32 uPosition, Uint32 uFlags, IntPtr hBitmapUnchecked, IntPtr hBitmapChecked), int Function(int hMenu, int uPosition, int uFlags, int hBitmapUnchecked, int hBitmapChecked)>('SetMenuItemBitmaps'); expect(SetMenuItemBitmaps, isA<Function>()); }); test('Can instantiate SetMenuItemInfo', () { final user32 = DynamicLibrary.open('user32.dll'); final SetMenuItemInfo = user32.lookupFunction< Int32 Function(IntPtr hmenu, Uint32 item, Int32 fByPositon, Pointer<MENUITEMINFO> lpmii), int Function(int hmenu, int item, int fByPositon, Pointer<MENUITEMINFO> lpmii)>('SetMenuItemInfoW'); expect(SetMenuItemInfo, isA<Function>()); }); test('Can instantiate SetMessageExtraInfo', () { final user32 = DynamicLibrary.open('user32.dll'); final SetMessageExtraInfo = user32.lookupFunction< IntPtr Function(IntPtr lParam), int Function(int lParam)>('SetMessageExtraInfo'); expect(SetMessageExtraInfo, isA<Function>()); }); test('Can instantiate SetParent', () { final user32 = DynamicLibrary.open('user32.dll'); final SetParent = user32.lookupFunction< IntPtr Function(IntPtr hWndChild, IntPtr hWndNewParent), int Function(int hWndChild, int hWndNewParent)>('SetParent'); expect(SetParent, isA<Function>()); }); test('Can instantiate SetProcessDPIAware', () { final user32 = DynamicLibrary.open('user32.dll'); final SetProcessDPIAware = user32.lookupFunction<Int32 Function(), int Function()>( 'SetProcessDPIAware'); expect(SetProcessDPIAware, isA<Function>()); }); if (windowsBuildNumber >= 15063) { test('Can instantiate SetProcessDpiAwarenessContext', () { final user32 = DynamicLibrary.open('user32.dll'); final SetProcessDpiAwarenessContext = user32.lookupFunction< Int32 Function(IntPtr value), int Function(int value)>('SetProcessDpiAwarenessContext'); expect(SetProcessDpiAwarenessContext, isA<Function>()); }); } if (windowsBuildNumber >= 14393) { test('Can instantiate SetProp', () { final user32 = DynamicLibrary.open('user32.dll'); final SetProp = user32.lookupFunction< Int32 Function(IntPtr hWnd, Pointer<Utf16> lpString, IntPtr hData), int Function( int hWnd, Pointer<Utf16> lpString, int hData)>('SetPropW'); expect(SetProp, isA<Function>()); }); } test('Can instantiate SetRect', () { final user32 = DynamicLibrary.open('user32.dll'); final SetRect = user32.lookupFunction< Int32 Function(Pointer<RECT> lprc, Int32 xLeft, Int32 yTop, Int32 xRight, Int32 yBottom), int Function(Pointer<RECT> lprc, int xLeft, int yTop, int xRight, int yBottom)>('SetRect'); expect(SetRect, isA<Function>()); }); test('Can instantiate SetRectEmpty', () { final user32 = DynamicLibrary.open('user32.dll'); final SetRectEmpty = user32.lookupFunction< Int32 Function(Pointer<RECT> lprc), int Function(Pointer<RECT> lprc)>('SetRectEmpty'); expect(SetRectEmpty, isA<Function>()); }); test('Can instantiate SetScrollInfo', () { final user32 = DynamicLibrary.open('user32.dll'); final SetScrollInfo = user32.lookupFunction< Int32 Function( IntPtr hwnd, Uint32 nBar, Pointer<SCROLLINFO> lpsi, Int32 redraw), int Function(int hwnd, int nBar, Pointer<SCROLLINFO> lpsi, int redraw)>('SetScrollInfo'); expect(SetScrollInfo, isA<Function>()); }); test('Can instantiate SetSysColors', () { final user32 = DynamicLibrary.open('user32.dll'); final SetSysColors = user32.lookupFunction< Int32 Function(Int32 cElements, Pointer<Int32> lpaElements, Pointer<Uint32> lpaRgbValues), int Function(int cElements, Pointer<Int32> lpaElements, Pointer<Uint32> lpaRgbValues)>('SetSysColors'); expect(SetSysColors, isA<Function>()); }); test('Can instantiate SetSystemCursor', () { final user32 = DynamicLibrary.open('user32.dll'); final SetSystemCursor = user32.lookupFunction< Int32 Function(IntPtr hcur, Uint32 id), int Function(int hcur, int id)>('SetSystemCursor'); expect(SetSystemCursor, isA<Function>()); }); if (windowsBuildNumber >= 14393) { test('Can instantiate SetThreadDpiAwarenessContext', () { final user32 = DynamicLibrary.open('user32.dll'); final SetThreadDpiAwarenessContext = user32.lookupFunction< IntPtr Function(IntPtr dpiContext), int Function(int dpiContext)>('SetThreadDpiAwarenessContext'); expect(SetThreadDpiAwarenessContext, isA<Function>()); }); } if (windowsBuildNumber >= 17134) { test('Can instantiate SetThreadDpiHostingBehavior', () { final user32 = DynamicLibrary.open('user32.dll'); final SetThreadDpiHostingBehavior = user32.lookupFunction< Int32 Function(Int32 value), int Function(int value)>('SetThreadDpiHostingBehavior'); expect(SetThreadDpiHostingBehavior, isA<Function>()); }); } test('Can instantiate SetTimer', () { final user32 = DynamicLibrary.open('user32.dll'); final SetTimer = user32.lookupFunction< IntPtr Function(IntPtr hWnd, IntPtr nIDEvent, Uint32 uElapse, Pointer<NativeFunction<TimerProc>> lpTimerFunc), int Function(int hWnd, int nIDEvent, int uElapse, Pointer<NativeFunction<TimerProc>> lpTimerFunc)>('SetTimer'); expect(SetTimer, isA<Function>()); }); test('Can instantiate SetUserObjectInformation', () { final user32 = DynamicLibrary.open('user32.dll'); final SetUserObjectInformation = user32.lookupFunction< Int32 Function( IntPtr hObj, Int32 nIndex, Pointer pvInfo, Uint32 nLength), int Function(int hObj, int nIndex, Pointer pvInfo, int nLength)>('SetUserObjectInformationW'); expect(SetUserObjectInformation, isA<Function>()); }); test('Can instantiate SetWindowDisplayAffinity', () { final user32 = DynamicLibrary.open('user32.dll'); final SetWindowDisplayAffinity = user32.lookupFunction< Int32 Function(IntPtr hWnd, Uint32 dwAffinity), int Function(int hWnd, int dwAffinity)>('SetWindowDisplayAffinity'); expect(SetWindowDisplayAffinity, isA<Function>()); }); test('Can instantiate SetWindowLongPtr', () { final user32 = DynamicLibrary.open('user32.dll'); final SetWindowLongPtr = user32.lookupFunction< IntPtr Function(IntPtr hWnd, Int32 nIndex, IntPtr dwNewLong), int Function( int hWnd, int nIndex, int dwNewLong)>('SetWindowLongPtrW'); expect(SetWindowLongPtr, isA<Function>()); }); test('Can instantiate SetWindowPlacement', () { final user32 = DynamicLibrary.open('user32.dll'); final SetWindowPlacement = user32.lookupFunction< Int32 Function(IntPtr hWnd, Pointer<WINDOWPLACEMENT> lpwndpl), int Function(int hWnd, Pointer<WINDOWPLACEMENT> lpwndpl)>('SetWindowPlacement'); expect(SetWindowPlacement, isA<Function>()); }); test('Can instantiate SetWindowPos', () { final user32 = DynamicLibrary.open('user32.dll'); final SetWindowPos = user32.lookupFunction< Int32 Function(IntPtr hWnd, IntPtr hWndInsertAfter, Int32 X, Int32 Y, Int32 cx, Int32 cy, Uint32 uFlags), int Function(int hWnd, int hWndInsertAfter, int X, int Y, int cx, int cy, int uFlags)>('SetWindowPos'); expect(SetWindowPos, isA<Function>()); }); test('Can instantiate SetWindowRgn', () { final user32 = DynamicLibrary.open('user32.dll'); final SetWindowRgn = user32.lookupFunction< Int32 Function(IntPtr hWnd, IntPtr hRgn, Int32 bRedraw), int Function(int hWnd, int hRgn, int bRedraw)>('SetWindowRgn'); expect(SetWindowRgn, isA<Function>()); }); test('Can instantiate SetWindowsHookEx', () { final user32 = DynamicLibrary.open('user32.dll'); final SetWindowsHookEx = user32.lookupFunction< IntPtr Function( Int32 idHook, Pointer<NativeFunction<CallWndProc>> lpfn, IntPtr hmod, Uint32 dwThreadId), int Function(int idHook, Pointer<NativeFunction<CallWndProc>> lpfn, int hmod, int dwThreadId)>('SetWindowsHookExW'); expect(SetWindowsHookEx, isA<Function>()); }); test('Can instantiate SetWindowText', () { final user32 = DynamicLibrary.open('user32.dll'); final SetWindowText = user32.lookupFunction< Int32 Function(IntPtr hWnd, Pointer<Utf16> lpString), int Function(int hWnd, Pointer<Utf16> lpString)>('SetWindowTextW'); expect(SetWindowText, isA<Function>()); }); test('Can instantiate ShowCaret', () { final user32 = DynamicLibrary.open('user32.dll'); final ShowCaret = user32.lookupFunction<Int32 Function(IntPtr hWnd), int Function(int hWnd)>('ShowCaret'); expect(ShowCaret, isA<Function>()); }); test('Can instantiate ShowCursor', () { final user32 = DynamicLibrary.open('user32.dll'); final ShowCursor = user32.lookupFunction<Int32 Function(Int32 bShow), int Function(int bShow)>('ShowCursor'); expect(ShowCursor, isA<Function>()); }); test('Can instantiate ShowOwnedPopups', () { final user32 = DynamicLibrary.open('user32.dll'); final ShowOwnedPopups = user32.lookupFunction< Int32 Function(IntPtr hWnd, Int32 fShow), int Function(int hWnd, int fShow)>('ShowOwnedPopups'); expect(ShowOwnedPopups, isA<Function>()); }); test('Can instantiate ShowWindow', () { final user32 = DynamicLibrary.open('user32.dll'); final ShowWindow = user32.lookupFunction< Int32 Function(IntPtr hWnd, Uint32 nCmdShow), int Function(int hWnd, int nCmdShow)>('ShowWindow'); expect(ShowWindow, isA<Function>()); }); test('Can instantiate ShowWindowAsync', () { final user32 = DynamicLibrary.open('user32.dll'); final ShowWindowAsync = user32.lookupFunction< Int32 Function(IntPtr hWnd, Uint32 nCmdShow), int Function(int hWnd, int nCmdShow)>('ShowWindowAsync'); expect(ShowWindowAsync, isA<Function>()); }); test('Can instantiate SoundSentry', () { final user32 = DynamicLibrary.open('user32.dll'); final SoundSentry = user32 .lookupFunction<Int32 Function(), int Function()>('SoundSentry'); expect(SoundSentry, isA<Function>()); }); test('Can instantiate SubtractRect', () { final user32 = DynamicLibrary.open('user32.dll'); final SubtractRect = user32.lookupFunction< Int32 Function(Pointer<RECT> lprcDst, Pointer<RECT> lprcSrc1, Pointer<RECT> lprcSrc2), int Function(Pointer<RECT> lprcDst, Pointer<RECT> lprcSrc1, Pointer<RECT> lprcSrc2)>('SubtractRect'); expect(SubtractRect, isA<Function>()); }); test('Can instantiate SwapMouseButton', () { final user32 = DynamicLibrary.open('user32.dll'); final SwapMouseButton = user32.lookupFunction<Int32 Function(Int32 fSwap), int Function(int fSwap)>('SwapMouseButton'); expect(SwapMouseButton, isA<Function>()); }); test('Can instantiate SwitchDesktop', () { final user32 = DynamicLibrary.open('user32.dll'); final SwitchDesktop = user32.lookupFunction< Int32 Function(IntPtr hDesktop), int Function(int hDesktop)>('SwitchDesktop'); expect(SwitchDesktop, isA<Function>()); }); test('Can instantiate SwitchToThisWindow', () { final user32 = DynamicLibrary.open('user32.dll'); final SwitchToThisWindow = user32.lookupFunction< Void Function(IntPtr hwnd, Int32 fUnknown), void Function(int hwnd, int fUnknown)>('SwitchToThisWindow'); expect(SwitchToThisWindow, isA<Function>()); }); test('Can instantiate SystemParametersInfo', () { final user32 = DynamicLibrary.open('user32.dll'); final SystemParametersInfo = user32.lookupFunction< Int32 Function( Uint32 uiAction, Uint32 uiParam, Pointer pvParam, Uint32 fWinIni), int Function(int uiAction, int uiParam, Pointer pvParam, int fWinIni)>('SystemParametersInfoW'); expect(SystemParametersInfo, isA<Function>()); }); if (windowsBuildNumber >= 14393) { test('Can instantiate SystemParametersInfoForDpi', () { final user32 = DynamicLibrary.open('user32.dll'); final SystemParametersInfoForDpi = user32.lookupFunction< Int32 Function(Uint32 uiAction, Uint32 uiParam, Pointer pvParam, Uint32 fWinIni, Uint32 dpi), int Function(int uiAction, int uiParam, Pointer pvParam, int fWinIni, int dpi)>('SystemParametersInfoForDpi'); expect(SystemParametersInfoForDpi, isA<Function>()); }); } test('Can instantiate TabbedTextOut', () { final user32 = DynamicLibrary.open('user32.dll'); final TabbedTextOut = user32.lookupFunction< Int32 Function( IntPtr hdc, Int32 x, Int32 y, Pointer<Utf16> lpString, Int32 chCount, Int32 nTabPositions, Pointer<Int32> lpnTabStopPositions, Int32 nTabOrigin), int Function( int hdc, int x, int y, Pointer<Utf16> lpString, int chCount, int nTabPositions, Pointer<Int32> lpnTabStopPositions, int nTabOrigin)>('TabbedTextOutW'); expect(TabbedTextOut, isA<Function>()); }); test('Can instantiate TileWindows', () { final user32 = DynamicLibrary.open('user32.dll'); final TileWindows = user32.lookupFunction< Uint16 Function(IntPtr hwndParent, Uint32 wHow, Pointer<RECT> lpRect, Uint32 cKids, Pointer<IntPtr> lpKids), int Function(int hwndParent, int wHow, Pointer<RECT> lpRect, int cKids, Pointer<IntPtr> lpKids)>('TileWindows'); expect(TileWindows, isA<Function>()); }); test('Can instantiate ToAscii', () { final user32 = DynamicLibrary.open('user32.dll'); final ToAscii = user32.lookupFunction< Int32 Function(Uint32 uVirtKey, Uint32 uScanCode, Pointer<Uint8> lpKeyState, Pointer<Uint16> lpChar, Uint32 uFlags), int Function(int uVirtKey, int uScanCode, Pointer<Uint8> lpKeyState, Pointer<Uint16> lpChar, int uFlags)>('ToAscii'); expect(ToAscii, isA<Function>()); }); test('Can instantiate ToAsciiEx', () { final user32 = DynamicLibrary.open('user32.dll'); final ToAsciiEx = user32.lookupFunction< Int32 Function( Uint32 uVirtKey, Uint32 uScanCode, Pointer<Uint8> lpKeyState, Pointer<Uint16> lpChar, Uint32 uFlags, IntPtr dwhkl), int Function(int uVirtKey, int uScanCode, Pointer<Uint8> lpKeyState, Pointer<Uint16> lpChar, int uFlags, int dwhkl)>('ToAsciiEx'); expect(ToAsciiEx, isA<Function>()); }); test('Can instantiate ToUnicode', () { final user32 = DynamicLibrary.open('user32.dll'); final ToUnicode = user32.lookupFunction< Int32 Function( Uint32 wVirtKey, Uint32 wScanCode, Pointer<Uint8> lpKeyState, Pointer<Utf16> pwszBuff, Int32 cchBuff, Uint32 wFlags), int Function(int wVirtKey, int wScanCode, Pointer<Uint8> lpKeyState, Pointer<Utf16> pwszBuff, int cchBuff, int wFlags)>('ToUnicode'); expect(ToUnicode, isA<Function>()); }); test('Can instantiate ToUnicodeEx', () { final user32 = DynamicLibrary.open('user32.dll'); final ToUnicodeEx = user32.lookupFunction< Int32 Function( Uint32 wVirtKey, Uint32 wScanCode, Pointer<Uint8> lpKeyState, Pointer<Utf16> pwszBuff, Int32 cchBuff, Uint32 wFlags, IntPtr dwhkl), int Function( int wVirtKey, int wScanCode, Pointer<Uint8> lpKeyState, Pointer<Utf16> pwszBuff, int cchBuff, int wFlags, int dwhkl)>('ToUnicodeEx'); expect(ToUnicodeEx, isA<Function>()); }); test('Can instantiate TrackPopupMenuEx', () { final user32 = DynamicLibrary.open('user32.dll'); final TrackPopupMenuEx = user32.lookupFunction< Int32 Function(IntPtr hMenu, Uint32 uFlags, Int32 x, Int32 y, IntPtr hwnd, Pointer<TPMPARAMS> lptpm), int Function(int hMenu, int uFlags, int x, int y, int hwnd, Pointer<TPMPARAMS> lptpm)>('TrackPopupMenuEx'); expect(TrackPopupMenuEx, isA<Function>()); }); test('Can instantiate TranslateAccelerator', () { final user32 = DynamicLibrary.open('user32.dll'); final TranslateAccelerator = user32.lookupFunction< Int32 Function(IntPtr hWnd, IntPtr hAccTable, Pointer<MSG> lpMsg), int Function(int hWnd, int hAccTable, Pointer<MSG> lpMsg)>('TranslateAcceleratorW'); expect(TranslateAccelerator, isA<Function>()); }); test('Can instantiate TranslateMDISysAccel', () { final user32 = DynamicLibrary.open('user32.dll'); final TranslateMDISysAccel = user32.lookupFunction< Int32 Function(IntPtr hWndClient, Pointer<MSG> lpMsg), int Function( int hWndClient, Pointer<MSG> lpMsg)>('TranslateMDISysAccel'); expect(TranslateMDISysAccel, isA<Function>()); }); test('Can instantiate TranslateMessage', () { final user32 = DynamicLibrary.open('user32.dll'); final TranslateMessage = user32.lookupFunction< Int32 Function(Pointer<MSG> lpMsg), int Function(Pointer<MSG> lpMsg)>('TranslateMessage'); expect(TranslateMessage, isA<Function>()); }); test('Can instantiate UnhookWindowsHookEx', () { final user32 = DynamicLibrary.open('user32.dll'); final UnhookWindowsHookEx = user32.lookupFunction< Int32 Function(IntPtr hhk), int Function(int hhk)>('UnhookWindowsHookEx'); expect(UnhookWindowsHookEx, isA<Function>()); }); test('Can instantiate UnionRect', () { final user32 = DynamicLibrary.open('user32.dll'); final UnionRect = user32.lookupFunction< Int32 Function(Pointer<RECT> lprcDst, Pointer<RECT> lprcSrc1, Pointer<RECT> lprcSrc2), int Function(Pointer<RECT> lprcDst, Pointer<RECT> lprcSrc1, Pointer<RECT> lprcSrc2)>('UnionRect'); expect(UnionRect, isA<Function>()); }); test('Can instantiate UnloadKeyboardLayout', () { final user32 = DynamicLibrary.open('user32.dll'); final UnloadKeyboardLayout = user32.lookupFunction< Int32 Function(IntPtr hkl), int Function(int hkl)>('UnloadKeyboardLayout'); expect(UnloadKeyboardLayout, isA<Function>()); }); test('Can instantiate UnregisterClass', () { final user32 = DynamicLibrary.open('user32.dll'); final UnregisterClass = user32.lookupFunction< Int32 Function(Pointer<Utf16> lpClassName, IntPtr hInstance), int Function( Pointer<Utf16> lpClassName, int hInstance)>('UnregisterClassW'); expect(UnregisterClass, isA<Function>()); }); test('Can instantiate UnregisterHotKey', () { final user32 = DynamicLibrary.open('user32.dll'); final UnregisterHotKey = user32.lookupFunction< Int32 Function(IntPtr hWnd, Int32 id), int Function(int hWnd, int id)>('UnregisterHotKey'); expect(UnregisterHotKey, isA<Function>()); }); test('Can instantiate UnregisterPowerSettingNotification', () { final user32 = DynamicLibrary.open('user32.dll'); final UnregisterPowerSettingNotification = user32.lookupFunction< Int32 Function(IntPtr Handle_), int Function(int Handle_)>('UnregisterPowerSettingNotification'); expect(UnregisterPowerSettingNotification, isA<Function>()); }); test('Can instantiate UnregisterTouchWindow', () { final user32 = DynamicLibrary.open('user32.dll'); final UnregisterTouchWindow = user32.lookupFunction< Int32 Function(IntPtr hwnd), int Function(int hwnd)>('UnregisterTouchWindow'); expect(UnregisterTouchWindow, isA<Function>()); }); test('Can instantiate UpdateLayeredWindowIndirect', () { final user32 = DynamicLibrary.open('user32.dll'); final UpdateLayeredWindowIndirect = user32.lookupFunction< Int32 Function( IntPtr hWnd, Pointer<UPDATELAYEREDWINDOWINFO> pULWInfo), int Function( int hWnd, Pointer<UPDATELAYEREDWINDOWINFO> pULWInfo)>( 'UpdateLayeredWindowIndirect'); expect(UpdateLayeredWindowIndirect, isA<Function>()); }); test('Can instantiate UpdateWindow', () { final user32 = DynamicLibrary.open('user32.dll'); final UpdateWindow = user32.lookupFunction<Int32 Function(IntPtr hWnd), int Function(int hWnd)>('UpdateWindow'); expect(UpdateWindow, isA<Function>()); }); test('Can instantiate ValidateRect', () { final user32 = DynamicLibrary.open('user32.dll'); final ValidateRect = user32.lookupFunction< Int32 Function(IntPtr hWnd, Pointer<RECT> lpRect), int Function(int hWnd, Pointer<RECT> lpRect)>('ValidateRect'); expect(ValidateRect, isA<Function>()); }); test('Can instantiate ValidateRgn', () { final user32 = DynamicLibrary.open('user32.dll'); final ValidateRgn = user32.lookupFunction< Int32 Function(IntPtr hWnd, IntPtr hRgn), int Function(int hWnd, int hRgn)>('ValidateRgn'); expect(ValidateRgn, isA<Function>()); }); test('Can instantiate VkKeyScan', () { final user32 = DynamicLibrary.open('user32.dll'); final VkKeyScan = user32.lookupFunction<Int16 Function(Uint16 ch), int Function(int ch)>('VkKeyScanW'); expect(VkKeyScan, isA<Function>()); }); test('Can instantiate VkKeyScanEx', () { final user32 = DynamicLibrary.open('user32.dll'); final VkKeyScanEx = user32.lookupFunction< Int16 Function(Uint16 ch, IntPtr dwhkl), int Function(int ch, int dwhkl)>('VkKeyScanExW'); expect(VkKeyScanEx, isA<Function>()); }); test('Can instantiate WaitForInputIdle', () { final user32 = DynamicLibrary.open('user32.dll'); final WaitForInputIdle = user32.lookupFunction< Uint32 Function(IntPtr hProcess, Uint32 dwMilliseconds), int Function(int hProcess, int dwMilliseconds)>('WaitForInputIdle'); expect(WaitForInputIdle, isA<Function>()); }); test('Can instantiate WaitMessage', () { final user32 = DynamicLibrary.open('user32.dll'); final WaitMessage = user32 .lookupFunction<Int32 Function(), int Function()>('WaitMessage'); expect(WaitMessage, isA<Function>()); }); test('Can instantiate WindowFromDC', () { final user32 = DynamicLibrary.open('user32.dll'); final WindowFromDC = user32.lookupFunction<IntPtr Function(IntPtr hDC), int Function(int hDC)>('WindowFromDC'); expect(WindowFromDC, isA<Function>()); }); test('Can instantiate WindowFromPhysicalPoint', () { final user32 = DynamicLibrary.open('user32.dll'); final WindowFromPhysicalPoint = user32.lookupFunction< IntPtr Function(POINT Point), int Function(POINT Point)>('WindowFromPhysicalPoint'); expect(WindowFromPhysicalPoint, isA<Function>()); }); test('Can instantiate WindowFromPoint', () { final user32 = DynamicLibrary.open('user32.dll'); final WindowFromPoint = user32.lookupFunction< IntPtr Function(POINT Point), int Function(POINT Point)>('WindowFromPoint'); expect(WindowFromPoint, isA<Function>()); }); }); group('Test winspool functions', () { test('Can instantiate CloseSpoolFileHandle', () { final winspool = DynamicLibrary.open('winspool.drv'); final CloseSpoolFileHandle = winspool.lookupFunction< Int32 Function(IntPtr hPrinter, IntPtr hSpoolFile), int Function(int hPrinter, int hSpoolFile)>('CloseSpoolFileHandle'); expect(CloseSpoolFileHandle, isA<Function>()); }); test('Can instantiate CommitSpoolData', () { final winspool = DynamicLibrary.open('winspool.drv'); final CommitSpoolData = winspool.lookupFunction< IntPtr Function(IntPtr hPrinter, IntPtr hSpoolFile, Uint32 cbCommit), int Function( int hPrinter, int hSpoolFile, int cbCommit)>('CommitSpoolData'); expect(CommitSpoolData, isA<Function>()); }); test('Can instantiate ConfigurePort', () { final winspool = DynamicLibrary.open('winspool.drv'); final ConfigurePort = winspool.lookupFunction< Int32 Function( Pointer<Utf16> pName, IntPtr hWnd, Pointer<Utf16> pPortName), int Function(Pointer<Utf16> pName, int hWnd, Pointer<Utf16> pPortName)>('ConfigurePortW'); expect(ConfigurePort, isA<Function>()); }); test('Can instantiate ConnectToPrinterDlg', () { final winspool = DynamicLibrary.open('winspool.drv'); final ConnectToPrinterDlg = winspool.lookupFunction< IntPtr Function(IntPtr hwnd, Uint32 Flags), int Function(int hwnd, int Flags)>('ConnectToPrinterDlg'); expect(ConnectToPrinterDlg, isA<Function>()); }); test('Can instantiate DeleteForm', () { final winspool = DynamicLibrary.open('winspool.drv'); final DeleteForm = winspool.lookupFunction< Int32 Function(IntPtr hPrinter, Pointer<Utf16> pFormName), int Function(int hPrinter, Pointer<Utf16> pFormName)>('DeleteFormW'); expect(DeleteForm, isA<Function>()); }); test('Can instantiate DeletePrinterConnection', () { final winspool = DynamicLibrary.open('winspool.drv'); final DeletePrinterConnection = winspool.lookupFunction< Int32 Function(Pointer<Utf16> pName), int Function(Pointer<Utf16> pName)>('DeletePrinterConnectionW'); expect(DeletePrinterConnection, isA<Function>()); }); test('Can instantiate DeletePrinterData', () { final winspool = DynamicLibrary.open('winspool.drv'); final DeletePrinterData = winspool.lookupFunction< Uint32 Function(IntPtr hPrinter, Pointer<Utf16> pValueName), int Function( int hPrinter, Pointer<Utf16> pValueName)>('DeletePrinterDataW'); expect(DeletePrinterData, isA<Function>()); }); test('Can instantiate DeletePrinterDataEx', () { final winspool = DynamicLibrary.open('winspool.drv'); final DeletePrinterDataEx = winspool.lookupFunction< Uint32 Function(IntPtr hPrinter, Pointer<Utf16> pKeyName, Pointer<Utf16> pValueName), int Function(int hPrinter, Pointer<Utf16> pKeyName, Pointer<Utf16> pValueName)>('DeletePrinterDataExW'); expect(DeletePrinterDataEx, isA<Function>()); }); test('Can instantiate DeletePrinterKey', () { final winspool = DynamicLibrary.open('winspool.drv'); final DeletePrinterKey = winspool.lookupFunction< Uint32 Function(IntPtr hPrinter, Pointer<Utf16> pKeyName), int Function( int hPrinter, Pointer<Utf16> pKeyName)>('DeletePrinterKeyW'); expect(DeletePrinterKey, isA<Function>()); }); test('Can instantiate DocumentProperties', () { final winspool = DynamicLibrary.open('winspool.drv'); final DocumentProperties = winspool.lookupFunction< Int32 Function( IntPtr hWnd, IntPtr hPrinter, Pointer<Utf16> pDeviceName, Pointer<DEVMODE> pDevModeOutput, Pointer<DEVMODE> pDevModeInput, Uint32 fMode), int Function( int hWnd, int hPrinter, Pointer<Utf16> pDeviceName, Pointer<DEVMODE> pDevModeOutput, Pointer<DEVMODE> pDevModeInput, int fMode)>('DocumentPropertiesW'); expect(DocumentProperties, isA<Function>()); }); test('Can instantiate EnumForms', () { final winspool = DynamicLibrary.open('winspool.drv'); final EnumForms = winspool.lookupFunction< Int32 Function( IntPtr hPrinter, Uint32 Level, Pointer<Uint8> pForm, Uint32 cbBuf, Pointer<Uint32> pcbNeeded, Pointer<Uint32> pcReturned), int Function( int hPrinter, int Level, Pointer<Uint8> pForm, int cbBuf, Pointer<Uint32> pcbNeeded, Pointer<Uint32> pcReturned)>('EnumFormsW'); expect(EnumForms, isA<Function>()); }); test('Can instantiate EnumJobs', () { final winspool = DynamicLibrary.open('winspool.drv'); final EnumJobs = winspool.lookupFunction< Int32 Function( IntPtr hPrinter, Uint32 FirstJob, Uint32 NoJobs, Uint32 Level, Pointer<Uint8> pJob, Uint32 cbBuf, Pointer<Uint32> pcbNeeded, Pointer<Uint32> pcReturned), int Function( int hPrinter, int FirstJob, int NoJobs, int Level, Pointer<Uint8> pJob, int cbBuf, Pointer<Uint32> pcbNeeded, Pointer<Uint32> pcReturned)>('EnumJobsW'); expect(EnumJobs, isA<Function>()); }); test('Can instantiate EnumPrinterData', () { final winspool = DynamicLibrary.open('winspool.drv'); final EnumPrinterData = winspool.lookupFunction< Uint32 Function( IntPtr hPrinter, Uint32 dwIndex, Pointer<Utf16> pValueName, Uint32 cbValueName, Pointer<Uint32> pcbValueName, Pointer<Uint32> pType, Pointer<Uint8> pData, Uint32 cbData, Pointer<Uint32> pcbData), int Function( int hPrinter, int dwIndex, Pointer<Utf16> pValueName, int cbValueName, Pointer<Uint32> pcbValueName, Pointer<Uint32> pType, Pointer<Uint8> pData, int cbData, Pointer<Uint32> pcbData)>('EnumPrinterDataW'); expect(EnumPrinterData, isA<Function>()); }); test('Can instantiate EnumPrinterDataEx', () { final winspool = DynamicLibrary.open('winspool.drv'); final EnumPrinterDataEx = winspool.lookupFunction< Uint32 Function( IntPtr hPrinter, Pointer<Utf16> pKeyName, Pointer<Uint8> pEnumValues, Uint32 cbEnumValues, Pointer<Uint32> pcbEnumValues, Pointer<Uint32> pnEnumValues), int Function( int hPrinter, Pointer<Utf16> pKeyName, Pointer<Uint8> pEnumValues, int cbEnumValues, Pointer<Uint32> pcbEnumValues, Pointer<Uint32> pnEnumValues)>('EnumPrinterDataExW'); expect(EnumPrinterDataEx, isA<Function>()); }); test('Can instantiate EnumPrinterKey', () { final winspool = DynamicLibrary.open('winspool.drv'); final EnumPrinterKey = winspool.lookupFunction< Uint32 Function( IntPtr hPrinter, Pointer<Utf16> pKeyName, Pointer<Utf16> pSubkey, Uint32 cbSubkey, Pointer<Uint32> pcbSubkey), int Function( int hPrinter, Pointer<Utf16> pKeyName, Pointer<Utf16> pSubkey, int cbSubkey, Pointer<Uint32> pcbSubkey)>('EnumPrinterKeyW'); expect(EnumPrinterKey, isA<Function>()); }); test('Can instantiate EnumPrinters', () { final winspool = DynamicLibrary.open('winspool.drv'); final EnumPrinters = winspool.lookupFunction< Int32 Function( Uint32 Flags, Pointer<Utf16> Name, Uint32 Level, Pointer<Uint8> pPrinterEnum, Uint32 cbBuf, Pointer<Uint32> pcbNeeded, Pointer<Uint32> pcReturned), int Function( int Flags, Pointer<Utf16> Name, int Level, Pointer<Uint8> pPrinterEnum, int cbBuf, Pointer<Uint32> pcbNeeded, Pointer<Uint32> pcReturned)>('EnumPrintersW'); expect(EnumPrinters, isA<Function>()); }); test('Can instantiate FindFirstPrinterChangeNotification', () { final winspool = DynamicLibrary.open('winspool.drv'); final FindFirstPrinterChangeNotification = winspool.lookupFunction< IntPtr Function(IntPtr hPrinter, Uint32 fdwFilter, Uint32 fdwOptions, Pointer pPrinterNotifyOptions), int Function( int hPrinter, int fdwFilter, int fdwOptions, Pointer pPrinterNotifyOptions)>('FindFirstPrinterChangeNotification'); expect(FindFirstPrinterChangeNotification, isA<Function>()); }); test('Can instantiate FindNextPrinterChangeNotification', () { final winspool = DynamicLibrary.open('winspool.drv'); final FindNextPrinterChangeNotification = winspool.lookupFunction< Int32 Function(IntPtr hChange, Pointer<Uint32> pdwChange, Pointer pvReserved, Pointer<Pointer> ppPrinterNotifyInfo), int Function(int hChange, Pointer<Uint32> pdwChange, Pointer pvReserved, Pointer<Pointer> ppPrinterNotifyInfo)>( 'FindNextPrinterChangeNotification'); expect(FindNextPrinterChangeNotification, isA<Function>()); }); test('Can instantiate FlushPrinter', () { final winspool = DynamicLibrary.open('winspool.drv'); final FlushPrinter = winspool.lookupFunction< Int32 Function(IntPtr hPrinter, Pointer pBuf, Uint32 cbBuf, Pointer<Uint32> pcWritten, Uint32 cSleep), int Function(int hPrinter, Pointer pBuf, int cbBuf, Pointer<Uint32> pcWritten, int cSleep)>('FlushPrinter'); expect(FlushPrinter, isA<Function>()); }); test('Can instantiate FreePrinterNotifyInfo', () { final winspool = DynamicLibrary.open('winspool.drv'); final FreePrinterNotifyInfo = winspool.lookupFunction< Int32 Function(Pointer<PRINTER_NOTIFY_INFO> pPrinterNotifyInfo), int Function(Pointer<PRINTER_NOTIFY_INFO> pPrinterNotifyInfo)>( 'FreePrinterNotifyInfo'); expect(FreePrinterNotifyInfo, isA<Function>()); }); test('Can instantiate GetDefaultPrinter', () { final winspool = DynamicLibrary.open('winspool.drv'); final GetDefaultPrinter = winspool.lookupFunction< Int32 Function(Pointer<Utf16> pszBuffer, Pointer<Uint32> pcchBuffer), int Function(Pointer<Utf16> pszBuffer, Pointer<Uint32> pcchBuffer)>('GetDefaultPrinterW'); expect(GetDefaultPrinter, isA<Function>()); }); test('Can instantiate GetJob', () { final winspool = DynamicLibrary.open('winspool.drv'); final GetJob = winspool.lookupFunction< Int32 Function(IntPtr hPrinter, Uint32 JobId, Uint32 Level, Pointer<Uint8> pJob, Uint32 cbBuf, Pointer<Uint32> pcbNeeded), int Function(int hPrinter, int JobId, int Level, Pointer<Uint8> pJob, int cbBuf, Pointer<Uint32> pcbNeeded)>('GetJobW'); expect(GetJob, isA<Function>()); }); test('Can instantiate GetPrinter', () { final winspool = DynamicLibrary.open('winspool.drv'); final GetPrinter = winspool.lookupFunction< Int32 Function(IntPtr hPrinter, Uint32 Level, Pointer<Uint8> pPrinter, Uint32 cbBuf, Pointer<Uint32> pcbNeeded), int Function(int hPrinter, int Level, Pointer<Uint8> pPrinter, int cbBuf, Pointer<Uint32> pcbNeeded)>('GetPrinterW'); expect(GetPrinter, isA<Function>()); }); test('Can instantiate GetPrinterData', () { final winspool = DynamicLibrary.open('winspool.drv'); final GetPrinterData = winspool.lookupFunction< Uint32 Function( IntPtr hPrinter, Pointer<Utf16> pValueName, Pointer<Uint32> pType, Pointer<Uint8> pData, Uint32 nSize, Pointer<Uint32> pcbNeeded), int Function( int hPrinter, Pointer<Utf16> pValueName, Pointer<Uint32> pType, Pointer<Uint8> pData, int nSize, Pointer<Uint32> pcbNeeded)>('GetPrinterDataW'); expect(GetPrinterData, isA<Function>()); }); test('Can instantiate GetPrinterDataEx', () { final winspool = DynamicLibrary.open('winspool.drv'); final GetPrinterDataEx = winspool.lookupFunction< Uint32 Function( IntPtr hPrinter, Pointer<Utf16> pKeyName, Pointer<Utf16> pValueName, Pointer<Uint32> pType, Pointer<Uint8> pData, Uint32 nSize, Pointer<Uint32> pcbNeeded), int Function( int hPrinter, Pointer<Utf16> pKeyName, Pointer<Utf16> pValueName, Pointer<Uint32> pType, Pointer<Uint8> pData, int nSize, Pointer<Uint32> pcbNeeded)>('GetPrinterDataExW'); expect(GetPrinterDataEx, isA<Function>()); }); test('Can instantiate GetPrintExecutionData', () { final winspool = DynamicLibrary.open('winspool.drv'); final GetPrintExecutionData = winspool.lookupFunction< Int32 Function(Pointer<PRINT_EXECUTION_DATA> pData), int Function( Pointer<PRINT_EXECUTION_DATA> pData)>('GetPrintExecutionData'); expect(GetPrintExecutionData, isA<Function>()); }); test('Can instantiate IsValidDevmode', () { final winspool = DynamicLibrary.open('winspool.drv'); final IsValidDevmode = winspool.lookupFunction< Int32 Function(Pointer<DEVMODE> pDevmode, IntPtr DevmodeSize), int Function( Pointer<DEVMODE> pDevmode, int DevmodeSize)>('IsValidDevmodeW'); expect(IsValidDevmode, isA<Function>()); }); test('Can instantiate OpenPrinter', () { final winspool = DynamicLibrary.open('winspool.drv'); final OpenPrinter = winspool.lookupFunction< Int32 Function(Pointer<Utf16> pPrinterName, Pointer<IntPtr> phPrinter, Pointer<PRINTER_DEFAULTS> pDefault), int Function(Pointer<Utf16> pPrinterName, Pointer<IntPtr> phPrinter, Pointer<PRINTER_DEFAULTS> pDefault)>('OpenPrinterW'); expect(OpenPrinter, isA<Function>()); }); test('Can instantiate PrinterProperties', () { final winspool = DynamicLibrary.open('winspool.drv'); final PrinterProperties = winspool.lookupFunction< Int32 Function(IntPtr hWnd, IntPtr hPrinter), int Function(int hWnd, int hPrinter)>('PrinterProperties'); expect(PrinterProperties, isA<Function>()); }); test('Can instantiate ResetPrinter', () { final winspool = DynamicLibrary.open('winspool.drv'); final ResetPrinter = winspool.lookupFunction< Int32 Function(IntPtr hPrinter, Pointer<PRINTER_DEFAULTS> pDefault), int Function(int hPrinter, Pointer<PRINTER_DEFAULTS> pDefault)>('ResetPrinterW'); expect(ResetPrinter, isA<Function>()); }); test('Can instantiate SetDefaultPrinter', () { final winspool = DynamicLibrary.open('winspool.drv'); final SetDefaultPrinter = winspool.lookupFunction< Int32 Function(Pointer<Utf16> pszPrinter), int Function(Pointer<Utf16> pszPrinter)>('SetDefaultPrinterW'); expect(SetDefaultPrinter, isA<Function>()); }); test('Can instantiate SetForm', () { final winspool = DynamicLibrary.open('winspool.drv'); final SetForm = winspool.lookupFunction< Int32 Function(IntPtr hPrinter, Pointer<Utf16> pFormName, Uint32 Level, Pointer<Uint8> pForm), int Function(int hPrinter, Pointer<Utf16> pFormName, int Level, Pointer<Uint8> pForm)>('SetFormW'); expect(SetForm, isA<Function>()); }); test('Can instantiate SetJob', () { final winspool = DynamicLibrary.open('winspool.drv'); final SetJob = winspool.lookupFunction< Int32 Function(IntPtr hPrinter, Uint32 JobId, Uint32 Level, Pointer<Uint8> pJob, Uint32 Command), int Function(int hPrinter, int JobId, int Level, Pointer<Uint8> pJob, int Command)>('SetJobW'); expect(SetJob, isA<Function>()); }); test('Can instantiate SetPort', () { final winspool = DynamicLibrary.open('winspool.drv'); final SetPort = winspool.lookupFunction< Int32 Function(Pointer<Utf16> pName, Pointer<Utf16> pPortName, Uint32 dwLevel, Pointer<Uint8> pPortInfo), int Function(Pointer<Utf16> pName, Pointer<Utf16> pPortName, int dwLevel, Pointer<Uint8> pPortInfo)>('SetPortW'); expect(SetPort, isA<Function>()); }); test('Can instantiate SetPrinter', () { final winspool = DynamicLibrary.open('winspool.drv'); final SetPrinter = winspool.lookupFunction< Int32 Function(IntPtr hPrinter, Uint32 Level, Pointer<Uint8> pPrinter, Uint32 Command), int Function(int hPrinter, int Level, Pointer<Uint8> pPrinter, int Command)>('SetPrinterW'); expect(SetPrinter, isA<Function>()); }); test('Can instantiate SetPrinterData', () { final winspool = DynamicLibrary.open('winspool.drv'); final SetPrinterData = winspool.lookupFunction< Uint32 Function(IntPtr hPrinter, Pointer<Utf16> pValueName, Uint32 Type, Pointer<Uint8> pData, Uint32 cbData), int Function(int hPrinter, Pointer<Utf16> pValueName, int Type, Pointer<Uint8> pData, int cbData)>('SetPrinterDataW'); expect(SetPrinterData, isA<Function>()); }); test('Can instantiate SetPrinterDataEx', () { final winspool = DynamicLibrary.open('winspool.drv'); final SetPrinterDataEx = winspool.lookupFunction< Uint32 Function( IntPtr hPrinter, Pointer<Utf16> pKeyName, Pointer<Utf16> pValueName, Uint32 Type, Pointer<Uint8> pData, Uint32 cbData), int Function( int hPrinter, Pointer<Utf16> pKeyName, Pointer<Utf16> pValueName, int Type, Pointer<Uint8> pData, int cbData)>('SetPrinterDataExW'); expect(SetPrinterDataEx, isA<Function>()); }); test('Can instantiate StartDocPrinter', () { final winspool = DynamicLibrary.open('winspool.drv'); final StartDocPrinter = winspool.lookupFunction< Uint32 Function( IntPtr hPrinter, Uint32 Level, Pointer<DOC_INFO_1> pDocInfo), int Function(int hPrinter, int Level, Pointer<DOC_INFO_1> pDocInfo)>('StartDocPrinterW'); expect(StartDocPrinter, isA<Function>()); }); }); group('Test bthprops functions', () { test('Can instantiate BluetoothAuthenticateDeviceEx', () { final bthprops = DynamicLibrary.open('bthprops.cpl'); final BluetoothAuthenticateDeviceEx = bthprops.lookupFunction< Uint32 Function( IntPtr hwndParentIn, IntPtr hRadioIn, Pointer<BLUETOOTH_DEVICE_INFO> pbtdiInout, Pointer<BLUETOOTH_OOB_DATA_INFO> pbtOobData, Int32 authenticationRequirement), int Function( int hwndParentIn, int hRadioIn, Pointer<BLUETOOTH_DEVICE_INFO> pbtdiInout, Pointer<BLUETOOTH_OOB_DATA_INFO> pbtOobData, int authenticationRequirement)>('BluetoothAuthenticateDeviceEx'); expect(BluetoothAuthenticateDeviceEx, isA<Function>()); }); test('Can instantiate BluetoothDisplayDeviceProperties', () { final bthprops = DynamicLibrary.open('bthprops.cpl'); final BluetoothDisplayDeviceProperties = bthprops.lookupFunction< Int32 Function( IntPtr hwndParent, Pointer<BLUETOOTH_DEVICE_INFO> pbtdi), int Function( int hwndParent, Pointer<BLUETOOTH_DEVICE_INFO> pbtdi)>( 'BluetoothDisplayDeviceProperties'); expect(BluetoothDisplayDeviceProperties, isA<Function>()); }); test('Can instantiate BluetoothEnableDiscovery', () { final bthprops = DynamicLibrary.open('bthprops.cpl'); final BluetoothEnableDiscovery = bthprops.lookupFunction< Int32 Function(IntPtr hRadio, Int32 fEnabled), int Function(int hRadio, int fEnabled)>('BluetoothEnableDiscovery'); expect(BluetoothEnableDiscovery, isA<Function>()); }); test('Can instantiate BluetoothEnableIncomingConnections', () { final bthprops = DynamicLibrary.open('bthprops.cpl'); final BluetoothEnableIncomingConnections = bthprops.lookupFunction< Int32 Function(IntPtr hRadio, Int32 fEnabled), int Function( int hRadio, int fEnabled)>('BluetoothEnableIncomingConnections'); expect(BluetoothEnableIncomingConnections, isA<Function>()); }); test('Can instantiate BluetoothEnumerateInstalledServices', () { final bthprops = DynamicLibrary.open('bthprops.cpl'); final BluetoothEnumerateInstalledServices = bthprops.lookupFunction< Uint32 Function(IntPtr hRadio, Pointer<BLUETOOTH_DEVICE_INFO> pbtdi, Pointer<Uint32> pcServiceInout, Pointer<GUID> pGuidServices), int Function( int hRadio, Pointer<BLUETOOTH_DEVICE_INFO> pbtdi, Pointer<Uint32> pcServiceInout, Pointer<GUID> pGuidServices)>('BluetoothEnumerateInstalledServices'); expect(BluetoothEnumerateInstalledServices, isA<Function>()); }); test('Can instantiate BluetoothFindDeviceClose', () { final bthprops = DynamicLibrary.open('bthprops.cpl'); final BluetoothFindDeviceClose = bthprops.lookupFunction< Int32 Function(IntPtr hFind), int Function(int hFind)>('BluetoothFindDeviceClose'); expect(BluetoothFindDeviceClose, isA<Function>()); }); test('Can instantiate BluetoothFindFirstDevice', () { final bthprops = DynamicLibrary.open('bthprops.cpl'); final BluetoothFindFirstDevice = bthprops.lookupFunction< IntPtr Function(Pointer<BLUETOOTH_DEVICE_SEARCH_PARAMS> pbtsp, Pointer<BLUETOOTH_DEVICE_INFO> pbtdi), int Function(Pointer<BLUETOOTH_DEVICE_SEARCH_PARAMS> pbtsp, Pointer<BLUETOOTH_DEVICE_INFO> pbtdi)>( 'BluetoothFindFirstDevice'); expect(BluetoothFindFirstDevice, isA<Function>()); }); test('Can instantiate BluetoothFindFirstRadio', () { final bthprops = DynamicLibrary.open('bthprops.cpl'); final BluetoothFindFirstRadio = bthprops.lookupFunction< IntPtr Function(Pointer<BLUETOOTH_FIND_RADIO_PARAMS> pbtfrp, Pointer<IntPtr> phRadio), int Function(Pointer<BLUETOOTH_FIND_RADIO_PARAMS> pbtfrp, Pointer<IntPtr> phRadio)>('BluetoothFindFirstRadio'); expect(BluetoothFindFirstRadio, isA<Function>()); }); test('Can instantiate BluetoothFindNextDevice', () { final bthprops = DynamicLibrary.open('bthprops.cpl'); final BluetoothFindNextDevice = bthprops.lookupFunction< Int32 Function(IntPtr hFind, Pointer<BLUETOOTH_DEVICE_INFO> pbtdi), int Function(int hFind, Pointer<BLUETOOTH_DEVICE_INFO> pbtdi)>('BluetoothFindNextDevice'); expect(BluetoothFindNextDevice, isA<Function>()); }); test('Can instantiate BluetoothFindNextRadio', () { final bthprops = DynamicLibrary.open('bthprops.cpl'); final BluetoothFindNextRadio = bthprops.lookupFunction< Int32 Function(IntPtr hFind, Pointer<IntPtr> phRadio), int Function( int hFind, Pointer<IntPtr> phRadio)>('BluetoothFindNextRadio'); expect(BluetoothFindNextRadio, isA<Function>()); }); test('Can instantiate BluetoothFindRadioClose', () { final bthprops = DynamicLibrary.open('bthprops.cpl'); final BluetoothFindRadioClose = bthprops.lookupFunction< Int32 Function(IntPtr hFind), int Function(int hFind)>('BluetoothFindRadioClose'); expect(BluetoothFindRadioClose, isA<Function>()); }); test('Can instantiate BluetoothGetRadioInfo', () { final bthprops = DynamicLibrary.open('bthprops.cpl'); final BluetoothGetRadioInfo = bthprops.lookupFunction< Uint32 Function( IntPtr hRadio, Pointer<BLUETOOTH_RADIO_INFO> pRadioInfo), int Function( int hRadio, Pointer<BLUETOOTH_RADIO_INFO> pRadioInfo)>( 'BluetoothGetRadioInfo'); expect(BluetoothGetRadioInfo, isA<Function>()); }); test('Can instantiate BluetoothIsConnectable', () { final bthprops = DynamicLibrary.open('bthprops.cpl'); final BluetoothIsConnectable = bthprops.lookupFunction< Int32 Function(IntPtr hRadio), int Function(int hRadio)>('BluetoothIsConnectable'); expect(BluetoothIsConnectable, isA<Function>()); }); test('Can instantiate BluetoothIsDiscoverable', () { final bthprops = DynamicLibrary.open('bthprops.cpl'); final BluetoothIsDiscoverable = bthprops.lookupFunction< Int32 Function(IntPtr hRadio), int Function(int hRadio)>('BluetoothIsDiscoverable'); expect(BluetoothIsDiscoverable, isA<Function>()); }); test('Can instantiate BluetoothIsVersionAvailable', () { final bthprops = DynamicLibrary.open('bthprops.cpl'); final BluetoothIsVersionAvailable = bthprops.lookupFunction< Int32 Function(Uint8 MajorVersion, Uint8 MinorVersion), int Function(int MajorVersion, int MinorVersion)>('BluetoothIsVersionAvailable'); expect(BluetoothIsVersionAvailable, isA<Function>()); }); test('Can instantiate BluetoothRegisterForAuthenticationEx', () { final bthprops = DynamicLibrary.open('bthprops.cpl'); final BluetoothRegisterForAuthenticationEx = bthprops.lookupFunction< Uint32 Function( Pointer<BLUETOOTH_DEVICE_INFO> pbtdiIn, Pointer<IntPtr> phRegHandleOut, Pointer<NativeFunction<PfnAuthenticationCallbackEx>> pfnCallbackIn, Pointer pvParam), int Function( Pointer<BLUETOOTH_DEVICE_INFO> pbtdiIn, Pointer<IntPtr> phRegHandleOut, Pointer<NativeFunction<PfnAuthenticationCallbackEx>> pfnCallbackIn, Pointer pvParam)>('BluetoothRegisterForAuthenticationEx'); expect(BluetoothRegisterForAuthenticationEx, isA<Function>()); }); test('Can instantiate BluetoothRemoveDevice', () { final bthprops = DynamicLibrary.open('bthprops.cpl'); final BluetoothRemoveDevice = bthprops.lookupFunction< Uint32 Function(Pointer<BLUETOOTH_ADDRESS> pAddress), int Function( Pointer<BLUETOOTH_ADDRESS> pAddress)>('BluetoothRemoveDevice'); expect(BluetoothRemoveDevice, isA<Function>()); }); test('Can instantiate BluetoothSetServiceState', () { final bthprops = DynamicLibrary.open('bthprops.cpl'); final BluetoothSetServiceState = bthprops.lookupFunction< Uint32 Function(IntPtr hRadio, Pointer<BLUETOOTH_DEVICE_INFO> pbtdi, Pointer<GUID> pGuidService, Uint32 dwServiceFlags), int Function( int hRadio, Pointer<BLUETOOTH_DEVICE_INFO> pbtdi, Pointer<GUID> pGuidService, int dwServiceFlags)>('BluetoothSetServiceState'); expect(BluetoothSetServiceState, isA<Function>()); }); test('Can instantiate BluetoothUnregisterAuthentication', () { final bthprops = DynamicLibrary.open('bthprops.cpl'); final BluetoothUnregisterAuthentication = bthprops.lookupFunction< Int32 Function(IntPtr hRegHandle), int Function(int hRegHandle)>('BluetoothUnregisterAuthentication'); expect(BluetoothUnregisterAuthentication, isA<Function>()); }); test('Can instantiate BluetoothUpdateDeviceRecord', () { final bthprops = DynamicLibrary.open('bthprops.cpl'); final BluetoothUpdateDeviceRecord = bthprops.lookupFunction< Uint32 Function(Pointer<BLUETOOTH_DEVICE_INFO> pbtdi), int Function(Pointer<BLUETOOTH_DEVICE_INFO> pbtdi)>( 'BluetoothUpdateDeviceRecord'); expect(BluetoothUpdateDeviceRecord, isA<Function>()); }); }); group('Test powrprof functions', () { test('Can instantiate CallNtPowerInformation', () { final powrprof = DynamicLibrary.open('powrprof.dll'); final CallNtPowerInformation = powrprof.lookupFunction< Int32 Function( Int32 InformationLevel, Pointer InputBuffer, Uint32 InputBufferLength, Pointer OutputBuffer, Uint32 OutputBufferLength), int Function( int InformationLevel, Pointer InputBuffer, int InputBufferLength, Pointer OutputBuffer, int OutputBufferLength)>('CallNtPowerInformation'); expect(CallNtPowerInformation, isA<Function>()); }); }); group('Test comdlg32 functions', () { test('Can instantiate ChooseColor', () { final comdlg32 = DynamicLibrary.open('comdlg32.dll'); final ChooseColor = comdlg32.lookupFunction< Int32 Function(Pointer<CHOOSECOLOR> param0), int Function(Pointer<CHOOSECOLOR> param0)>('ChooseColorW'); expect(ChooseColor, isA<Function>()); }); test('Can instantiate ChooseFont', () { final comdlg32 = DynamicLibrary.open('comdlg32.dll'); final ChooseFont = comdlg32.lookupFunction< Int32 Function(Pointer<CHOOSEFONT> param0), int Function(Pointer<CHOOSEFONT> param0)>('ChooseFontW'); expect(ChooseFont, isA<Function>()); }); test('Can instantiate FindText', () { final comdlg32 = DynamicLibrary.open('comdlg32.dll'); final FindText = comdlg32.lookupFunction< IntPtr Function(Pointer<FINDREPLACE> param0), int Function(Pointer<FINDREPLACE> param0)>('FindTextW'); expect(FindText, isA<Function>()); }); test('Can instantiate GetOpenFileName', () { final comdlg32 = DynamicLibrary.open('comdlg32.dll'); final GetOpenFileName = comdlg32.lookupFunction< Int32 Function(Pointer<OPENFILENAME> param0), int Function(Pointer<OPENFILENAME> param0)>('GetOpenFileNameW'); expect(GetOpenFileName, isA<Function>()); }); test('Can instantiate GetSaveFileName', () { final comdlg32 = DynamicLibrary.open('comdlg32.dll'); final GetSaveFileName = comdlg32.lookupFunction< Int32 Function(Pointer<OPENFILENAME> param0), int Function(Pointer<OPENFILENAME> param0)>('GetSaveFileNameW'); expect(GetSaveFileName, isA<Function>()); }); test('Can instantiate ReplaceText', () { final comdlg32 = DynamicLibrary.open('comdlg32.dll'); final ReplaceText = comdlg32.lookupFunction< IntPtr Function(Pointer<FINDREPLACE> param0), int Function(Pointer<FINDREPLACE> param0)>('ReplaceTextW'); expect(ReplaceText, isA<Function>()); }); }); group('Test uxtheme functions', () { test('Can instantiate CloseThemeData', () { final uxtheme = DynamicLibrary.open('uxtheme.dll'); final CloseThemeData = uxtheme.lookupFunction< Int32 Function(IntPtr hTheme), int Function(int hTheme)>('CloseThemeData'); expect(CloseThemeData, isA<Function>()); }); test('Can instantiate DrawThemeBackground', () { final uxtheme = DynamicLibrary.open('uxtheme.dll'); final DrawThemeBackground = uxtheme.lookupFunction< Int32 Function(IntPtr hTheme, IntPtr hdc, Int32 iPartId, Int32 iStateId, Pointer<RECT> pRect, Pointer<RECT> pClipRect), int Function( int hTheme, int hdc, int iPartId, int iStateId, Pointer<RECT> pRect, Pointer<RECT> pClipRect)>('DrawThemeBackground'); expect(DrawThemeBackground, isA<Function>()); }); test('Can instantiate DrawThemeIcon', () { final uxtheme = DynamicLibrary.open('uxtheme.dll'); final DrawThemeIcon = uxtheme.lookupFunction< Int32 Function( IntPtr hTheme, IntPtr hdc, Int32 iPartId, Int32 iStateId, Pointer<RECT> pRect, IntPtr himl, Int32 iImageIndex), int Function(int hTheme, int hdc, int iPartId, int iStateId, Pointer<RECT> pRect, int himl, int iImageIndex)>('DrawThemeIcon'); expect(DrawThemeIcon, isA<Function>()); }); test('Can instantiate EnableThemeDialogTexture', () { final uxtheme = DynamicLibrary.open('uxtheme.dll'); final EnableThemeDialogTexture = uxtheme.lookupFunction< Int32 Function(IntPtr hwnd, Uint32 dwFlags), int Function(int hwnd, int dwFlags)>('EnableThemeDialogTexture'); expect(EnableThemeDialogTexture, isA<Function>()); }); test('Can instantiate GetCurrentThemeName', () { final uxtheme = DynamicLibrary.open('uxtheme.dll'); final GetCurrentThemeName = uxtheme.lookupFunction< Int32 Function( Pointer<Utf16> pszThemeFileName, Int32 cchMaxNameChars, Pointer<Utf16> pszColorBuff, Int32 cchMaxColorChars, Pointer<Utf16> pszSizeBuff, Int32 cchMaxSizeChars), int Function( Pointer<Utf16> pszThemeFileName, int cchMaxNameChars, Pointer<Utf16> pszColorBuff, int cchMaxColorChars, Pointer<Utf16> pszSizeBuff, int cchMaxSizeChars)>('GetCurrentThemeName'); expect(GetCurrentThemeName, isA<Function>()); }); test('Can instantiate GetThemeMetric', () { final uxtheme = DynamicLibrary.open('uxtheme.dll'); final GetThemeMetric = uxtheme.lookupFunction< Int32 Function(IntPtr hTheme, IntPtr hdc, Int32 iPartId, Int32 iStateId, Uint32 iPropId, Pointer<Int32> piVal), int Function(int hTheme, int hdc, int iPartId, int iStateId, int iPropId, Pointer<Int32> piVal)>('GetThemeMetric'); expect(GetThemeMetric, isA<Function>()); }); test('Can instantiate GetThemeRect', () { final uxtheme = DynamicLibrary.open('uxtheme.dll'); final GetThemeRect = uxtheme.lookupFunction< Int32 Function(IntPtr hTheme, Int32 iPartId, Int32 iStateId, Int32 iPropId, Pointer<RECT> pRect), int Function(int hTheme, int iPartId, int iStateId, int iPropId, Pointer<RECT> pRect)>('GetThemeRect'); expect(GetThemeRect, isA<Function>()); }); test('Can instantiate GetThemeSysColor', () { final uxtheme = DynamicLibrary.open('uxtheme.dll'); final GetThemeSysColor = uxtheme.lookupFunction< Uint32 Function(IntPtr hTheme, Int32 iColorId), int Function(int hTheme, int iColorId)>('GetThemeSysColor'); expect(GetThemeSysColor, isA<Function>()); }); test('Can instantiate GetThemeSysColorBrush', () { final uxtheme = DynamicLibrary.open('uxtheme.dll'); final GetThemeSysColorBrush = uxtheme.lookupFunction< IntPtr Function(IntPtr hTheme, Uint32 iColorId), int Function(int hTheme, int iColorId)>('GetThemeSysColorBrush'); expect(GetThemeSysColorBrush, isA<Function>()); }); test('Can instantiate GetThemeSysFont', () { final uxtheme = DynamicLibrary.open('uxtheme.dll'); final GetThemeSysFont = uxtheme.lookupFunction< Int32 Function(IntPtr hTheme, Uint32 iFontId, Pointer<LOGFONT> plf), int Function(int hTheme, int iFontId, Pointer<LOGFONT> plf)>('GetThemeSysFont'); expect(GetThemeSysFont, isA<Function>()); }); test('Can instantiate GetThemeSysSize', () { final uxtheme = DynamicLibrary.open('uxtheme.dll'); final GetThemeSysSize = uxtheme.lookupFunction< Int32 Function(IntPtr hTheme, Int32 iSizeId), int Function(int hTheme, int iSizeId)>('GetThemeSysSize'); expect(GetThemeSysSize, isA<Function>()); }); test('Can instantiate GetWindowTheme', () { final uxtheme = DynamicLibrary.open('uxtheme.dll'); final GetWindowTheme = uxtheme.lookupFunction< IntPtr Function(IntPtr hwnd), int Function(int hwnd)>('GetWindowTheme'); expect(GetWindowTheme, isA<Function>()); }); test('Can instantiate IsAppThemed', () { final uxtheme = DynamicLibrary.open('uxtheme.dll'); final IsAppThemed = uxtheme .lookupFunction<Int32 Function(), int Function()>('IsAppThemed'); expect(IsAppThemed, isA<Function>()); }); test('Can instantiate IsCompositionActive', () { final uxtheme = DynamicLibrary.open('uxtheme.dll'); final IsCompositionActive = uxtheme.lookupFunction<Int32 Function(), int Function()>( 'IsCompositionActive'); expect(IsCompositionActive, isA<Function>()); }); test('Can instantiate IsThemeActive', () { final uxtheme = DynamicLibrary.open('uxtheme.dll'); final IsThemeActive = uxtheme .lookupFunction<Int32 Function(), int Function()>('IsThemeActive'); expect(IsThemeActive, isA<Function>()); }); test('Can instantiate IsThemeBackgroundPartiallyTransparent', () { final uxtheme = DynamicLibrary.open('uxtheme.dll'); final IsThemeBackgroundPartiallyTransparent = uxtheme.lookupFunction< Int32 Function(IntPtr hTheme, Int32 iPartId, Int32 iStateId), int Function(int hTheme, int iPartId, int iStateId)>('IsThemeBackgroundPartiallyTransparent'); expect(IsThemeBackgroundPartiallyTransparent, isA<Function>()); }); test('Can instantiate IsThemeDialogTextureEnabled', () { final uxtheme = DynamicLibrary.open('uxtheme.dll'); final IsThemeDialogTextureEnabled = uxtheme.lookupFunction< Int32 Function(IntPtr hwnd), int Function(int hwnd)>('IsThemeDialogTextureEnabled'); expect(IsThemeDialogTextureEnabled, isA<Function>()); }); test('Can instantiate OpenThemeData', () { final uxtheme = DynamicLibrary.open('uxtheme.dll'); final OpenThemeData = uxtheme.lookupFunction< IntPtr Function(IntPtr hwnd, Pointer<Utf16> pszClassList), int Function(int hwnd, Pointer<Utf16> pszClassList)>('OpenThemeData'); expect(OpenThemeData, isA<Function>()); }); test('Can instantiate OpenThemeDataEx', () { final uxtheme = DynamicLibrary.open('uxtheme.dll'); final OpenThemeDataEx = uxtheme.lookupFunction< IntPtr Function( IntPtr hwnd, Pointer<Utf16> pszClassList, Uint32 dwFlags), int Function(int hwnd, Pointer<Utf16> pszClassList, int dwFlags)>('OpenThemeDataEx'); expect(OpenThemeDataEx, isA<Function>()); }); if (windowsBuildNumber >= 15063) { test('Can instantiate OpenThemeDataForDpi', () { final uxtheme = DynamicLibrary.open('uxtheme.dll'); final OpenThemeDataForDpi = uxtheme.lookupFunction< IntPtr Function( IntPtr hwnd, Pointer<Utf16> pszClassList, Uint32 dpi), int Function(int hwnd, Pointer<Utf16> pszClassList, int dpi)>('OpenThemeDataForDpi'); expect(OpenThemeDataForDpi, isA<Function>()); }); } test('Can instantiate SetWindowTheme', () { final uxtheme = DynamicLibrary.open('uxtheme.dll'); final SetWindowTheme = uxtheme.lookupFunction< Int32 Function(IntPtr hwnd, Pointer<Utf16> pszSubAppName, Pointer<Utf16> pszSubIdList), int Function(int hwnd, Pointer<Utf16> pszSubAppName, Pointer<Utf16> pszSubIdList)>('SetWindowTheme'); expect(SetWindowTheme, isA<Function>()); }); }); group('Test ole32 functions', () { test('Can instantiate CLSIDFromProgID', () { final ole32 = DynamicLibrary.open('ole32.dll'); final CLSIDFromProgID = ole32.lookupFunction< Int32 Function(Pointer<Utf16> lpszProgID, Pointer<GUID> lpclsid), int Function(Pointer<Utf16> lpszProgID, Pointer<GUID> lpclsid)>('CLSIDFromProgID'); expect(CLSIDFromProgID, isA<Function>()); }); test('Can instantiate CLSIDFromProgIDEx', () { final ole32 = DynamicLibrary.open('ole32.dll'); final CLSIDFromProgIDEx = ole32.lookupFunction< Int32 Function(Pointer<Utf16> lpszProgID, Pointer<GUID> lpclsid), int Function(Pointer<Utf16> lpszProgID, Pointer<GUID> lpclsid)>('CLSIDFromProgIDEx'); expect(CLSIDFromProgIDEx, isA<Function>()); }); test('Can instantiate CLSIDFromString', () { final ole32 = DynamicLibrary.open('ole32.dll'); final CLSIDFromString = ole32.lookupFunction< Int32 Function(Pointer<Utf16> lpsz, Pointer<GUID> pclsid), int Function( Pointer<Utf16> lpsz, Pointer<GUID> pclsid)>('CLSIDFromString'); expect(CLSIDFromString, isA<Function>()); }); test('Can instantiate CoAddRefServerProcess', () { final ole32 = DynamicLibrary.open('ole32.dll'); final CoAddRefServerProcess = ole32.lookupFunction<Uint32 Function(), int Function()>( 'CoAddRefServerProcess'); expect(CoAddRefServerProcess, isA<Function>()); }); test('Can instantiate CoCreateGuid', () { final ole32 = DynamicLibrary.open('ole32.dll'); final CoCreateGuid = ole32.lookupFunction< Int32 Function(Pointer<GUID> pguid), int Function(Pointer<GUID> pguid)>('CoCreateGuid'); expect(CoCreateGuid, isA<Function>()); }); test('Can instantiate CoCreateInstance', () { final ole32 = DynamicLibrary.open('ole32.dll'); final CoCreateInstance = ole32.lookupFunction< Int32 Function(Pointer<GUID> rclsid, Pointer<COMObject> pUnkOuter, Uint32 dwClsContext, Pointer<GUID> riid, Pointer<Pointer> ppv), int Function( Pointer<GUID> rclsid, Pointer<COMObject> pUnkOuter, int dwClsContext, Pointer<GUID> riid, Pointer<Pointer> ppv)>('CoCreateInstance'); expect(CoCreateInstance, isA<Function>()); }); test('Can instantiate CoGetClassObject', () { final ole32 = DynamicLibrary.open('ole32.dll'); final CoGetClassObject = ole32.lookupFunction< Int32 Function(Pointer<GUID> rclsid, Uint32 dwClsContext, Pointer pvReserved, Pointer<GUID> riid, Pointer<Pointer> ppv), int Function( Pointer<GUID> rclsid, int dwClsContext, Pointer pvReserved, Pointer<GUID> riid, Pointer<Pointer> ppv)>('CoGetClassObject'); expect(CoGetClassObject, isA<Function>()); }); test('Can instantiate CoGetCurrentProcess', () { final ole32 = DynamicLibrary.open('ole32.dll'); final CoGetCurrentProcess = ole32.lookupFunction<Uint32 Function(), int Function()>( 'CoGetCurrentProcess'); expect(CoGetCurrentProcess, isA<Function>()); }); test('Can instantiate CoInitializeEx', () { final ole32 = DynamicLibrary.open('ole32.dll'); final CoInitializeEx = ole32.lookupFunction< Int32 Function(Pointer pvReserved, Uint32 dwCoInit), int Function(Pointer pvReserved, int dwCoInit)>('CoInitializeEx'); expect(CoInitializeEx, isA<Function>()); }); test('Can instantiate CoInitializeSecurity', () { final ole32 = DynamicLibrary.open('ole32.dll'); final CoInitializeSecurity = ole32.lookupFunction< Int32 Function( Pointer<SECURITY_DESCRIPTOR> pSecDesc, Int32 cAuthSvc, Pointer<SOLE_AUTHENTICATION_SERVICE> asAuthSvc, Pointer pReserved1, Uint32 dwAuthnLevel, Uint32 dwImpLevel, Pointer pAuthList, Int32 dwCapabilities, Pointer pReserved3), int Function( Pointer<SECURITY_DESCRIPTOR> pSecDesc, int cAuthSvc, Pointer<SOLE_AUTHENTICATION_SERVICE> asAuthSvc, Pointer pReserved1, int dwAuthnLevel, int dwImpLevel, Pointer pAuthList, int dwCapabilities, Pointer pReserved3)>('CoInitializeSecurity'); expect(CoInitializeSecurity, isA<Function>()); }); test('Can instantiate CoSetProxyBlanket', () { final ole32 = DynamicLibrary.open('ole32.dll'); final CoSetProxyBlanket = ole32.lookupFunction< Int32 Function( Pointer<COMObject> pProxy, Uint32 dwAuthnSvc, Uint32 dwAuthzSvc, Pointer<Utf16> pServerPrincName, Uint32 dwAuthnLevel, Uint32 dwImpLevel, Pointer pAuthInfo, Int32 dwCapabilities), int Function( Pointer<COMObject> pProxy, int dwAuthnSvc, int dwAuthzSvc, Pointer<Utf16> pServerPrincName, int dwAuthnLevel, int dwImpLevel, Pointer pAuthInfo, int dwCapabilities)>('CoSetProxyBlanket'); expect(CoSetProxyBlanket, isA<Function>()); }); test('Can instantiate CoTaskMemAlloc', () { final ole32 = DynamicLibrary.open('ole32.dll'); final CoTaskMemAlloc = ole32.lookupFunction<Pointer Function(IntPtr cb), Pointer Function(int cb)>('CoTaskMemAlloc'); expect(CoTaskMemAlloc, isA<Function>()); }); test('Can instantiate CoTaskMemFree', () { final ole32 = DynamicLibrary.open('ole32.dll'); final CoTaskMemFree = ole32.lookupFunction<Void Function(Pointer pv), void Function(Pointer pv)>('CoTaskMemFree'); expect(CoTaskMemFree, isA<Function>()); }); test('Can instantiate CoTaskMemRealloc', () { final ole32 = DynamicLibrary.open('ole32.dll'); final CoTaskMemRealloc = ole32.lookupFunction< Pointer Function(Pointer pv, IntPtr cb), Pointer Function(Pointer pv, int cb)>('CoTaskMemRealloc'); expect(CoTaskMemRealloc, isA<Function>()); }); test('Can instantiate CoUninitialize', () { final ole32 = DynamicLibrary.open('ole32.dll'); final CoUninitialize = ole32 .lookupFunction<Void Function(), void Function()>('CoUninitialize'); expect(CoUninitialize, isA<Function>()); }); test('Can instantiate CoWaitForMultipleHandles', () { final ole32 = DynamicLibrary.open('ole32.dll'); final CoWaitForMultipleHandles = ole32.lookupFunction< Int32 Function(Uint32 dwFlags, Uint32 dwTimeout, Uint32 cHandles, Pointer<IntPtr> pHandles, Pointer<Uint32> lpdwindex), int Function( int dwFlags, int dwTimeout, int cHandles, Pointer<IntPtr> pHandles, Pointer<Uint32> lpdwindex)>('CoWaitForMultipleHandles'); expect(CoWaitForMultipleHandles, isA<Function>()); }); if (windowsBuildNumber >= 10586) { test('Can instantiate CoWaitForMultipleObjects', () { final ole32 = DynamicLibrary.open('ole32.dll'); final CoWaitForMultipleObjects = ole32.lookupFunction< Int32 Function(Uint32 dwFlags, Uint32 dwTimeout, Uint32 cHandles, Pointer<IntPtr> pHandles, Pointer<Uint32> lpdwindex), int Function( int dwFlags, int dwTimeout, int cHandles, Pointer<IntPtr> pHandles, Pointer<Uint32> lpdwindex)>('CoWaitForMultipleObjects'); expect(CoWaitForMultipleObjects, isA<Function>()); }); } test('Can instantiate IIDFromString', () { final ole32 = DynamicLibrary.open('ole32.dll'); final IIDFromString = ole32.lookupFunction< Int32 Function(Pointer<Utf16> lpsz, Pointer<GUID> lpiid), int Function( Pointer<Utf16> lpsz, Pointer<GUID> lpiid)>('IIDFromString'); expect(IIDFromString, isA<Function>()); }); test('Can instantiate OleInitialize', () { final ole32 = DynamicLibrary.open('ole32.dll'); final OleInitialize = ole32.lookupFunction< Int32 Function(Pointer pvReserved), int Function(Pointer pvReserved)>('OleInitialize'); expect(OleInitialize, isA<Function>()); }); test('Can instantiate OleUninitialize', () { final ole32 = DynamicLibrary.open('ole32.dll'); final OleUninitialize = ole32 .lookupFunction<Void Function(), void Function()>('OleUninitialize'); expect(OleUninitialize, isA<Function>()); }); test('Can instantiate ProgIDFromCLSID', () { final ole32 = DynamicLibrary.open('ole32.dll'); final ProgIDFromCLSID = ole32.lookupFunction< Int32 Function( Pointer<GUID> clsid, Pointer<Pointer<Utf16>> lplpszProgID), int Function(Pointer<GUID> clsid, Pointer<Pointer<Utf16>> lplpszProgID)>('ProgIDFromCLSID'); expect(ProgIDFromCLSID, isA<Function>()); }); test('Can instantiate StringFromCLSID', () { final ole32 = DynamicLibrary.open('ole32.dll'); final StringFromCLSID = ole32.lookupFunction< Int32 Function(Pointer<GUID> rclsid, Pointer<Pointer<Utf16>> lplpsz), int Function(Pointer<GUID> rclsid, Pointer<Pointer<Utf16>> lplpsz)>('StringFromCLSID'); expect(StringFromCLSID, isA<Function>()); }); test('Can instantiate StringFromGUID2', () { final ole32 = DynamicLibrary.open('ole32.dll'); final StringFromGUID2 = ole32.lookupFunction< Int32 Function( Pointer<GUID> rguid, Pointer<Utf16> lpsz, Int32 cchMax), int Function(Pointer<GUID> rguid, Pointer<Utf16> lpsz, int cchMax)>('StringFromGUID2'); expect(StringFromGUID2, isA<Function>()); }); test('Can instantiate StringFromIID', () { final ole32 = DynamicLibrary.open('ole32.dll'); final StringFromIID = ole32.lookupFunction< Int32 Function(Pointer<GUID> rclsid, Pointer<Pointer<Utf16>> lplpsz), int Function(Pointer<GUID> rclsid, Pointer<Pointer<Utf16>> lplpsz)>('StringFromIID'); expect(StringFromIID, isA<Function>()); }); }); group('Test shell32 functions', () { test('Can instantiate CommandLineToArgvW', () { final shell32 = DynamicLibrary.open('shell32.dll'); final CommandLineToArgvW = shell32.lookupFunction< Pointer<Pointer<Utf16>> Function( Pointer<Utf16> lpCmdLine, Pointer<Int32> pNumArgs), Pointer<Pointer<Utf16>> Function(Pointer<Utf16> lpCmdLine, Pointer<Int32> pNumArgs)>('CommandLineToArgvW'); expect(CommandLineToArgvW, isA<Function>()); }); test('Can instantiate ExtractAssociatedIcon', () { final shell32 = DynamicLibrary.open('shell32.dll'); final ExtractAssociatedIcon = shell32.lookupFunction< IntPtr Function( IntPtr hInst, Pointer<Utf16> pszIconPath, Pointer<Uint16> piIcon), int Function(int hInst, Pointer<Utf16> pszIconPath, Pointer<Uint16> piIcon)>('ExtractAssociatedIconW'); expect(ExtractAssociatedIcon, isA<Function>()); }); test('Can instantiate FindExecutable', () { final shell32 = DynamicLibrary.open('shell32.dll'); final FindExecutable = shell32.lookupFunction< IntPtr Function(Pointer<Utf16> lpFile, Pointer<Utf16> lpDirectory, Pointer<Utf16> lpResult), int Function(Pointer<Utf16> lpFile, Pointer<Utf16> lpDirectory, Pointer<Utf16> lpResult)>('FindExecutableW'); expect(FindExecutable, isA<Function>()); }); test('Can instantiate SHCreateItemFromParsingName', () { final shell32 = DynamicLibrary.open('shell32.dll'); final SHCreateItemFromParsingName = shell32.lookupFunction< Int32 Function(Pointer<Utf16> pszPath, Pointer<COMObject> pbc, Pointer<GUID> riid, Pointer<Pointer> ppv), int Function( Pointer<Utf16> pszPath, Pointer<COMObject> pbc, Pointer<GUID> riid, Pointer<Pointer> ppv)>('SHCreateItemFromParsingName'); expect(SHCreateItemFromParsingName, isA<Function>()); }); test('Can instantiate Shell_NotifyIcon', () { final shell32 = DynamicLibrary.open('shell32.dll'); final Shell_NotifyIcon = shell32.lookupFunction< Int32 Function(Uint32 dwMessage, Pointer<NOTIFYICONDATA> lpData), int Function(int dwMessage, Pointer<NOTIFYICONDATA> lpData)>('Shell_NotifyIconW'); expect(Shell_NotifyIcon, isA<Function>()); }); test('Can instantiate ShellAbout', () { final shell32 = DynamicLibrary.open('shell32.dll'); final ShellAbout = shell32.lookupFunction< Int32 Function(IntPtr hWnd, Pointer<Utf16> szApp, Pointer<Utf16> szOtherStuff, IntPtr hIcon), int Function(int hWnd, Pointer<Utf16> szApp, Pointer<Utf16> szOtherStuff, int hIcon)>('ShellAboutW'); expect(ShellAbout, isA<Function>()); }); test('Can instantiate ShellExecute', () { final shell32 = DynamicLibrary.open('shell32.dll'); final ShellExecute = shell32.lookupFunction< IntPtr Function( IntPtr hwnd, Pointer<Utf16> lpOperation, Pointer<Utf16> lpFile, Pointer<Utf16> lpParameters, Pointer<Utf16> lpDirectory, Int32 nShowCmd), int Function( int hwnd, Pointer<Utf16> lpOperation, Pointer<Utf16> lpFile, Pointer<Utf16> lpParameters, Pointer<Utf16> lpDirectory, int nShowCmd)>('ShellExecuteW'); expect(ShellExecute, isA<Function>()); }); test('Can instantiate ShellExecuteEx', () { final shell32 = DynamicLibrary.open('shell32.dll'); final ShellExecuteEx = shell32.lookupFunction< Int32 Function(Pointer<SHELLEXECUTEINFO> pExecInfo), int Function(Pointer<SHELLEXECUTEINFO> pExecInfo)>('ShellExecuteExW'); expect(ShellExecuteEx, isA<Function>()); }); test('Can instantiate SHEmptyRecycleBin', () { final shell32 = DynamicLibrary.open('shell32.dll'); final SHEmptyRecycleBin = shell32.lookupFunction< Int32 Function( IntPtr hwnd, Pointer<Utf16> pszRootPath, Uint32 dwFlags), int Function(int hwnd, Pointer<Utf16> pszRootPath, int dwFlags)>('SHEmptyRecycleBinW'); expect(SHEmptyRecycleBin, isA<Function>()); }); test('Can instantiate SHGetDesktopFolder', () { final shell32 = DynamicLibrary.open('shell32.dll'); final SHGetDesktopFolder = shell32.lookupFunction< Int32 Function(Pointer<Pointer<COMObject>> ppshf), int Function( Pointer<Pointer<COMObject>> ppshf)>('SHGetDesktopFolder'); expect(SHGetDesktopFolder, isA<Function>()); }); test('Can instantiate SHGetDiskFreeSpaceEx', () { final shell32 = DynamicLibrary.open('shell32.dll'); final SHGetDiskFreeSpaceEx = shell32.lookupFunction< Int32 Function( Pointer<Utf16> pszDirectoryName, Pointer<Uint64> pulFreeBytesAvailableToCaller, Pointer<Uint64> pulTotalNumberOfBytes, Pointer<Uint64> pulTotalNumberOfFreeBytes), int Function( Pointer<Utf16> pszDirectoryName, Pointer<Uint64> pulFreeBytesAvailableToCaller, Pointer<Uint64> pulTotalNumberOfBytes, Pointer<Uint64> pulTotalNumberOfFreeBytes)>( 'SHGetDiskFreeSpaceExW'); expect(SHGetDiskFreeSpaceEx, isA<Function>()); }); test('Can instantiate SHGetDriveMedia', () { final shell32 = DynamicLibrary.open('shell32.dll'); final SHGetDriveMedia = shell32.lookupFunction< Int32 Function( Pointer<Utf16> pszDrive, Pointer<Uint32> pdwMediaContent), int Function(Pointer<Utf16> pszDrive, Pointer<Uint32> pdwMediaContent)>('SHGetDriveMedia'); expect(SHGetDriveMedia, isA<Function>()); }); test('Can instantiate SHGetFolderPath', () { final shell32 = DynamicLibrary.open('shell32.dll'); final SHGetFolderPath = shell32.lookupFunction< Int32 Function(IntPtr hwnd, Int32 csidl, IntPtr hToken, Uint32 dwFlags, Pointer<Utf16> pszPath), int Function(int hwnd, int csidl, int hToken, int dwFlags, Pointer<Utf16> pszPath)>('SHGetFolderPathW'); expect(SHGetFolderPath, isA<Function>()); }); test('Can instantiate SHGetKnownFolderPath', () { final shell32 = DynamicLibrary.open('shell32.dll'); final SHGetKnownFolderPath = shell32.lookupFunction< Int32 Function(Pointer<GUID> rfid, Uint32 dwFlags, IntPtr hToken, Pointer<Pointer<Utf16>> ppszPath), int Function(Pointer<GUID> rfid, int dwFlags, int hToken, Pointer<Pointer<Utf16>> ppszPath)>('SHGetKnownFolderPath'); expect(SHGetKnownFolderPath, isA<Function>()); }); test('Can instantiate SHQueryRecycleBin', () { final shell32 = DynamicLibrary.open('shell32.dll'); final SHQueryRecycleBin = shell32.lookupFunction< Int32 Function(Pointer<Utf16> pszRootPath, Pointer<SHQUERYRBINFO> pSHQueryRBInfo), int Function(Pointer<Utf16> pszRootPath, Pointer<SHQUERYRBINFO> pSHQueryRBInfo)>('SHQueryRecycleBinW'); expect(SHQueryRecycleBin, isA<Function>()); }); }); group('Test kernelbase functions', () { if (windowsBuildNumber >= 10240) { test('Can instantiate CompareObjectHandles', () { final kernelbase = DynamicLibrary.open('kernelbase.dll'); final CompareObjectHandles = kernelbase.lookupFunction< Int32 Function( IntPtr hFirstObjectHandle, IntPtr hSecondObjectHandle), int Function(int hFirstObjectHandle, int hSecondObjectHandle)>('CompareObjectHandles'); expect(CompareObjectHandles, isA<Function>()); }); } if (windowsBuildNumber >= 17134) { test('Can instantiate GetCommPorts', () { final kernelbase = DynamicLibrary.open('kernelbase.dll'); final GetCommPorts = kernelbase.lookupFunction< Uint32 Function(Pointer<Uint32> lpPortNumbers, Uint32 uPortNumbersCount, Pointer<Uint32> puPortNumbersFound), int Function(Pointer<Uint32> lpPortNumbers, int uPortNumbersCount, Pointer<Uint32> puPortNumbersFound)>('GetCommPorts'); expect(GetCommPorts, isA<Function>()); }); } if (windowsBuildNumber >= 10240) { test('Can instantiate GetIntegratedDisplaySize', () { final kernelbase = DynamicLibrary.open('kernelbase.dll'); final GetIntegratedDisplaySize = kernelbase.lookupFunction< Int32 Function(Pointer<Double> sizeInInches), int Function( Pointer<Double> sizeInInches)>('GetIntegratedDisplaySize'); expect(GetIntegratedDisplaySize, isA<Function>()); }); } if (windowsBuildNumber >= 17134) { test('Can instantiate OpenCommPort', () { final kernelbase = DynamicLibrary.open('kernelbase.dll'); final OpenCommPort = kernelbase.lookupFunction< IntPtr Function(Uint32 uPortNumber, Uint32 dwDesiredAccess, Uint32 dwFlagsAndAttributes), int Function(int uPortNumber, int dwDesiredAccess, int dwFlagsAndAttributes)>('OpenCommPort'); expect(OpenCommPort, isA<Function>()); }); } }); group('Test advapi32 functions', () { test('Can instantiate CredDelete', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final CredDelete = advapi32.lookupFunction< Int32 Function(Pointer<Utf16> TargetName, Uint32 Type, Uint32 Flags), int Function( Pointer<Utf16> TargetName, int Type, int Flags)>('CredDeleteW'); expect(CredDelete, isA<Function>()); }); test('Can instantiate CredFree', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final CredFree = advapi32.lookupFunction<Void Function(Pointer Buffer), void Function(Pointer Buffer)>('CredFree'); expect(CredFree, isA<Function>()); }); test('Can instantiate CredRead', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final CredRead = advapi32.lookupFunction< Int32 Function(Pointer<Utf16> TargetName, Uint32 Type, Uint32 Flags, Pointer<Pointer<CREDENTIAL>> Credential), int Function(Pointer<Utf16> TargetName, int Type, int Flags, Pointer<Pointer<CREDENTIAL>> Credential)>('CredReadW'); expect(CredRead, isA<Function>()); }); test('Can instantiate CredWrite', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final CredWrite = advapi32.lookupFunction< Int32 Function(Pointer<CREDENTIAL> Credential, Uint32 Flags), int Function( Pointer<CREDENTIAL> Credential, int Flags)>('CredWriteW'); expect(CredWrite, isA<Function>()); }); test('Can instantiate DecryptFile', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final DecryptFile = advapi32.lookupFunction< Int32 Function(Pointer<Utf16> lpFileName, Uint32 dwReserved), int Function( Pointer<Utf16> lpFileName, int dwReserved)>('DecryptFileW'); expect(DecryptFile, isA<Function>()); }); test('Can instantiate EncryptFile', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final EncryptFile = advapi32.lookupFunction< Int32 Function(Pointer<Utf16> lpFileName), int Function(Pointer<Utf16> lpFileName)>('EncryptFileW'); expect(EncryptFile, isA<Function>()); }); test('Can instantiate FileEncryptionStatus', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final FileEncryptionStatus = advapi32.lookupFunction< Int32 Function(Pointer<Utf16> lpFileName, Pointer<Uint32> lpStatus), int Function(Pointer<Utf16> lpFileName, Pointer<Uint32> lpStatus)>('FileEncryptionStatusW'); expect(FileEncryptionStatus, isA<Function>()); }); test('Can instantiate GetTokenInformation', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final GetTokenInformation = advapi32.lookupFunction< Int32 Function( IntPtr TokenHandle, Int32 TokenInformationClass, Pointer TokenInformation, Uint32 TokenInformationLength, Pointer<Uint32> ReturnLength), int Function( int TokenHandle, int TokenInformationClass, Pointer TokenInformation, int TokenInformationLength, Pointer<Uint32> ReturnLength)>('GetTokenInformation'); expect(GetTokenInformation, isA<Function>()); }); test('Can instantiate InitiateShutdown', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final InitiateShutdown = advapi32.lookupFunction< Uint32 Function( Pointer<Utf16> lpMachineName, Pointer<Utf16> lpMessage, Uint32 dwGracePeriod, Uint32 dwShutdownFlags, Uint32 dwReason), int Function( Pointer<Utf16> lpMachineName, Pointer<Utf16> lpMessage, int dwGracePeriod, int dwShutdownFlags, int dwReason)>('InitiateShutdownW'); expect(InitiateShutdown, isA<Function>()); }); test('Can instantiate OpenProcessToken', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final OpenProcessToken = advapi32.lookupFunction< Int32 Function(IntPtr ProcessHandle, Uint32 DesiredAccess, Pointer<IntPtr> TokenHandle), int Function(int ProcessHandle, int DesiredAccess, Pointer<IntPtr> TokenHandle)>('OpenProcessToken'); expect(OpenProcessToken, isA<Function>()); }); test('Can instantiate OpenThreadToken', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final OpenThreadToken = advapi32.lookupFunction< Int32 Function(IntPtr ThreadHandle, Uint32 DesiredAccess, Int32 OpenAsSelf, Pointer<IntPtr> TokenHandle), int Function(int ThreadHandle, int DesiredAccess, int OpenAsSelf, Pointer<IntPtr> TokenHandle)>('OpenThreadToken'); expect(OpenThreadToken, isA<Function>()); }); test('Can instantiate RegCloseKey', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegCloseKey = advapi32.lookupFunction<Uint32 Function(IntPtr hKey), int Function(int hKey)>('RegCloseKey'); expect(RegCloseKey, isA<Function>()); }); test('Can instantiate RegConnectRegistry', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegConnectRegistry = advapi32.lookupFunction< Uint32 Function(Pointer<Utf16> lpMachineName, IntPtr hKey, Pointer<IntPtr> phkResult), int Function(Pointer<Utf16> lpMachineName, int hKey, Pointer<IntPtr> phkResult)>('RegConnectRegistryW'); expect(RegConnectRegistry, isA<Function>()); }); test('Can instantiate RegCopyTree', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegCopyTree = advapi32.lookupFunction< Uint32 Function( IntPtr hKeySrc, Pointer<Utf16> lpSubKey, IntPtr hKeyDest), int Function(int hKeySrc, Pointer<Utf16> lpSubKey, int hKeyDest)>('RegCopyTreeW'); expect(RegCopyTree, isA<Function>()); }); test('Can instantiate RegCreateKey', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegCreateKey = advapi32.lookupFunction< Uint32 Function( IntPtr hKey, Pointer<Utf16> lpSubKey, Pointer<IntPtr> phkResult), int Function(int hKey, Pointer<Utf16> lpSubKey, Pointer<IntPtr> phkResult)>('RegCreateKeyW'); expect(RegCreateKey, isA<Function>()); }); test('Can instantiate RegCreateKeyEx', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegCreateKeyEx = advapi32.lookupFunction< Uint32 Function( IntPtr hKey, Pointer<Utf16> lpSubKey, Uint32 Reserved, Pointer<Utf16> lpClass, Uint32 dwOptions, Uint32 samDesired, Pointer<SECURITY_ATTRIBUTES> lpSecurityAttributes, Pointer<IntPtr> phkResult, Pointer<Uint32> lpdwDisposition), int Function( int hKey, Pointer<Utf16> lpSubKey, int Reserved, Pointer<Utf16> lpClass, int dwOptions, int samDesired, Pointer<SECURITY_ATTRIBUTES> lpSecurityAttributes, Pointer<IntPtr> phkResult, Pointer<Uint32> lpdwDisposition)>('RegCreateKeyExW'); expect(RegCreateKeyEx, isA<Function>()); }); test('Can instantiate RegCreateKeyTransacted', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegCreateKeyTransacted = advapi32.lookupFunction< Uint32 Function( IntPtr hKey, Pointer<Utf16> lpSubKey, Uint32 Reserved, Pointer<Utf16> lpClass, Uint32 dwOptions, Uint32 samDesired, Pointer<SECURITY_ATTRIBUTES> lpSecurityAttributes, Pointer<IntPtr> phkResult, Pointer<Uint32> lpdwDisposition, IntPtr hTransaction, Pointer pExtendedParemeter), int Function( int hKey, Pointer<Utf16> lpSubKey, int Reserved, Pointer<Utf16> lpClass, int dwOptions, int samDesired, Pointer<SECURITY_ATTRIBUTES> lpSecurityAttributes, Pointer<IntPtr> phkResult, Pointer<Uint32> lpdwDisposition, int hTransaction, Pointer pExtendedParemeter)>('RegCreateKeyTransactedW'); expect(RegCreateKeyTransacted, isA<Function>()); }); test('Can instantiate RegDeleteKey', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegDeleteKey = advapi32.lookupFunction< Uint32 Function(IntPtr hKey, Pointer<Utf16> lpSubKey), int Function(int hKey, Pointer<Utf16> lpSubKey)>('RegDeleteKeyW'); expect(RegDeleteKey, isA<Function>()); }); test('Can instantiate RegDeleteKeyEx', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegDeleteKeyEx = advapi32.lookupFunction< Uint32 Function(IntPtr hKey, Pointer<Utf16> lpSubKey, Uint32 samDesired, Uint32 Reserved), int Function(int hKey, Pointer<Utf16> lpSubKey, int samDesired, int Reserved)>('RegDeleteKeyExW'); expect(RegDeleteKeyEx, isA<Function>()); }); test('Can instantiate RegDeleteKeyTransacted', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegDeleteKeyTransacted = advapi32.lookupFunction< Uint32 Function( IntPtr hKey, Pointer<Utf16> lpSubKey, Uint32 samDesired, Uint32 Reserved, IntPtr hTransaction, Pointer pExtendedParameter), int Function( int hKey, Pointer<Utf16> lpSubKey, int samDesired, int Reserved, int hTransaction, Pointer pExtendedParameter)>('RegDeleteKeyTransactedW'); expect(RegDeleteKeyTransacted, isA<Function>()); }); test('Can instantiate RegDeleteKeyValue', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegDeleteKeyValue = advapi32.lookupFunction< Uint32 Function( IntPtr hKey, Pointer<Utf16> lpSubKey, Pointer<Utf16> lpValueName), int Function(int hKey, Pointer<Utf16> lpSubKey, Pointer<Utf16> lpValueName)>('RegDeleteKeyValueW'); expect(RegDeleteKeyValue, isA<Function>()); }); test('Can instantiate RegDeleteTree', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegDeleteTree = advapi32.lookupFunction< Uint32 Function(IntPtr hKey, Pointer<Utf16> lpSubKey), int Function(int hKey, Pointer<Utf16> lpSubKey)>('RegDeleteTreeW'); expect(RegDeleteTree, isA<Function>()); }); test('Can instantiate RegDeleteValue', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegDeleteValue = advapi32.lookupFunction< Uint32 Function(IntPtr hKey, Pointer<Utf16> lpValueName), int Function( int hKey, Pointer<Utf16> lpValueName)>('RegDeleteValueW'); expect(RegDeleteValue, isA<Function>()); }); test('Can instantiate RegDisablePredefinedCache', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegDisablePredefinedCache = advapi32.lookupFunction<Uint32 Function(), int Function()>( 'RegDisablePredefinedCache'); expect(RegDisablePredefinedCache, isA<Function>()); }); test('Can instantiate RegDisablePredefinedCacheEx', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegDisablePredefinedCacheEx = advapi32.lookupFunction<Uint32 Function(), int Function()>( 'RegDisablePredefinedCacheEx'); expect(RegDisablePredefinedCacheEx, isA<Function>()); }); test('Can instantiate RegDisableReflectionKey', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegDisableReflectionKey = advapi32.lookupFunction< Uint32 Function(IntPtr hBase), int Function(int hBase)>('RegDisableReflectionKey'); expect(RegDisableReflectionKey, isA<Function>()); }); test('Can instantiate RegEnableReflectionKey', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegEnableReflectionKey = advapi32.lookupFunction< Uint32 Function(IntPtr hBase), int Function(int hBase)>('RegEnableReflectionKey'); expect(RegEnableReflectionKey, isA<Function>()); }); test('Can instantiate RegEnumKey', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegEnumKey = advapi32.lookupFunction< Uint32 Function(IntPtr hKey, Uint32 dwIndex, Pointer<Utf16> lpName, Uint32 cchName), int Function(int hKey, int dwIndex, Pointer<Utf16> lpName, int cchName)>('RegEnumKeyW'); expect(RegEnumKey, isA<Function>()); }); test('Can instantiate RegEnumKeyEx', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegEnumKeyEx = advapi32.lookupFunction< Uint32 Function( IntPtr hKey, Uint32 dwIndex, Pointer<Utf16> lpName, Pointer<Uint32> lpcchName, Pointer<Uint32> lpReserved, Pointer<Utf16> lpClass, Pointer<Uint32> lpcchClass, Pointer<FILETIME> lpftLastWriteTime), int Function( int hKey, int dwIndex, Pointer<Utf16> lpName, Pointer<Uint32> lpcchName, Pointer<Uint32> lpReserved, Pointer<Utf16> lpClass, Pointer<Uint32> lpcchClass, Pointer<FILETIME> lpftLastWriteTime)>('RegEnumKeyExW'); expect(RegEnumKeyEx, isA<Function>()); }); test('Can instantiate RegEnumValue', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegEnumValue = advapi32.lookupFunction< Uint32 Function( IntPtr hKey, Uint32 dwIndex, Pointer<Utf16> lpValueName, Pointer<Uint32> lpcchValueName, Pointer<Uint32> lpReserved, Pointer<Uint32> lpType, Pointer<Uint8> lpData, Pointer<Uint32> lpcbData), int Function( int hKey, int dwIndex, Pointer<Utf16> lpValueName, Pointer<Uint32> lpcchValueName, Pointer<Uint32> lpReserved, Pointer<Uint32> lpType, Pointer<Uint8> lpData, Pointer<Uint32> lpcbData)>('RegEnumValueW'); expect(RegEnumValue, isA<Function>()); }); test('Can instantiate RegFlushKey', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegFlushKey = advapi32.lookupFunction<Uint32 Function(IntPtr hKey), int Function(int hKey)>('RegFlushKey'); expect(RegFlushKey, isA<Function>()); }); test('Can instantiate RegGetValue', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegGetValue = advapi32.lookupFunction< Uint32 Function( IntPtr hkey, Pointer<Utf16> lpSubKey, Pointer<Utf16> lpValue, Uint32 dwFlags, Pointer<Uint32> pdwType, Pointer pvData, Pointer<Uint32> pcbData), int Function( int hkey, Pointer<Utf16> lpSubKey, Pointer<Utf16> lpValue, int dwFlags, Pointer<Uint32> pdwType, Pointer pvData, Pointer<Uint32> pcbData)>('RegGetValueW'); expect(RegGetValue, isA<Function>()); }); test('Can instantiate RegLoadAppKey', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegLoadAppKey = advapi32.lookupFunction< Uint32 Function(Pointer<Utf16> lpFile, Pointer<IntPtr> phkResult, Uint32 samDesired, Uint32 dwOptions, Uint32 Reserved), int Function(Pointer<Utf16> lpFile, Pointer<IntPtr> phkResult, int samDesired, int dwOptions, int Reserved)>('RegLoadAppKeyW'); expect(RegLoadAppKey, isA<Function>()); }); test('Can instantiate RegLoadKey', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegLoadKey = advapi32.lookupFunction< Uint32 Function( IntPtr hKey, Pointer<Utf16> lpSubKey, Pointer<Utf16> lpFile), int Function(int hKey, Pointer<Utf16> lpSubKey, Pointer<Utf16> lpFile)>('RegLoadKeyW'); expect(RegLoadKey, isA<Function>()); }); test('Can instantiate RegLoadMUIString', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegLoadMUIString = advapi32.lookupFunction< Uint32 Function( IntPtr hKey, Pointer<Utf16> pszValue, Pointer<Utf16> pszOutBuf, Uint32 cbOutBuf, Pointer<Uint32> pcbData, Uint32 Flags, Pointer<Utf16> pszDirectory), int Function( int hKey, Pointer<Utf16> pszValue, Pointer<Utf16> pszOutBuf, int cbOutBuf, Pointer<Uint32> pcbData, int Flags, Pointer<Utf16> pszDirectory)>('RegLoadMUIStringW'); expect(RegLoadMUIString, isA<Function>()); }); test('Can instantiate RegNotifyChangeKeyValue', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegNotifyChangeKeyValue = advapi32.lookupFunction< Uint32 Function(IntPtr hKey, Int32 bWatchSubtree, Uint32 dwNotifyFilter, IntPtr hEvent, Int32 fAsynchronous), int Function(int hKey, int bWatchSubtree, int dwNotifyFilter, int hEvent, int fAsynchronous)>('RegNotifyChangeKeyValue'); expect(RegNotifyChangeKeyValue, isA<Function>()); }); test('Can instantiate RegOpenCurrentUser', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegOpenCurrentUser = advapi32.lookupFunction< Uint32 Function(Uint32 samDesired, Pointer<IntPtr> phkResult), int Function( int samDesired, Pointer<IntPtr> phkResult)>('RegOpenCurrentUser'); expect(RegOpenCurrentUser, isA<Function>()); }); test('Can instantiate RegOpenKey', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegOpenKey = advapi32.lookupFunction< Uint32 Function( IntPtr hKey, Pointer<Utf16> lpSubKey, Pointer<IntPtr> phkResult), int Function(int hKey, Pointer<Utf16> lpSubKey, Pointer<IntPtr> phkResult)>('RegOpenKeyW'); expect(RegOpenKey, isA<Function>()); }); test('Can instantiate RegOpenKeyEx', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegOpenKeyEx = advapi32.lookupFunction< Uint32 Function(IntPtr hKey, Pointer<Utf16> lpSubKey, Uint32 ulOptions, Uint32 samDesired, Pointer<IntPtr> phkResult), int Function(int hKey, Pointer<Utf16> lpSubKey, int ulOptions, int samDesired, Pointer<IntPtr> phkResult)>('RegOpenKeyExW'); expect(RegOpenKeyEx, isA<Function>()); }); test('Can instantiate RegOpenKeyTransacted', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegOpenKeyTransacted = advapi32.lookupFunction< Uint32 Function( IntPtr hKey, Pointer<Utf16> lpSubKey, Uint32 ulOptions, Uint32 samDesired, Pointer<IntPtr> phkResult, IntPtr hTransaction, Pointer pExtendedParemeter), int Function( int hKey, Pointer<Utf16> lpSubKey, int ulOptions, int samDesired, Pointer<IntPtr> phkResult, int hTransaction, Pointer pExtendedParemeter)>('RegOpenKeyTransactedW'); expect(RegOpenKeyTransacted, isA<Function>()); }); test('Can instantiate RegOpenUserClassesRoot', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegOpenUserClassesRoot = advapi32.lookupFunction< Uint32 Function(IntPtr hToken, Uint32 dwOptions, Uint32 samDesired, Pointer<IntPtr> phkResult), int Function(int hToken, int dwOptions, int samDesired, Pointer<IntPtr> phkResult)>('RegOpenUserClassesRoot'); expect(RegOpenUserClassesRoot, isA<Function>()); }); test('Can instantiate RegOverridePredefKey', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegOverridePredefKey = advapi32.lookupFunction< Uint32 Function(IntPtr hKey, IntPtr hNewHKey), int Function(int hKey, int hNewHKey)>('RegOverridePredefKey'); expect(RegOverridePredefKey, isA<Function>()); }); test('Can instantiate RegQueryInfoKey', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegQueryInfoKey = advapi32.lookupFunction< Uint32 Function( IntPtr hKey, Pointer<Utf16> lpClass, Pointer<Uint32> lpcchClass, Pointer<Uint32> lpReserved, Pointer<Uint32> lpcSubKeys, Pointer<Uint32> lpcbMaxSubKeyLen, Pointer<Uint32> lpcbMaxClassLen, Pointer<Uint32> lpcValues, Pointer<Uint32> lpcbMaxValueNameLen, Pointer<Uint32> lpcbMaxValueLen, Pointer<Uint32> lpcbSecurityDescriptor, Pointer<FILETIME> lpftLastWriteTime), int Function( int hKey, Pointer<Utf16> lpClass, Pointer<Uint32> lpcchClass, Pointer<Uint32> lpReserved, Pointer<Uint32> lpcSubKeys, Pointer<Uint32> lpcbMaxSubKeyLen, Pointer<Uint32> lpcbMaxClassLen, Pointer<Uint32> lpcValues, Pointer<Uint32> lpcbMaxValueNameLen, Pointer<Uint32> lpcbMaxValueLen, Pointer<Uint32> lpcbSecurityDescriptor, Pointer<FILETIME> lpftLastWriteTime)>('RegQueryInfoKeyW'); expect(RegQueryInfoKey, isA<Function>()); }); test('Can instantiate RegQueryMultipleValues', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegQueryMultipleValues = advapi32.lookupFunction< Uint32 Function( IntPtr hKey, Pointer<VALENT> val_list, Uint32 num_vals, Pointer<Utf16> lpValueBuf, Pointer<Uint32> ldwTotsize), int Function( int hKey, Pointer<VALENT> val_list, int num_vals, Pointer<Utf16> lpValueBuf, Pointer<Uint32> ldwTotsize)>('RegQueryMultipleValuesW'); expect(RegQueryMultipleValues, isA<Function>()); }); test('Can instantiate RegQueryReflectionKey', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegQueryReflectionKey = advapi32.lookupFunction< Uint32 Function(IntPtr hBase, Pointer<Int32> bIsReflectionDisabled), int Function(int hBase, Pointer<Int32> bIsReflectionDisabled)>('RegQueryReflectionKey'); expect(RegQueryReflectionKey, isA<Function>()); }); test('Can instantiate RegQueryValue', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegQueryValue = advapi32.lookupFunction< Uint32 Function(IntPtr hKey, Pointer<Utf16> lpSubKey, Pointer<Utf16> lpData, Pointer<Int32> lpcbData), int Function(int hKey, Pointer<Utf16> lpSubKey, Pointer<Utf16> lpData, Pointer<Int32> lpcbData)>('RegQueryValueW'); expect(RegQueryValue, isA<Function>()); }); test('Can instantiate RegQueryValueEx', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegQueryValueEx = advapi32.lookupFunction< Uint32 Function( IntPtr hKey, Pointer<Utf16> lpValueName, Pointer<Uint32> lpReserved, Pointer<Uint32> lpType, Pointer<Uint8> lpData, Pointer<Uint32> lpcbData), int Function( int hKey, Pointer<Utf16> lpValueName, Pointer<Uint32> lpReserved, Pointer<Uint32> lpType, Pointer<Uint8> lpData, Pointer<Uint32> lpcbData)>('RegQueryValueExW'); expect(RegQueryValueEx, isA<Function>()); }); test('Can instantiate RegReplaceKey', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegReplaceKey = advapi32.lookupFunction< Uint32 Function(IntPtr hKey, Pointer<Utf16> lpSubKey, Pointer<Utf16> lpNewFile, Pointer<Utf16> lpOldFile), int Function( int hKey, Pointer<Utf16> lpSubKey, Pointer<Utf16> lpNewFile, Pointer<Utf16> lpOldFile)>('RegReplaceKeyW'); expect(RegReplaceKey, isA<Function>()); }); test('Can instantiate RegRestoreKey', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegRestoreKey = advapi32.lookupFunction< Uint32 Function(IntPtr hKey, Pointer<Utf16> lpFile, Int32 dwFlags), int Function( int hKey, Pointer<Utf16> lpFile, int dwFlags)>('RegRestoreKeyW'); expect(RegRestoreKey, isA<Function>()); }); test('Can instantiate RegSaveKey', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegSaveKey = advapi32.lookupFunction< Uint32 Function(IntPtr hKey, Pointer<Utf16> lpFile, Pointer<SECURITY_ATTRIBUTES> lpSecurityAttributes), int Function(int hKey, Pointer<Utf16> lpFile, Pointer<SECURITY_ATTRIBUTES> lpSecurityAttributes)>( 'RegSaveKeyW'); expect(RegSaveKey, isA<Function>()); }); test('Can instantiate RegSaveKeyEx', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegSaveKeyEx = advapi32.lookupFunction< Uint32 Function(IntPtr hKey, Pointer<Utf16> lpFile, Pointer<SECURITY_ATTRIBUTES> lpSecurityAttributes, Uint32 Flags), int Function( int hKey, Pointer<Utf16> lpFile, Pointer<SECURITY_ATTRIBUTES> lpSecurityAttributes, int Flags)>('RegSaveKeyExW'); expect(RegSaveKeyEx, isA<Function>()); }); test('Can instantiate RegSetKeyValue', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegSetKeyValue = advapi32.lookupFunction< Uint32 Function( IntPtr hKey, Pointer<Utf16> lpSubKey, Pointer<Utf16> lpValueName, Uint32 dwType, Pointer lpData, Uint32 cbData), int Function( int hKey, Pointer<Utf16> lpSubKey, Pointer<Utf16> lpValueName, int dwType, Pointer lpData, int cbData)>('RegSetKeyValueW'); expect(RegSetKeyValue, isA<Function>()); }); test('Can instantiate RegSetValue', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegSetValue = advapi32.lookupFunction< Uint32 Function(IntPtr hKey, Pointer<Utf16> lpSubKey, Uint32 dwType, Pointer<Utf16> lpData, Uint32 cbData), int Function(int hKey, Pointer<Utf16> lpSubKey, int dwType, Pointer<Utf16> lpData, int cbData)>('RegSetValueW'); expect(RegSetValue, isA<Function>()); }); test('Can instantiate RegSetValueEx', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegSetValueEx = advapi32.lookupFunction< Uint32 Function( IntPtr hKey, Pointer<Utf16> lpValueName, Uint32 Reserved, Uint32 dwType, Pointer<Uint8> lpData, Uint32 cbData), int Function(int hKey, Pointer<Utf16> lpValueName, int Reserved, int dwType, Pointer<Uint8> lpData, int cbData)>('RegSetValueExW'); expect(RegSetValueEx, isA<Function>()); }); test('Can instantiate RegUnLoadKey', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final RegUnLoadKey = advapi32.lookupFunction< Uint32 Function(IntPtr hKey, Pointer<Utf16> lpSubKey), int Function(int hKey, Pointer<Utf16> lpSubKey)>('RegUnLoadKeyW'); expect(RegUnLoadKey, isA<Function>()); }); test('Can instantiate SetThreadToken', () { final advapi32 = DynamicLibrary.open('advapi32.dll'); final SetThreadToken = advapi32.lookupFunction< Int32 Function(Pointer<IntPtr> Thread, IntPtr Token), int Function(Pointer<IntPtr> Thread, int Token)>('SetThreadToken'); expect(SetThreadToken, isA<Function>()); }); }); group('Test comctl32 functions', () { test('Can instantiate DefSubclassProc', () { final comctl32 = DynamicLibrary.open('comctl32.dll'); final DefSubclassProc = comctl32.lookupFunction< IntPtr Function( IntPtr hWnd, Uint32 uMsg, IntPtr wParam, IntPtr lParam), int Function( int hWnd, int uMsg, int wParam, int lParam)>('DefSubclassProc'); expect(DefSubclassProc, isA<Function>()); }); test('Can instantiate DrawStatusText', () { final comctl32 = DynamicLibrary.open('comctl32.dll'); final DrawStatusText = comctl32.lookupFunction< Void Function(IntPtr hDC, Pointer<RECT> lprc, Pointer<Utf16> pszText, Uint32 uFlags), void Function(int hDC, Pointer<RECT> lprc, Pointer<Utf16> pszText, int uFlags)>('DrawStatusTextW'); expect(DrawStatusText, isA<Function>()); }); test('Can instantiate InitCommonControlsEx', () { final comctl32 = DynamicLibrary.open('comctl32.dll'); final InitCommonControlsEx = comctl32.lookupFunction< Int32 Function(Pointer<INITCOMMONCONTROLSEX> picce), int Function( Pointer<INITCOMMONCONTROLSEX> picce)>('InitCommonControlsEx'); expect(InitCommonControlsEx, isA<Function>()); }); test('Can instantiate RemoveWindowSubclass', () { final comctl32 = DynamicLibrary.open('comctl32.dll'); final RemoveWindowSubclass = comctl32.lookupFunction< Int32 Function( IntPtr hWnd, Pointer<NativeFunction<SubclassProc>> pfnSubclass, IntPtr uIdSubclass), int Function( int hWnd, Pointer<NativeFunction<SubclassProc>> pfnSubclass, int uIdSubclass)>('RemoveWindowSubclass'); expect(RemoveWindowSubclass, isA<Function>()); }); test('Can instantiate SetWindowSubclass', () { final comctl32 = DynamicLibrary.open('comctl32.dll'); final SetWindowSubclass = comctl32.lookupFunction< Int32 Function( IntPtr hWnd, Pointer<NativeFunction<SubclassProc>> pfnSubclass, IntPtr uIdSubclass, IntPtr dwRefData), int Function( int hWnd, Pointer<NativeFunction<SubclassProc>> pfnSubclass, int uIdSubclass, int dwRefData)>('SetWindowSubclass'); expect(SetWindowSubclass, isA<Function>()); }); }); group('Test dxva2 functions', () { test('Can instantiate DestroyPhysicalMonitor', () { final dxva2 = DynamicLibrary.open('dxva2.dll'); final DestroyPhysicalMonitor = dxva2.lookupFunction< Int32 Function(IntPtr hMonitor), int Function(int hMonitor)>('DestroyPhysicalMonitor'); expect(DestroyPhysicalMonitor, isA<Function>()); }); test('Can instantiate DestroyPhysicalMonitors', () { final dxva2 = DynamicLibrary.open('dxva2.dll'); final DestroyPhysicalMonitors = dxva2.lookupFunction< Int32 Function(Uint32 dwPhysicalMonitorArraySize, Pointer<PHYSICAL_MONITOR> pPhysicalMonitorArray), int Function(int dwPhysicalMonitorArraySize, Pointer<PHYSICAL_MONITOR> pPhysicalMonitorArray)>( 'DestroyPhysicalMonitors'); expect(DestroyPhysicalMonitors, isA<Function>()); }); test('Can instantiate GetMonitorBrightness', () { final dxva2 = DynamicLibrary.open('dxva2.dll'); final GetMonitorBrightness = dxva2.lookupFunction< Int32 Function( IntPtr hMonitor, Pointer<Uint32> pdwMinimumBrightness, Pointer<Uint32> pdwCurrentBrightness, Pointer<Uint32> pdwMaximumBrightness), int Function( int hMonitor, Pointer<Uint32> pdwMinimumBrightness, Pointer<Uint32> pdwCurrentBrightness, Pointer<Uint32> pdwMaximumBrightness)>('GetMonitorBrightness'); expect(GetMonitorBrightness, isA<Function>()); }); test('Can instantiate GetMonitorCapabilities', () { final dxva2 = DynamicLibrary.open('dxva2.dll'); final GetMonitorCapabilities = dxva2.lookupFunction< Int32 Function( IntPtr hMonitor, Pointer<Uint32> pdwMonitorCapabilities, Pointer<Uint32> pdwSupportedColorTemperatures), int Function(int hMonitor, Pointer<Uint32> pdwMonitorCapabilities, Pointer<Uint32> pdwSupportedColorTemperatures)>( 'GetMonitorCapabilities'); expect(GetMonitorCapabilities, isA<Function>()); }); test('Can instantiate GetMonitorColorTemperature', () { final dxva2 = DynamicLibrary.open('dxva2.dll'); final GetMonitorColorTemperature = dxva2.lookupFunction< Int32 Function( IntPtr hMonitor, Pointer<Int32> pctCurrentColorTemperature), int Function( int hMonitor, Pointer<Int32> pctCurrentColorTemperature)>( 'GetMonitorColorTemperature'); expect(GetMonitorColorTemperature, isA<Function>()); }); test('Can instantiate GetMonitorContrast', () { final dxva2 = DynamicLibrary.open('dxva2.dll'); final GetMonitorContrast = dxva2.lookupFunction< Int32 Function( IntPtr hMonitor, Pointer<Uint32> pdwMinimumContrast, Pointer<Uint32> pdwCurrentContrast, Pointer<Uint32> pdwMaximumContrast), int Function( int hMonitor, Pointer<Uint32> pdwMinimumContrast, Pointer<Uint32> pdwCurrentContrast, Pointer<Uint32> pdwMaximumContrast)>('GetMonitorContrast'); expect(GetMonitorContrast, isA<Function>()); }); test('Can instantiate GetMonitorDisplayAreaPosition', () { final dxva2 = DynamicLibrary.open('dxva2.dll'); final GetMonitorDisplayAreaPosition = dxva2.lookupFunction< Int32 Function( IntPtr hMonitor, Int32 ptPositionType, Pointer<Uint32> pdwMinimumPosition, Pointer<Uint32> pdwCurrentPosition, Pointer<Uint32> pdwMaximumPosition), int Function( int hMonitor, int ptPositionType, Pointer<Uint32> pdwMinimumPosition, Pointer<Uint32> pdwCurrentPosition, Pointer<Uint32> pdwMaximumPosition)>( 'GetMonitorDisplayAreaPosition'); expect(GetMonitorDisplayAreaPosition, isA<Function>()); }); test('Can instantiate GetMonitorDisplayAreaSize', () { final dxva2 = DynamicLibrary.open('dxva2.dll'); final GetMonitorDisplayAreaSize = dxva2.lookupFunction< Int32 Function( IntPtr hMonitor, Int32 stSizeType, Pointer<Uint32> pdwMinimumWidthOrHeight, Pointer<Uint32> pdwCurrentWidthOrHeight, Pointer<Uint32> pdwMaximumWidthOrHeight), int Function( int hMonitor, int stSizeType, Pointer<Uint32> pdwMinimumWidthOrHeight, Pointer<Uint32> pdwCurrentWidthOrHeight, Pointer<Uint32> pdwMaximumWidthOrHeight)>( 'GetMonitorDisplayAreaSize'); expect(GetMonitorDisplayAreaSize, isA<Function>()); }); test('Can instantiate GetMonitorRedGreenOrBlueDrive', () { final dxva2 = DynamicLibrary.open('dxva2.dll'); final GetMonitorRedGreenOrBlueDrive = dxva2.lookupFunction< Int32 Function( IntPtr hMonitor, Int32 dtDriveType, Pointer<Uint32> pdwMinimumDrive, Pointer<Uint32> pdwCurrentDrive, Pointer<Uint32> pdwMaximumDrive), int Function( int hMonitor, int dtDriveType, Pointer<Uint32> pdwMinimumDrive, Pointer<Uint32> pdwCurrentDrive, Pointer<Uint32> pdwMaximumDrive)>( 'GetMonitorRedGreenOrBlueDrive'); expect(GetMonitorRedGreenOrBlueDrive, isA<Function>()); }); test('Can instantiate GetMonitorRedGreenOrBlueGain', () { final dxva2 = DynamicLibrary.open('dxva2.dll'); final GetMonitorRedGreenOrBlueGain = dxva2.lookupFunction< Int32 Function( IntPtr hMonitor, Int32 gtGainType, Pointer<Uint32> pdwMinimumGain, Pointer<Uint32> pdwCurrentGain, Pointer<Uint32> pdwMaximumGain), int Function( int hMonitor, int gtGainType, Pointer<Uint32> pdwMinimumGain, Pointer<Uint32> pdwCurrentGain, Pointer<Uint32> pdwMaximumGain)>('GetMonitorRedGreenOrBlueGain'); expect(GetMonitorRedGreenOrBlueGain, isA<Function>()); }); test('Can instantiate GetMonitorTechnologyType', () { final dxva2 = DynamicLibrary.open('dxva2.dll'); final GetMonitorTechnologyType = dxva2.lookupFunction< Int32 Function( IntPtr hMonitor, Pointer<Int32> pdtyDisplayTechnologyType), int Function( int hMonitor, Pointer<Int32> pdtyDisplayTechnologyType)>( 'GetMonitorTechnologyType'); expect(GetMonitorTechnologyType, isA<Function>()); }); test('Can instantiate GetNumberOfPhysicalMonitorsFromHMONITOR', () { final dxva2 = DynamicLibrary.open('dxva2.dll'); final GetNumberOfPhysicalMonitorsFromHMONITOR = dxva2.lookupFunction< Int32 Function( IntPtr hMonitor, Pointer<Uint32> pdwNumberOfPhysicalMonitors), int Function( int hMonitor, Pointer<Uint32> pdwNumberOfPhysicalMonitors)>( 'GetNumberOfPhysicalMonitorsFromHMONITOR'); expect(GetNumberOfPhysicalMonitorsFromHMONITOR, isA<Function>()); }); test('Can instantiate GetPhysicalMonitorsFromHMONITOR', () { final dxva2 = DynamicLibrary.open('dxva2.dll'); final GetPhysicalMonitorsFromHMONITOR = dxva2.lookupFunction< Int32 Function(IntPtr hMonitor, Uint32 dwPhysicalMonitorArraySize, Pointer<PHYSICAL_MONITOR> pPhysicalMonitorArray), int Function(int hMonitor, int dwPhysicalMonitorArraySize, Pointer<PHYSICAL_MONITOR> pPhysicalMonitorArray)>( 'GetPhysicalMonitorsFromHMONITOR'); expect(GetPhysicalMonitorsFromHMONITOR, isA<Function>()); }); test('Can instantiate SaveCurrentMonitorSettings', () { final dxva2 = DynamicLibrary.open('dxva2.dll'); final SaveCurrentMonitorSettings = dxva2.lookupFunction< Int32 Function(IntPtr hMonitor), int Function(int hMonitor)>('SaveCurrentMonitorSettings'); expect(SaveCurrentMonitorSettings, isA<Function>()); }); test('Can instantiate SetMonitorBrightness', () { final dxva2 = DynamicLibrary.open('dxva2.dll'); final SetMonitorBrightness = dxva2.lookupFunction< Int32 Function(IntPtr hMonitor, Uint32 dwNewBrightness), int Function( int hMonitor, int dwNewBrightness)>('SetMonitorBrightness'); expect(SetMonitorBrightness, isA<Function>()); }); test('Can instantiate SetMonitorColorTemperature', () { final dxva2 = DynamicLibrary.open('dxva2.dll'); final SetMonitorColorTemperature = dxva2.lookupFunction< Int32 Function(IntPtr hMonitor, Int32 ctCurrentColorTemperature), int Function(int hMonitor, int ctCurrentColorTemperature)>('SetMonitorColorTemperature'); expect(SetMonitorColorTemperature, isA<Function>()); }); test('Can instantiate SetMonitorContrast', () { final dxva2 = DynamicLibrary.open('dxva2.dll'); final SetMonitorContrast = dxva2.lookupFunction< Int32 Function(IntPtr hMonitor, Uint32 dwNewContrast), int Function(int hMonitor, int dwNewContrast)>('SetMonitorContrast'); expect(SetMonitorContrast, isA<Function>()); }); test('Can instantiate SetMonitorDisplayAreaPosition', () { final dxva2 = DynamicLibrary.open('dxva2.dll'); final SetMonitorDisplayAreaPosition = dxva2.lookupFunction< Int32 Function( IntPtr hMonitor, Int32 ptPositionType, Uint32 dwNewPosition), int Function(int hMonitor, int ptPositionType, int dwNewPosition)>('SetMonitorDisplayAreaPosition'); expect(SetMonitorDisplayAreaPosition, isA<Function>()); }); test('Can instantiate SetMonitorDisplayAreaSize', () { final dxva2 = DynamicLibrary.open('dxva2.dll'); final SetMonitorDisplayAreaSize = dxva2.lookupFunction< Int32 Function(IntPtr hMonitor, Int32 stSizeType, Uint32 dwNewDisplayAreaWidthOrHeight), int Function(int hMonitor, int stSizeType, int dwNewDisplayAreaWidthOrHeight)>('SetMonitorDisplayAreaSize'); expect(SetMonitorDisplayAreaSize, isA<Function>()); }); test('Can instantiate SetMonitorRedGreenOrBlueDrive', () { final dxva2 = DynamicLibrary.open('dxva2.dll'); final SetMonitorRedGreenOrBlueDrive = dxva2.lookupFunction< Int32 Function(IntPtr hMonitor, Int32 dtDriveType, Uint32 dwNewDrive), int Function(int hMonitor, int dtDriveType, int dwNewDrive)>('SetMonitorRedGreenOrBlueDrive'); expect(SetMonitorRedGreenOrBlueDrive, isA<Function>()); }); test('Can instantiate SetMonitorRedGreenOrBlueGain', () { final dxva2 = DynamicLibrary.open('dxva2.dll'); final SetMonitorRedGreenOrBlueGain = dxva2.lookupFunction< Int32 Function(IntPtr hMonitor, Int32 gtGainType, Uint32 dwNewGain), int Function(int hMonitor, int gtGainType, int dwNewGain)>('SetMonitorRedGreenOrBlueGain'); expect(SetMonitorRedGreenOrBlueGain, isA<Function>()); }); }); group('Test oleaut32 functions', () { test('Can instantiate DosDateTimeToVariantTime', () { final oleaut32 = DynamicLibrary.open('oleaut32.dll'); final DosDateTimeToVariantTime = oleaut32.lookupFunction< Int32 Function( Uint16 wDosDate, Uint16 wDosTime, Pointer<Double> pvtime), int Function(int wDosDate, int wDosTime, Pointer<Double> pvtime)>('DosDateTimeToVariantTime'); expect(DosDateTimeToVariantTime, isA<Function>()); }); test('Can instantiate GetActiveObject', () { final oleaut32 = DynamicLibrary.open('oleaut32.dll'); final GetActiveObject = oleaut32.lookupFunction< Int32 Function(Pointer<GUID> rclsid, Pointer pvReserved, Pointer<Pointer<COMObject>> ppunk), int Function(Pointer<GUID> rclsid, Pointer pvReserved, Pointer<Pointer<COMObject>> ppunk)>('GetActiveObject'); expect(GetActiveObject, isA<Function>()); }); test('Can instantiate SysAllocString', () { final oleaut32 = DynamicLibrary.open('oleaut32.dll'); final SysAllocString = oleaut32.lookupFunction< Pointer<Utf16> Function(Pointer<Utf16> psz), Pointer<Utf16> Function(Pointer<Utf16> psz)>('SysAllocString'); expect(SysAllocString, isA<Function>()); }); test('Can instantiate SysAllocStringByteLen', () { final oleaut32 = DynamicLibrary.open('oleaut32.dll'); final SysAllocStringByteLen = oleaut32.lookupFunction< Pointer<Utf16> Function(Pointer<Utf8> psz, Uint32 len), Pointer<Utf16> Function( Pointer<Utf8> psz, int len)>('SysAllocStringByteLen'); expect(SysAllocStringByteLen, isA<Function>()); }); test('Can instantiate SysAllocStringLen', () { final oleaut32 = DynamicLibrary.open('oleaut32.dll'); final SysAllocStringLen = oleaut32.lookupFunction< Pointer<Utf16> Function(Pointer<Utf16> strIn, Uint32 ui), Pointer<Utf16> Function( Pointer<Utf16> strIn, int ui)>('SysAllocStringLen'); expect(SysAllocStringLen, isA<Function>()); }); test('Can instantiate SysFreeString', () { final oleaut32 = DynamicLibrary.open('oleaut32.dll'); final SysFreeString = oleaut32.lookupFunction< Void Function(Pointer<Utf16> bstrString), void Function(Pointer<Utf16> bstrString)>('SysFreeString'); expect(SysFreeString, isA<Function>()); }); test('Can instantiate SysReAllocString', () { final oleaut32 = DynamicLibrary.open('oleaut32.dll'); final SysReAllocString = oleaut32.lookupFunction< Int32 Function(Pointer<Pointer<Utf16>> pbstr, Pointer<Utf16> psz), int Function(Pointer<Pointer<Utf16>> pbstr, Pointer<Utf16> psz)>('SysReAllocString'); expect(SysReAllocString, isA<Function>()); }); test('Can instantiate SysReAllocStringLen', () { final oleaut32 = DynamicLibrary.open('oleaut32.dll'); final SysReAllocStringLen = oleaut32.lookupFunction< Int32 Function( Pointer<Pointer<Utf16>> pbstr, Pointer<Utf16> psz, Uint32 len), int Function(Pointer<Pointer<Utf16>> pbstr, Pointer<Utf16> psz, int len)>('SysReAllocStringLen'); expect(SysReAllocStringLen, isA<Function>()); }); test('Can instantiate SysReleaseString', () { final oleaut32 = DynamicLibrary.open('oleaut32.dll'); final SysReleaseString = oleaut32.lookupFunction< Void Function(Pointer<Utf16> bstrString), void Function(Pointer<Utf16> bstrString)>('SysReleaseString'); expect(SysReleaseString, isA<Function>()); }); test('Can instantiate SysStringByteLen', () { final oleaut32 = DynamicLibrary.open('oleaut32.dll'); final SysStringByteLen = oleaut32.lookupFunction< Uint32 Function(Pointer<Utf16> bstr), int Function(Pointer<Utf16> bstr)>('SysStringByteLen'); expect(SysStringByteLen, isA<Function>()); }); test('Can instantiate SysStringLen', () { final oleaut32 = DynamicLibrary.open('oleaut32.dll'); final SysStringLen = oleaut32.lookupFunction< Uint32 Function(Pointer<Utf16> pbstr), int Function(Pointer<Utf16> pbstr)>('SysStringLen'); expect(SysStringLen, isA<Function>()); }); test('Can instantiate VariantChangeType', () { final oleaut32 = DynamicLibrary.open('oleaut32.dll'); final VariantChangeType = oleaut32.lookupFunction< Int32 Function(Pointer<VARIANT> pvargDest, Pointer<VARIANT> pvarSrc, Uint16 wFlags, Uint16 vt), int Function(Pointer<VARIANT> pvargDest, Pointer<VARIANT> pvarSrc, int wFlags, int vt)>('VariantChangeType'); expect(VariantChangeType, isA<Function>()); }); test('Can instantiate VariantClear', () { final oleaut32 = DynamicLibrary.open('oleaut32.dll'); final VariantClear = oleaut32.lookupFunction< Int32 Function(Pointer<VARIANT> pvarg), int Function(Pointer<VARIANT> pvarg)>('VariantClear'); expect(VariantClear, isA<Function>()); }); test('Can instantiate VariantCopy', () { final oleaut32 = DynamicLibrary.open('oleaut32.dll'); final VariantCopy = oleaut32.lookupFunction< Int32 Function(Pointer<VARIANT> pvargDest, Pointer<VARIANT> pvargSrc), int Function(Pointer<VARIANT> pvargDest, Pointer<VARIANT> pvargSrc)>('VariantCopy'); expect(VariantCopy, isA<Function>()); }); test('Can instantiate VariantInit', () { final oleaut32 = DynamicLibrary.open('oleaut32.dll'); final VariantInit = oleaut32.lookupFunction< Void Function(Pointer<VARIANT> pvarg), void Function(Pointer<VARIANT> pvarg)>('VariantInit'); expect(VariantInit, isA<Function>()); }); test('Can instantiate VariantTimeToDosDateTime', () { final oleaut32 = DynamicLibrary.open('oleaut32.dll'); final VariantTimeToDosDateTime = oleaut32.lookupFunction< Int32 Function(Double vtime, Pointer<Uint16> pwDosDate, Pointer<Uint16> pwDosTime), int Function(double vtime, Pointer<Uint16> pwDosDate, Pointer<Uint16> pwDosTime)>('VariantTimeToDosDateTime'); expect(VariantTimeToDosDateTime, isA<Function>()); }); test('Can instantiate VariantTimeToSystemTime', () { final oleaut32 = DynamicLibrary.open('oleaut32.dll'); final VariantTimeToSystemTime = oleaut32.lookupFunction< Int32 Function(Double vtime, Pointer<SYSTEMTIME> lpSystemTime), int Function(double vtime, Pointer<SYSTEMTIME> lpSystemTime)>('VariantTimeToSystemTime'); expect(VariantTimeToSystemTime, isA<Function>()); }); }); group('Test dwmapi functions', () { test('Can instantiate DwmEnableBlurBehindWindow', () { final dwmapi = DynamicLibrary.open('dwmapi.dll'); final DwmEnableBlurBehindWindow = dwmapi.lookupFunction< Int32 Function(IntPtr hWnd, Pointer<DWM_BLURBEHIND> pBlurBehind), int Function(int hWnd, Pointer<DWM_BLURBEHIND> pBlurBehind)>( 'DwmEnableBlurBehindWindow'); expect(DwmEnableBlurBehindWindow, isA<Function>()); }); test('Can instantiate DwmEnableMMCSS', () { final dwmapi = DynamicLibrary.open('dwmapi.dll'); final DwmEnableMMCSS = dwmapi.lookupFunction< Int32 Function(Int32 fEnableMMCSS), int Function(int fEnableMMCSS)>('DwmEnableMMCSS'); expect(DwmEnableMMCSS, isA<Function>()); }); test('Can instantiate DwmExtendFrameIntoClientArea', () { final dwmapi = DynamicLibrary.open('dwmapi.dll'); final DwmExtendFrameIntoClientArea = dwmapi.lookupFunction< Int32 Function(IntPtr hWnd, Pointer<MARGINS> pMarInset), int Function(int hWnd, Pointer<MARGINS> pMarInset)>('DwmExtendFrameIntoClientArea'); expect(DwmExtendFrameIntoClientArea, isA<Function>()); }); test('Can instantiate DwmFlush', () { final dwmapi = DynamicLibrary.open('dwmapi.dll'); final DwmFlush = dwmapi.lookupFunction<Int32 Function(), int Function()>('DwmFlush'); expect(DwmFlush, isA<Function>()); }); test('Can instantiate DwmGetColorizationColor', () { final dwmapi = DynamicLibrary.open('dwmapi.dll'); final DwmGetColorizationColor = dwmapi.lookupFunction< Int32 Function( Pointer<Uint32> pcrColorization, Pointer<Int32> pfOpaqueBlend), int Function(Pointer<Uint32> pcrColorization, Pointer<Int32> pfOpaqueBlend)>('DwmGetColorizationColor'); expect(DwmGetColorizationColor, isA<Function>()); }); test('Can instantiate DwmGetTransportAttributes', () { final dwmapi = DynamicLibrary.open('dwmapi.dll'); final DwmGetTransportAttributes = dwmapi.lookupFunction< Int32 Function(Pointer<Int32> pfIsRemoting, Pointer<Int32> pfIsConnected, Pointer<Uint32> pDwGeneration), int Function( Pointer<Int32> pfIsRemoting, Pointer<Int32> pfIsConnected, Pointer<Uint32> pDwGeneration)>('DwmGetTransportAttributes'); expect(DwmGetTransportAttributes, isA<Function>()); }); test('Can instantiate DwmGetWindowAttribute', () { final dwmapi = DynamicLibrary.open('dwmapi.dll'); final DwmGetWindowAttribute = dwmapi.lookupFunction< Int32 Function(IntPtr hwnd, Int32 dwAttribute, Pointer pvAttribute, Uint32 cbAttribute), int Function(int hwnd, int dwAttribute, Pointer pvAttribute, int cbAttribute)>('DwmGetWindowAttribute'); expect(DwmGetWindowAttribute, isA<Function>()); }); test('Can instantiate DwmInvalidateIconicBitmaps', () { final dwmapi = DynamicLibrary.open('dwmapi.dll'); final DwmInvalidateIconicBitmaps = dwmapi.lookupFunction< Int32 Function(IntPtr hwnd), int Function(int hwnd)>('DwmInvalidateIconicBitmaps'); expect(DwmInvalidateIconicBitmaps, isA<Function>()); }); if (windowsBuildNumber >= 9200) { test('Can instantiate DwmRenderGesture', () { final dwmapi = DynamicLibrary.open('dwmapi.dll'); final DwmRenderGesture = dwmapi.lookupFunction< Int32 Function(Int32 gt, Uint32 cContacts, Pointer<Uint32> pdwPointerID, Pointer<POINT> pPoints), int Function(int gt, int cContacts, Pointer<Uint32> pdwPointerID, Pointer<POINT> pPoints)>('DwmRenderGesture'); expect(DwmRenderGesture, isA<Function>()); }); } test('Can instantiate DwmSetWindowAttribute', () { final dwmapi = DynamicLibrary.open('dwmapi.dll'); final DwmSetWindowAttribute = dwmapi.lookupFunction< Int32 Function(IntPtr hwnd, Int32 dwAttribute, Pointer pvAttribute, Uint32 cbAttribute), int Function(int hwnd, int dwAttribute, Pointer pvAttribute, int cbAttribute)>('DwmSetWindowAttribute'); expect(DwmSetWindowAttribute, isA<Function>()); }); if (windowsBuildNumber >= 9200) { test('Can instantiate DwmShowContact', () { final dwmapi = DynamicLibrary.open('dwmapi.dll'); final DwmShowContact = dwmapi.lookupFunction< Int32 Function(Uint32 dwPointerID, Uint32 eShowContact), int Function(int dwPointerID, int eShowContact)>('DwmShowContact'); expect(DwmShowContact, isA<Function>()); }); } }); group('Test shcore functions', () { if (windowsBuildNumber >= 9600) { test('Can instantiate GetDpiForMonitor', () { final shcore = DynamicLibrary.open('shcore.dll'); final GetDpiForMonitor = shcore.lookupFunction< Int32 Function(IntPtr hmonitor, Int32 dpiType, Pointer<Uint32> dpiX, Pointer<Uint32> dpiY), int Function(int hmonitor, int dpiType, Pointer<Uint32> dpiX, Pointer<Uint32> dpiY)>('GetDpiForMonitor'); expect(GetDpiForMonitor, isA<Function>()); }); } if (windowsBuildNumber >= 9600) { test('Can instantiate GetProcessDpiAwareness', () { final shcore = DynamicLibrary.open('shcore.dll'); final GetProcessDpiAwareness = shcore.lookupFunction< Int32 Function(IntPtr hprocess, Pointer<Int32> value), int Function( int hprocess, Pointer<Int32> value)>('GetProcessDpiAwareness'); expect(GetProcessDpiAwareness, isA<Function>()); }); } if (windowsBuildNumber >= 9600) { test('Can instantiate GetScaleFactorForMonitor', () { final shcore = DynamicLibrary.open('shcore.dll'); final GetScaleFactorForMonitor = shcore.lookupFunction< Int32 Function(IntPtr hMon, Pointer<Int32> pScale), int Function( int hMon, Pointer<Int32> pScale)>('GetScaleFactorForMonitor'); expect(GetScaleFactorForMonitor, isA<Function>()); }); } if (windowsBuildNumber >= 9600) { test('Can instantiate SetProcessDpiAwareness', () { final shcore = DynamicLibrary.open('shcore.dll'); final SetProcessDpiAwareness = shcore.lookupFunction< Int32 Function(Int32 value), int Function(int value)>('SetProcessDpiAwareness'); expect(SetProcessDpiAwareness, isA<Function>()); }); } }); group('Test version functions', () { test('Can instantiate GetFileVersionInfo', () { final version = DynamicLibrary.open('version.dll'); final GetFileVersionInfo = version.lookupFunction< Int32 Function(Pointer<Utf16> lptstrFilename, Uint32 dwHandle, Uint32 dwLen, Pointer lpData), int Function(Pointer<Utf16> lptstrFilename, int dwHandle, int dwLen, Pointer lpData)>('GetFileVersionInfoW'); expect(GetFileVersionInfo, isA<Function>()); }); test('Can instantiate GetFileVersionInfoEx', () { final version = DynamicLibrary.open('version.dll'); final GetFileVersionInfoEx = version.lookupFunction< Int32 Function(Uint32 dwFlags, Pointer<Utf16> lpwstrFilename, Uint32 dwHandle, Uint32 dwLen, Pointer lpData), int Function(int dwFlags, Pointer<Utf16> lpwstrFilename, int dwHandle, int dwLen, Pointer lpData)>('GetFileVersionInfoExW'); expect(GetFileVersionInfoEx, isA<Function>()); }); test('Can instantiate GetFileVersionInfoSize', () { final version = DynamicLibrary.open('version.dll'); final GetFileVersionInfoSize = version.lookupFunction< Uint32 Function( Pointer<Utf16> lptstrFilename, Pointer<Uint32> lpdwHandle), int Function(Pointer<Utf16> lptstrFilename, Pointer<Uint32> lpdwHandle)>('GetFileVersionInfoSizeW'); expect(GetFileVersionInfoSize, isA<Function>()); }); test('Can instantiate GetFileVersionInfoSizeEx', () { final version = DynamicLibrary.open('version.dll'); final GetFileVersionInfoSizeEx = version.lookupFunction< Uint32 Function(Uint32 dwFlags, Pointer<Utf16> lpwstrFilename, Pointer<Uint32> lpdwHandle), int Function(int dwFlags, Pointer<Utf16> lpwstrFilename, Pointer<Uint32> lpdwHandle)>('GetFileVersionInfoSizeExW'); expect(GetFileVersionInfoSizeEx, isA<Function>()); }); test('Can instantiate VerFindFile', () { final version = DynamicLibrary.open('version.dll'); final VerFindFile = version.lookupFunction< Uint32 Function( Uint32 uFlags, Pointer<Utf16> szFileName, Pointer<Utf16> szWinDir, Pointer<Utf16> szAppDir, Pointer<Utf16> szCurDir, Pointer<Uint32> puCurDirLen, Pointer<Utf16> szDestDir, Pointer<Uint32> puDestDirLen), int Function( int uFlags, Pointer<Utf16> szFileName, Pointer<Utf16> szWinDir, Pointer<Utf16> szAppDir, Pointer<Utf16> szCurDir, Pointer<Uint32> puCurDirLen, Pointer<Utf16> szDestDir, Pointer<Uint32> puDestDirLen)>('VerFindFileW'); expect(VerFindFile, isA<Function>()); }); test('Can instantiate VerInstallFile', () { final version = DynamicLibrary.open('version.dll'); final VerInstallFile = version.lookupFunction< Uint32 Function( Uint32 uFlags, Pointer<Utf16> szSrcFileName, Pointer<Utf16> szDestFileName, Pointer<Utf16> szSrcDir, Pointer<Utf16> szDestDir, Pointer<Utf16> szCurDir, Pointer<Utf16> szTmpFile, Pointer<Uint32> puTmpFileLen), int Function( int uFlags, Pointer<Utf16> szSrcFileName, Pointer<Utf16> szDestFileName, Pointer<Utf16> szSrcDir, Pointer<Utf16> szDestDir, Pointer<Utf16> szCurDir, Pointer<Utf16> szTmpFile, Pointer<Uint32> puTmpFileLen)>('VerInstallFileW'); expect(VerInstallFile, isA<Function>()); }); test('Can instantiate VerQueryValue', () { final version = DynamicLibrary.open('version.dll'); final VerQueryValue = version.lookupFunction< Int32 Function(Pointer pBlock, Pointer<Utf16> lpSubBlock, Pointer<Pointer> lplpBuffer, Pointer<Uint32> puLen), int Function( Pointer pBlock, Pointer<Utf16> lpSubBlock, Pointer<Pointer> lplpBuffer, Pointer<Uint32> puLen)>('VerQueryValueW'); expect(VerQueryValue, isA<Function>()); }); }); group('Test magnification functions', () { test('Can instantiate MagGetColorEffect', () { final magnification = DynamicLibrary.open('magnification.dll'); final MagGetColorEffect = magnification.lookupFunction< Int32 Function(IntPtr hwnd, Pointer<MAGCOLOREFFECT> pEffect), int Function( int hwnd, Pointer<MAGCOLOREFFECT> pEffect)>('MagGetColorEffect'); expect(MagGetColorEffect, isA<Function>()); }); test('Can instantiate MagGetFullscreenColorEffect', () { final magnification = DynamicLibrary.open('magnification.dll'); final MagGetFullscreenColorEffect = magnification.lookupFunction< Int32 Function(Pointer<MAGCOLOREFFECT> pEffect), int Function( Pointer<MAGCOLOREFFECT> pEffect)>('MagGetFullscreenColorEffect'); expect(MagGetFullscreenColorEffect, isA<Function>()); }); test('Can instantiate MagGetFullscreenTransform', () { final magnification = DynamicLibrary.open('magnification.dll'); final MagGetFullscreenTransform = magnification.lookupFunction< Int32 Function(Pointer<Float> pMagLevel, Pointer<Int32> pxOffset, Pointer<Int32> pyOffset), int Function(Pointer<Float> pMagLevel, Pointer<Int32> pxOffset, Pointer<Int32> pyOffset)>('MagGetFullscreenTransform'); expect(MagGetFullscreenTransform, isA<Function>()); }); test('Can instantiate MagGetImageScalingCallback', () { final magnification = DynamicLibrary.open('magnification.dll'); final MagGetImageScalingCallback = magnification.lookupFunction< Pointer<NativeFunction<MagImageScalingCallback>> Function( IntPtr hwnd), Pointer<NativeFunction<MagImageScalingCallback>> Function( int hwnd)>('MagGetImageScalingCallback'); expect(MagGetImageScalingCallback, isA<Function>()); }); test('Can instantiate MagGetInputTransform', () { final magnification = DynamicLibrary.open('magnification.dll'); final MagGetInputTransform = magnification.lookupFunction< Int32 Function(Pointer<Int32> pfEnabled, Pointer<RECT> pRectSource, Pointer<RECT> pRectDest), int Function(Pointer<Int32> pfEnabled, Pointer<RECT> pRectSource, Pointer<RECT> pRectDest)>('MagGetInputTransform'); expect(MagGetInputTransform, isA<Function>()); }); test('Can instantiate MagGetWindowFilterList', () { final magnification = DynamicLibrary.open('magnification.dll'); final MagGetWindowFilterList = magnification.lookupFunction< Int32 Function(IntPtr hwnd, Pointer<Uint32> pdwFilterMode, Int32 count, Pointer<IntPtr> pHWND), int Function(int hwnd, Pointer<Uint32> pdwFilterMode, int count, Pointer<IntPtr> pHWND)>('MagGetWindowFilterList'); expect(MagGetWindowFilterList, isA<Function>()); }); test('Can instantiate MagGetWindowSource', () { final magnification = DynamicLibrary.open('magnification.dll'); final MagGetWindowSource = magnification.lookupFunction< Int32 Function(IntPtr hwnd, Pointer<RECT> pRect), int Function(int hwnd, Pointer<RECT> pRect)>('MagGetWindowSource'); expect(MagGetWindowSource, isA<Function>()); }); test('Can instantiate MagGetWindowTransform', () { final magnification = DynamicLibrary.open('magnification.dll'); final MagGetWindowTransform = magnification.lookupFunction< Int32 Function(IntPtr hwnd, Pointer<MAGTRANSFORM> pTransform), int Function(int hwnd, Pointer<MAGTRANSFORM> pTransform)>('MagGetWindowTransform'); expect(MagGetWindowTransform, isA<Function>()); }); test('Can instantiate MagInitialize', () { final magnification = DynamicLibrary.open('magnification.dll'); final MagInitialize = magnification .lookupFunction<Int32 Function(), int Function()>('MagInitialize'); expect(MagInitialize, isA<Function>()); }); test('Can instantiate MagSetColorEffect', () { final magnification = DynamicLibrary.open('magnification.dll'); final MagSetColorEffect = magnification.lookupFunction< Int32 Function(IntPtr hwnd, Pointer<MAGCOLOREFFECT> pEffect), int Function( int hwnd, Pointer<MAGCOLOREFFECT> pEffect)>('MagSetColorEffect'); expect(MagSetColorEffect, isA<Function>()); }); test('Can instantiate MagSetFullscreenColorEffect', () { final magnification = DynamicLibrary.open('magnification.dll'); final MagSetFullscreenColorEffect = magnification.lookupFunction< Int32 Function(Pointer<MAGCOLOREFFECT> pEffect), int Function( Pointer<MAGCOLOREFFECT> pEffect)>('MagSetFullscreenColorEffect'); expect(MagSetFullscreenColorEffect, isA<Function>()); }); test('Can instantiate MagSetFullscreenTransform', () { final magnification = DynamicLibrary.open('magnification.dll'); final MagSetFullscreenTransform = magnification.lookupFunction< Int32 Function(Float magLevel, Int32 xOffset, Int32 yOffset), int Function(double magLevel, int xOffset, int yOffset)>('MagSetFullscreenTransform'); expect(MagSetFullscreenTransform, isA<Function>()); }); test('Can instantiate MagSetImageScalingCallback', () { final magnification = DynamicLibrary.open('magnification.dll'); final MagSetImageScalingCallback = magnification.lookupFunction< Int32 Function(IntPtr hwnd, Pointer<NativeFunction<MagImageScalingCallback>> callback), int Function(int hwnd, Pointer<NativeFunction<MagImageScalingCallback>> callback)>( 'MagSetImageScalingCallback'); expect(MagSetImageScalingCallback, isA<Function>()); }); test('Can instantiate MagSetInputTransform', () { final magnification = DynamicLibrary.open('magnification.dll'); final MagSetInputTransform = magnification.lookupFunction< Int32 Function(Int32 fEnabled, Pointer<RECT> pRectSource, Pointer<RECT> pRectDest), int Function(int fEnabled, Pointer<RECT> pRectSource, Pointer<RECT> pRectDest)>('MagSetInputTransform'); expect(MagSetInputTransform, isA<Function>()); }); test('Can instantiate MagSetWindowFilterList', () { final magnification = DynamicLibrary.open('magnification.dll'); final MagSetWindowFilterList = magnification.lookupFunction< Int32 Function(IntPtr hwnd, Uint32 dwFilterMode, Int32 count, Pointer<IntPtr> pHWND), int Function(int hwnd, int dwFilterMode, int count, Pointer<IntPtr> pHWND)>('MagSetWindowFilterList'); expect(MagSetWindowFilterList, isA<Function>()); }); test('Can instantiate MagSetWindowSource', () { final magnification = DynamicLibrary.open('magnification.dll'); final MagSetWindowSource = magnification.lookupFunction< Int32 Function(IntPtr hwnd, RECT rect), int Function(int hwnd, RECT rect)>('MagSetWindowSource'); expect(MagSetWindowSource, isA<Function>()); }); test('Can instantiate MagSetWindowTransform', () { final magnification = DynamicLibrary.open('magnification.dll'); final MagSetWindowTransform = magnification.lookupFunction< Int32 Function(IntPtr hwnd, Pointer<MAGTRANSFORM> pTransform), int Function(int hwnd, Pointer<MAGTRANSFORM> pTransform)>('MagSetWindowTransform'); expect(MagSetWindowTransform, isA<Function>()); }); test('Can instantiate MagShowSystemCursor', () { final magnification = DynamicLibrary.open('magnification.dll'); final MagShowSystemCursor = magnification.lookupFunction< Int32 Function(Int32 fShowCursor), int Function(int fShowCursor)>('MagShowSystemCursor'); expect(MagShowSystemCursor, isA<Function>()); }); test('Can instantiate MagUninitialize', () { final magnification = DynamicLibrary.open('magnification.dll'); final MagUninitialize = magnification .lookupFunction<Int32 Function(), int Function()>('MagUninitialize'); expect(MagUninitialize, isA<Function>()); }); }); group('Test winmm functions', () { test('Can instantiate mciGetDeviceID', () { final winmm = DynamicLibrary.open('winmm.dll'); final mciGetDeviceID = winmm.lookupFunction< Uint32 Function(Pointer<Utf16> pszDevice), int Function(Pointer<Utf16> pszDevice)>('mciGetDeviceIDW'); expect(mciGetDeviceID, isA<Function>()); }); test('Can instantiate mciGetDeviceIDFromElementID', () { final winmm = DynamicLibrary.open('winmm.dll'); final mciGetDeviceIDFromElementID = winmm.lookupFunction< Uint32 Function(Uint32 dwElementID, Pointer<Utf16> lpstrType), int Function(int dwElementID, Pointer<Utf16> lpstrType)>('mciGetDeviceIDFromElementIDW'); expect(mciGetDeviceIDFromElementID, isA<Function>()); }); test('Can instantiate mciGetErrorString', () { final winmm = DynamicLibrary.open('winmm.dll'); final mciGetErrorString = winmm.lookupFunction< Int32 Function(Uint32 mcierr, Pointer<Utf16> pszText, Uint32 cchText), int Function(int mcierr, Pointer<Utf16> pszText, int cchText)>('mciGetErrorStringW'); expect(mciGetErrorString, isA<Function>()); }); test('Can instantiate mciSendCommand', () { final winmm = DynamicLibrary.open('winmm.dll'); final mciSendCommand = winmm.lookupFunction< Uint32 Function( Uint32 mciId, Uint32 uMsg, IntPtr dwParam1, IntPtr dwParam2), int Function(int mciId, int uMsg, int dwParam1, int dwParam2)>('mciSendCommandW'); expect(mciSendCommand, isA<Function>()); }); test('Can instantiate mciSendString', () { final winmm = DynamicLibrary.open('winmm.dll'); final mciSendString = winmm.lookupFunction< Uint32 Function( Pointer<Utf16> lpstrCommand, Pointer<Utf16> lpstrReturnString, Uint32 uReturnLength, IntPtr hwndCallback), int Function( Pointer<Utf16> lpstrCommand, Pointer<Utf16> lpstrReturnString, int uReturnLength, int hwndCallback)>('mciSendStringW'); expect(mciSendString, isA<Function>()); }); test('Can instantiate midiConnect', () { final winmm = DynamicLibrary.open('winmm.dll'); final midiConnect = winmm.lookupFunction< Uint32 Function(IntPtr hmi, IntPtr hmo, Pointer pReserved), int Function(int hmi, int hmo, Pointer pReserved)>('midiConnect'); expect(midiConnect, isA<Function>()); }); test('Can instantiate midiDisconnect', () { final winmm = DynamicLibrary.open('winmm.dll'); final midiDisconnect = winmm.lookupFunction< Uint32 Function(IntPtr hmi, IntPtr hmo, Pointer pReserved), int Function(int hmi, int hmo, Pointer pReserved)>('midiDisconnect'); expect(midiDisconnect, isA<Function>()); }); test('Can instantiate midiInClose', () { final winmm = DynamicLibrary.open('winmm.dll'); final midiInClose = winmm.lookupFunction<Uint32 Function(IntPtr hmi), int Function(int hmi)>('midiInClose'); expect(midiInClose, isA<Function>()); }); test('Can instantiate midiInGetDevCaps', () { final winmm = DynamicLibrary.open('winmm.dll'); final midiInGetDevCaps = winmm.lookupFunction< Uint32 Function( IntPtr uDeviceID, Pointer<MIDIINCAPS> pmic, Uint32 cbmic), int Function(int uDeviceID, Pointer<MIDIINCAPS> pmic, int cbmic)>('midiInGetDevCapsW'); expect(midiInGetDevCaps, isA<Function>()); }); test('Can instantiate midiInGetErrorText', () { final winmm = DynamicLibrary.open('winmm.dll'); final midiInGetErrorText = winmm.lookupFunction< Uint32 Function( Uint32 mmrError, Pointer<Utf16> pszText, Uint32 cchText), int Function(int mmrError, Pointer<Utf16> pszText, int cchText)>('midiInGetErrorTextW'); expect(midiInGetErrorText, isA<Function>()); }); test('Can instantiate midiInGetID', () { final winmm = DynamicLibrary.open('winmm.dll'); final midiInGetID = winmm.lookupFunction< Uint32 Function(IntPtr hmi, Pointer<Uint32> puDeviceID), int Function(int hmi, Pointer<Uint32> puDeviceID)>('midiInGetID'); expect(midiInGetID, isA<Function>()); }); test('Can instantiate midiInGetNumDevs', () { final winmm = DynamicLibrary.open('winmm.dll'); final midiInGetNumDevs = winmm.lookupFunction<Uint32 Function(), int Function()>( 'midiInGetNumDevs'); expect(midiInGetNumDevs, isA<Function>()); }); test('Can instantiate midiInMessage', () { final winmm = DynamicLibrary.open('winmm.dll'); final midiInMessage = winmm.lookupFunction< Uint32 Function(IntPtr hmi, Uint32 uMsg, IntPtr dw1, IntPtr dw2), int Function(int hmi, int uMsg, int dw1, int dw2)>('midiInMessage'); expect(midiInMessage, isA<Function>()); }); test('Can instantiate midiInOpen', () { final winmm = DynamicLibrary.open('winmm.dll'); final midiInOpen = winmm.lookupFunction< Uint32 Function(Pointer<IntPtr> phmi, Uint32 uDeviceID, IntPtr dwCallback, IntPtr dwInstance, Uint32 fdwOpen), int Function(Pointer<IntPtr> phmi, int uDeviceID, int dwCallback, int dwInstance, int fdwOpen)>('midiInOpen'); expect(midiInOpen, isA<Function>()); }); test('Can instantiate midiInPrepareHeader', () { final winmm = DynamicLibrary.open('winmm.dll'); final midiInPrepareHeader = winmm.lookupFunction< Uint32 Function(IntPtr hmi, Pointer<MIDIHDR> pmh, Uint32 cbmh), int Function( int hmi, Pointer<MIDIHDR> pmh, int cbmh)>('midiInPrepareHeader'); expect(midiInPrepareHeader, isA<Function>()); }); test('Can instantiate midiInReset', () { final winmm = DynamicLibrary.open('winmm.dll'); final midiInReset = winmm.lookupFunction<Uint32 Function(IntPtr hmi), int Function(int hmi)>('midiInReset'); expect(midiInReset, isA<Function>()); }); test('Can instantiate midiInStart', () { final winmm = DynamicLibrary.open('winmm.dll'); final midiInStart = winmm.lookupFunction<Uint32 Function(IntPtr hmi), int Function(int hmi)>('midiInStart'); expect(midiInStart, isA<Function>()); }); test('Can instantiate midiInStop', () { final winmm = DynamicLibrary.open('winmm.dll'); final midiInStop = winmm.lookupFunction<Uint32 Function(IntPtr hmi), int Function(int hmi)>('midiInStop'); expect(midiInStop, isA<Function>()); }); test('Can instantiate midiInUnprepareHeader', () { final winmm = DynamicLibrary.open('winmm.dll'); final midiInUnprepareHeader = winmm.lookupFunction< Uint32 Function(IntPtr hmi, Pointer<MIDIHDR> pmh, Uint32 cbmh), int Function(int hmi, Pointer<MIDIHDR> pmh, int cbmh)>('midiInUnprepareHeader'); expect(midiInUnprepareHeader, isA<Function>()); }); test('Can instantiate midiOutCacheDrumPatches', () { final winmm = DynamicLibrary.open('winmm.dll'); final midiOutCacheDrumPatches = winmm.lookupFunction< Uint32 Function( IntPtr hmo, Uint32 uPatch, Pointer<Uint16> pwkya, Uint32 fuCache), int Function(int hmo, int uPatch, Pointer<Uint16> pwkya, int fuCache)>('midiOutCacheDrumPatches'); expect(midiOutCacheDrumPatches, isA<Function>()); }); test('Can instantiate midiOutCachePatches', () { final winmm = DynamicLibrary.open('winmm.dll'); final midiOutCachePatches = winmm.lookupFunction< Uint32 Function( IntPtr hmo, Uint32 uBank, Pointer<Uint16> pwpa, Uint32 fuCache), int Function(int hmo, int uBank, Pointer<Uint16> pwpa, int fuCache)>('midiOutCachePatches'); expect(midiOutCachePatches, isA<Function>()); }); test('Can instantiate midiOutClose', () { final winmm = DynamicLibrary.open('winmm.dll'); final midiOutClose = winmm.lookupFunction<Uint32 Function(IntPtr hmo), int Function(int hmo)>('midiOutClose'); expect(midiOutClose, isA<Function>()); }); test('Can instantiate midiOutGetDevCaps', () { final winmm = DynamicLibrary.open('winmm.dll'); final midiOutGetDevCaps = winmm.lookupFunction< Uint32 Function( IntPtr uDeviceID, Pointer<MIDIOUTCAPS> pmoc, Uint32 cbmoc), int Function(int uDeviceID, Pointer<MIDIOUTCAPS> pmoc, int cbmoc)>('midiOutGetDevCapsW'); expect(midiOutGetDevCaps, isA<Function>()); }); test('Can instantiate midiOutGetErrorText', () { final winmm = DynamicLibrary.open('winmm.dll'); final midiOutGetErrorText = winmm.lookupFunction< Uint32 Function( Uint32 mmrError, Pointer<Utf16> pszText, Uint32 cchText), int Function(int mmrError, Pointer<Utf16> pszText, int cchText)>('midiOutGetErrorTextW'); expect(midiOutGetErrorText, isA<Function>()); }); test('Can instantiate midiOutGetID', () { final winmm = DynamicLibrary.open('winmm.dll'); final midiOutGetID = winmm.lookupFunction< Uint32 Function(IntPtr hmo, Pointer<Uint32> puDeviceID), int Function(int hmo, Pointer<Uint32> puDeviceID)>('midiOutGetID'); expect(midiOutGetID, isA<Function>()); }); test('Can instantiate midiOutGetNumDevs', () { final winmm = DynamicLibrary.open('winmm.dll'); final midiOutGetNumDevs = winmm.lookupFunction<Uint32 Function(), int Function()>( 'midiOutGetNumDevs'); expect(midiOutGetNumDevs, isA<Function>()); }); test('Can instantiate midiOutGetVolume', () { final winmm = DynamicLibrary.open('winmm.dll'); final midiOutGetVolume = winmm.lookupFunction< Uint32 Function(IntPtr hmo, Pointer<Uint32> pdwVolume), int Function(int hmo, Pointer<Uint32> pdwVolume)>('midiOutGetVolume'); expect(midiOutGetVolume, isA<Function>()); }); test('Can instantiate midiOutLongMsg', () { final winmm = DynamicLibrary.open('winmm.dll'); final midiOutLongMsg = winmm.lookupFunction< Uint32 Function(IntPtr hmo, Pointer<MIDIHDR> pmh, Uint32 cbmh), int Function( int hmo, Pointer<MIDIHDR> pmh, int cbmh)>('midiOutLongMsg'); expect(midiOutLongMsg, isA<Function>()); }); test('Can instantiate midiOutMessage', () { final winmm = DynamicLibrary.open('winmm.dll'); final midiOutMessage = winmm.lookupFunction< Uint32 Function(IntPtr hmo, Uint32 uMsg, IntPtr dw1, IntPtr dw2), int Function(int hmo, int uMsg, int dw1, int dw2)>('midiOutMessage'); expect(midiOutMessage, isA<Function>()); }); test('Can instantiate midiOutOpen', () { final winmm = DynamicLibrary.open('winmm.dll'); final midiOutOpen = winmm.lookupFunction< Uint32 Function(Pointer<IntPtr> phmo, Uint32 uDeviceID, IntPtr dwCallback, IntPtr dwInstance, Uint32 fdwOpen), int Function(Pointer<IntPtr> phmo, int uDeviceID, int dwCallback, int dwInstance, int fdwOpen)>('midiOutOpen'); expect(midiOutOpen, isA<Function>()); }); test('Can instantiate midiOutPrepareHeader', () { final winmm = DynamicLibrary.open('winmm.dll'); final midiOutPrepareHeader = winmm.lookupFunction< Uint32 Function(IntPtr hmo, Pointer<MIDIHDR> pmh, Uint32 cbmh), int Function( int hmo, Pointer<MIDIHDR> pmh, int cbmh)>('midiOutPrepareHeader'); expect(midiOutPrepareHeader, isA<Function>()); }); test('Can instantiate midiOutReset', () { final winmm = DynamicLibrary.open('winmm.dll'); final midiOutReset = winmm.lookupFunction<Uint32 Function(IntPtr hmo), int Function(int hmo)>('midiOutReset'); expect(midiOutReset, isA<Function>()); }); test('Can instantiate midiOutSetVolume', () { final winmm = DynamicLibrary.open('winmm.dll'); final midiOutSetVolume = winmm.lookupFunction< Uint32 Function(IntPtr hmo, Uint32 dwVolume), int Function(int hmo, int dwVolume)>('midiOutSetVolume'); expect(midiOutSetVolume, isA<Function>()); }); test('Can instantiate midiOutShortMsg', () { final winmm = DynamicLibrary.open('winmm.dll'); final midiOutShortMsg = winmm.lookupFunction< Uint32 Function(IntPtr hmo, Uint32 dwMsg), int Function(int hmo, int dwMsg)>('midiOutShortMsg'); expect(midiOutShortMsg, isA<Function>()); }); test('Can instantiate midiOutUnprepareHeader', () { final winmm = DynamicLibrary.open('winmm.dll'); final midiOutUnprepareHeader = winmm.lookupFunction< Uint32 Function(IntPtr hmo, Pointer<MIDIHDR> pmh, Uint32 cbmh), int Function(int hmo, Pointer<MIDIHDR> pmh, int cbmh)>('midiOutUnprepareHeader'); expect(midiOutUnprepareHeader, isA<Function>()); }); test('Can instantiate PlaySound', () { final winmm = DynamicLibrary.open('winmm.dll'); final PlaySound = winmm.lookupFunction< Int32 Function(Pointer<Utf16> pszSound, IntPtr hmod, Uint32 fdwSound), int Function( Pointer<Utf16> pszSound, int hmod, int fdwSound)>('PlaySoundW'); expect(PlaySound, isA<Function>()); }); test('Can instantiate waveOutClose', () { final winmm = DynamicLibrary.open('winmm.dll'); final waveOutClose = winmm.lookupFunction<Uint32 Function(IntPtr hwo), int Function(int hwo)>('waveOutClose'); expect(waveOutClose, isA<Function>()); }); test('Can instantiate waveOutGetDevCaps', () { final winmm = DynamicLibrary.open('winmm.dll'); final waveOutGetDevCaps = winmm.lookupFunction< Uint32 Function( IntPtr uDeviceID, Pointer<WAVEOUTCAPS> pwoc, Uint32 cbwoc), int Function(int uDeviceID, Pointer<WAVEOUTCAPS> pwoc, int cbwoc)>('waveOutGetDevCapsW'); expect(waveOutGetDevCaps, isA<Function>()); }); test('Can instantiate waveOutGetErrorText', () { final winmm = DynamicLibrary.open('winmm.dll'); final waveOutGetErrorText = winmm.lookupFunction< Uint32 Function( Uint32 mmrError, Pointer<Utf16> pszText, Uint32 cchText), int Function(int mmrError, Pointer<Utf16> pszText, int cchText)>('waveOutGetErrorTextW'); expect(waveOutGetErrorText, isA<Function>()); }); test('Can instantiate waveOutGetID', () { final winmm = DynamicLibrary.open('winmm.dll'); final waveOutGetID = winmm.lookupFunction< Uint32 Function(IntPtr hwo, Pointer<Uint32> puDeviceID), int Function(int hwo, Pointer<Uint32> puDeviceID)>('waveOutGetID'); expect(waveOutGetID, isA<Function>()); }); test('Can instantiate waveOutGetNumDevs', () { final winmm = DynamicLibrary.open('winmm.dll'); final waveOutGetNumDevs = winmm.lookupFunction<Uint32 Function(), int Function()>( 'waveOutGetNumDevs'); expect(waveOutGetNumDevs, isA<Function>()); }); test('Can instantiate waveOutGetPitch', () { final winmm = DynamicLibrary.open('winmm.dll'); final waveOutGetPitch = winmm.lookupFunction< Uint32 Function(IntPtr hwo, Pointer<Uint32> pdwPitch), int Function(int hwo, Pointer<Uint32> pdwPitch)>('waveOutGetPitch'); expect(waveOutGetPitch, isA<Function>()); }); test('Can instantiate waveOutGetPlaybackRate', () { final winmm = DynamicLibrary.open('winmm.dll'); final waveOutGetPlaybackRate = winmm.lookupFunction< Uint32 Function(IntPtr hwo, Pointer<Uint32> pdwRate), int Function( int hwo, Pointer<Uint32> pdwRate)>('waveOutGetPlaybackRate'); expect(waveOutGetPlaybackRate, isA<Function>()); }); test('Can instantiate waveOutGetPosition', () { final winmm = DynamicLibrary.open('winmm.dll'); final waveOutGetPosition = winmm.lookupFunction< Uint32 Function(IntPtr hwo, Pointer<MMTIME> pmmt, Uint32 cbmmt), int Function( int hwo, Pointer<MMTIME> pmmt, int cbmmt)>('waveOutGetPosition'); expect(waveOutGetPosition, isA<Function>()); }); test('Can instantiate waveOutGetVolume', () { final winmm = DynamicLibrary.open('winmm.dll'); final waveOutGetVolume = winmm.lookupFunction< Uint32 Function(IntPtr hwo, Pointer<Uint32> pdwVolume), int Function(int hwo, Pointer<Uint32> pdwVolume)>('waveOutGetVolume'); expect(waveOutGetVolume, isA<Function>()); }); test('Can instantiate waveOutMessage', () { final winmm = DynamicLibrary.open('winmm.dll'); final waveOutMessage = winmm.lookupFunction< Uint32 Function(IntPtr hwo, Uint32 uMsg, IntPtr dw1, IntPtr dw2), int Function(int hwo, int uMsg, int dw1, int dw2)>('waveOutMessage'); expect(waveOutMessage, isA<Function>()); }); test('Can instantiate waveOutOpen', () { final winmm = DynamicLibrary.open('winmm.dll'); final waveOutOpen = winmm.lookupFunction< Uint32 Function( Pointer<IntPtr> phwo, Uint32 uDeviceID, Pointer<WAVEFORMATEX> pwfx, IntPtr dwCallback, IntPtr dwInstance, Uint32 fdwOpen), int Function( Pointer<IntPtr> phwo, int uDeviceID, Pointer<WAVEFORMATEX> pwfx, int dwCallback, int dwInstance, int fdwOpen)>('waveOutOpen'); expect(waveOutOpen, isA<Function>()); }); test('Can instantiate waveOutPause', () { final winmm = DynamicLibrary.open('winmm.dll'); final waveOutPause = winmm.lookupFunction<Uint32 Function(IntPtr hwo), int Function(int hwo)>('waveOutPause'); expect(waveOutPause, isA<Function>()); }); test('Can instantiate waveOutPrepareHeader', () { final winmm = DynamicLibrary.open('winmm.dll'); final waveOutPrepareHeader = winmm.lookupFunction< Uint32 Function(IntPtr hwo, Pointer<WAVEHDR> pwh, Uint32 cbwh), int Function( int hwo, Pointer<WAVEHDR> pwh, int cbwh)>('waveOutPrepareHeader'); expect(waveOutPrepareHeader, isA<Function>()); }); test('Can instantiate waveOutReset', () { final winmm = DynamicLibrary.open('winmm.dll'); final waveOutReset = winmm.lookupFunction<Uint32 Function(IntPtr hwo), int Function(int hwo)>('waveOutReset'); expect(waveOutReset, isA<Function>()); }); test('Can instantiate waveOutRestart', () { final winmm = DynamicLibrary.open('winmm.dll'); final waveOutRestart = winmm.lookupFunction<Uint32 Function(IntPtr hwo), int Function(int hwo)>('waveOutRestart'); expect(waveOutRestart, isA<Function>()); }); test('Can instantiate waveOutSetPitch', () { final winmm = DynamicLibrary.open('winmm.dll'); final waveOutSetPitch = winmm.lookupFunction< Uint32 Function(IntPtr hwo, Uint32 dwPitch), int Function(int hwo, int dwPitch)>('waveOutSetPitch'); expect(waveOutSetPitch, isA<Function>()); }); test('Can instantiate waveOutSetPlaybackRate', () { final winmm = DynamicLibrary.open('winmm.dll'); final waveOutSetPlaybackRate = winmm.lookupFunction< Uint32 Function(IntPtr hwo, Uint32 dwRate), int Function(int hwo, int dwRate)>('waveOutSetPlaybackRate'); expect(waveOutSetPlaybackRate, isA<Function>()); }); test('Can instantiate waveOutSetVolume', () { final winmm = DynamicLibrary.open('winmm.dll'); final waveOutSetVolume = winmm.lookupFunction< Uint32 Function(IntPtr hwo, Uint32 dwVolume), int Function(int hwo, int dwVolume)>('waveOutSetVolume'); expect(waveOutSetVolume, isA<Function>()); }); test('Can instantiate waveOutUnprepareHeader', () { final winmm = DynamicLibrary.open('winmm.dll'); final waveOutUnprepareHeader = winmm.lookupFunction< Uint32 Function(IntPtr hwo, Pointer<WAVEHDR> pwh, Uint32 cbwh), int Function(int hwo, Pointer<WAVEHDR> pwh, int cbwh)>('waveOutUnprepareHeader'); expect(waveOutUnprepareHeader, isA<Function>()); }); test('Can instantiate waveOutWrite', () { final winmm = DynamicLibrary.open('winmm.dll'); final waveOutWrite = winmm.lookupFunction< Uint32 Function(IntPtr hwo, Pointer<WAVEHDR> pwh, Uint32 cbwh), int Function( int hwo, Pointer<WAVEHDR> pwh, int cbwh)>('waveOutWrite'); expect(waveOutWrite, isA<Function>()); }); }); group('Test rometadata functions', () { if (windowsBuildNumber >= 10586) { test('Can instantiate MetaDataGetDispenser', () { final rometadata = DynamicLibrary.open('rometadata.dll'); final MetaDataGetDispenser = rometadata.lookupFunction< Int32 Function( Pointer<GUID> rclsid, Pointer<GUID> riid, Pointer<Pointer> ppv), int Function(Pointer<GUID> rclsid, Pointer<GUID> riid, Pointer<Pointer> ppv)>('MetaDataGetDispenser'); expect(MetaDataGetDispenser, isA<Function>()); }); } }); group('Test api-ms-win-core-winrt-l1-1-0 functions', () { if (windowsBuildNumber >= 9200) { test('Can instantiate RoActivateInstance', () { final api_ms_win_core_winrt_l1_1_0 = DynamicLibrary.open('api-ms-win-core-winrt-l1-1-0.dll'); final RoActivateInstance = api_ms_win_core_winrt_l1_1_0.lookupFunction< Int32 Function(IntPtr activatableClassId, Pointer<Pointer<COMObject>> instance), int Function(int activatableClassId, Pointer<Pointer<COMObject>> instance)>('RoActivateInstance'); expect(RoActivateInstance, isA<Function>()); }); } if (windowsBuildNumber >= 9200) { test('Can instantiate RoGetActivationFactory', () { final api_ms_win_core_winrt_l1_1_0 = DynamicLibrary.open('api-ms-win-core-winrt-l1-1-0.dll'); final RoGetActivationFactory = api_ms_win_core_winrt_l1_1_0.lookupFunction< Int32 Function(IntPtr activatableClassId, Pointer<GUID> iid, Pointer<Pointer> factory), int Function(int activatableClassId, Pointer<GUID> iid, Pointer<Pointer> factory)>('RoGetActivationFactory'); expect(RoGetActivationFactory, isA<Function>()); }); } if (windowsBuildNumber >= 9200) { test('Can instantiate RoGetApartmentIdentifier', () { final api_ms_win_core_winrt_l1_1_0 = DynamicLibrary.open('api-ms-win-core-winrt-l1-1-0.dll'); final RoGetApartmentIdentifier = api_ms_win_core_winrt_l1_1_0.lookupFunction< Int32 Function(Pointer<Uint64> apartmentIdentifier), int Function(Pointer<Uint64> apartmentIdentifier)>( 'RoGetApartmentIdentifier'); expect(RoGetApartmentIdentifier, isA<Function>()); }); } if (windowsBuildNumber >= 9200) { test('Can instantiate RoInitialize', () { final api_ms_win_core_winrt_l1_1_0 = DynamicLibrary.open('api-ms-win-core-winrt-l1-1-0.dll'); final RoInitialize = api_ms_win_core_winrt_l1_1_0.lookupFunction< Int32 Function(Int32 initType), int Function(int initType)>('RoInitialize'); expect(RoInitialize, isA<Function>()); }); } if (windowsBuildNumber >= 9200) { test('Can instantiate RoUninitialize', () { final api_ms_win_core_winrt_l1_1_0 = DynamicLibrary.open('api-ms-win-core-winrt-l1-1-0.dll'); final RoUninitialize = api_ms_win_core_winrt_l1_1_0 .lookupFunction<Void Function(), void Function()>('RoUninitialize'); expect(RoUninitialize, isA<Function>()); }); } }); group('Test api-ms-win-ro-typeresolution-l1-1-0 functions', () {}); group('Test winscard functions', () { test('Can instantiate SCardAccessStartedEvent', () { final winscard = DynamicLibrary.open('winscard.dll'); final SCardAccessStartedEvent = winscard.lookupFunction<IntPtr Function(), int Function()>( 'SCardAccessStartedEvent'); expect(SCardAccessStartedEvent, isA<Function>()); }); test('Can instantiate SCardAddReaderToGroup', () { final winscard = DynamicLibrary.open('winscard.dll'); final SCardAddReaderToGroup = winscard.lookupFunction< Int32 Function(IntPtr hContext, Pointer<Utf16> szReaderName, Pointer<Utf16> szGroupName), int Function(int hContext, Pointer<Utf16> szReaderName, Pointer<Utf16> szGroupName)>('SCardAddReaderToGroupW'); expect(SCardAddReaderToGroup, isA<Function>()); }); if (windowsBuildNumber >= 9200) { test('Can instantiate SCardAudit', () { final winscard = DynamicLibrary.open('winscard.dll'); final SCardAudit = winscard.lookupFunction< Int32 Function(IntPtr hContext, Uint32 dwEvent), int Function(int hContext, int dwEvent)>('SCardAudit'); expect(SCardAudit, isA<Function>()); }); } test('Can instantiate SCardBeginTransaction', () { final winscard = DynamicLibrary.open('winscard.dll'); final SCardBeginTransaction = winscard.lookupFunction< Int32 Function(IntPtr hCard), int Function(int hCard)>('SCardBeginTransaction'); expect(SCardBeginTransaction, isA<Function>()); }); test('Can instantiate SCardCancel', () { final winscard = DynamicLibrary.open('winscard.dll'); final SCardCancel = winscard.lookupFunction< Int32 Function(IntPtr hContext), int Function(int hContext)>('SCardCancel'); expect(SCardCancel, isA<Function>()); }); test('Can instantiate SCardConnect', () { final winscard = DynamicLibrary.open('winscard.dll'); final SCardConnect = winscard.lookupFunction< Int32 Function( IntPtr hContext, Pointer<Utf16> szReader, Uint32 dwShareMode, Uint32 dwPreferredProtocols, Pointer<IntPtr> phCard, Pointer<Uint32> pdwActiveProtocol), int Function( int hContext, Pointer<Utf16> szReader, int dwShareMode, int dwPreferredProtocols, Pointer<IntPtr> phCard, Pointer<Uint32> pdwActiveProtocol)>('SCardConnectW'); expect(SCardConnect, isA<Function>()); }); test('Can instantiate SCardControl', () { final winscard = DynamicLibrary.open('winscard.dll'); final SCardControl = winscard.lookupFunction< Int32 Function( IntPtr hCard, Uint32 dwControlCode, Pointer lpInBuffer, Uint32 cbInBufferSize, Pointer lpOutBuffer, Uint32 cbOutBufferSize, Pointer<Uint32> lpBytesReturned), int Function( int hCard, int dwControlCode, Pointer lpInBuffer, int cbInBufferSize, Pointer lpOutBuffer, int cbOutBufferSize, Pointer<Uint32> lpBytesReturned)>('SCardControl'); expect(SCardControl, isA<Function>()); }); test('Can instantiate SCardDisconnect', () { final winscard = DynamicLibrary.open('winscard.dll'); final SCardDisconnect = winscard.lookupFunction< Int32 Function(IntPtr hCard, Uint32 dwDisposition), int Function(int hCard, int dwDisposition)>('SCardDisconnect'); expect(SCardDisconnect, isA<Function>()); }); test('Can instantiate SCardEndTransaction', () { final winscard = DynamicLibrary.open('winscard.dll'); final SCardEndTransaction = winscard.lookupFunction< Int32 Function(IntPtr hCard, Uint32 dwDisposition), int Function(int hCard, int dwDisposition)>('SCardEndTransaction'); expect(SCardEndTransaction, isA<Function>()); }); test('Can instantiate SCardEstablishContext', () { final winscard = DynamicLibrary.open('winscard.dll'); final SCardEstablishContext = winscard.lookupFunction< Int32 Function(Uint32 dwScope, Pointer pvReserved1, Pointer pvReserved2, Pointer<IntPtr> phContext), int Function(int dwScope, Pointer pvReserved1, Pointer pvReserved2, Pointer<IntPtr> phContext)>('SCardEstablishContext'); expect(SCardEstablishContext, isA<Function>()); }); test('Can instantiate SCardForgetCardType', () { final winscard = DynamicLibrary.open('winscard.dll'); final SCardForgetCardType = winscard.lookupFunction< Int32 Function(IntPtr hContext, Pointer<Utf16> szCardName), int Function( int hContext, Pointer<Utf16> szCardName)>('SCardForgetCardTypeW'); expect(SCardForgetCardType, isA<Function>()); }); test('Can instantiate SCardForgetReader', () { final winscard = DynamicLibrary.open('winscard.dll'); final SCardForgetReader = winscard.lookupFunction< Int32 Function(IntPtr hContext, Pointer<Utf16> szReaderName), int Function( int hContext, Pointer<Utf16> szReaderName)>('SCardForgetReaderW'); expect(SCardForgetReader, isA<Function>()); }); test('Can instantiate SCardForgetReaderGroup', () { final winscard = DynamicLibrary.open('winscard.dll'); final SCardForgetReaderGroup = winscard.lookupFunction< Int32 Function(IntPtr hContext, Pointer<Utf16> szGroupName), int Function(int hContext, Pointer<Utf16> szGroupName)>('SCardForgetReaderGroupW'); expect(SCardForgetReaderGroup, isA<Function>()); }); test('Can instantiate SCardFreeMemory', () { final winscard = DynamicLibrary.open('winscard.dll'); final SCardFreeMemory = winscard.lookupFunction< Int32 Function(IntPtr hContext, Pointer pvMem), int Function(int hContext, Pointer pvMem)>('SCardFreeMemory'); expect(SCardFreeMemory, isA<Function>()); }); test('Can instantiate SCardGetAttrib', () { final winscard = DynamicLibrary.open('winscard.dll'); final SCardGetAttrib = winscard.lookupFunction< Int32 Function(IntPtr hCard, Uint32 dwAttrId, Pointer<Uint8> pbAttr, Pointer<Uint32> pcbAttrLen), int Function(int hCard, int dwAttrId, Pointer<Uint8> pbAttr, Pointer<Uint32> pcbAttrLen)>('SCardGetAttrib'); expect(SCardGetAttrib, isA<Function>()); }); test('Can instantiate SCardGetCardTypeProviderName', () { final winscard = DynamicLibrary.open('winscard.dll'); final SCardGetCardTypeProviderName = winscard.lookupFunction< Int32 Function( IntPtr hContext, Pointer<Utf16> szCardName, Uint32 dwProviderId, Pointer<Utf16> szProvider, Pointer<Uint32> pcchProvider), int Function( int hContext, Pointer<Utf16> szCardName, int dwProviderId, Pointer<Utf16> szProvider, Pointer<Uint32> pcchProvider)>('SCardGetCardTypeProviderNameW'); expect(SCardGetCardTypeProviderName, isA<Function>()); }); if (windowsBuildNumber >= 9200) { test('Can instantiate SCardGetDeviceTypeId', () { final winscard = DynamicLibrary.open('winscard.dll'); final SCardGetDeviceTypeId = winscard.lookupFunction< Int32 Function(IntPtr hContext, Pointer<Utf16> szReaderName, Pointer<Uint32> pdwDeviceTypeId), int Function(int hContext, Pointer<Utf16> szReaderName, Pointer<Uint32> pdwDeviceTypeId)>('SCardGetDeviceTypeIdW'); expect(SCardGetDeviceTypeId, isA<Function>()); }); } test('Can instantiate SCardGetProviderId', () { final winscard = DynamicLibrary.open('winscard.dll'); final SCardGetProviderId = winscard.lookupFunction< Int32 Function(IntPtr hContext, Pointer<Utf16> szCard, Pointer<GUID> pguidProviderId), int Function(int hContext, Pointer<Utf16> szCard, Pointer<GUID> pguidProviderId)>('SCardGetProviderIdW'); expect(SCardGetProviderId, isA<Function>()); }); if (windowsBuildNumber >= 9200) { test('Can instantiate SCardGetReaderDeviceInstanceId', () { final winscard = DynamicLibrary.open('winscard.dll'); final SCardGetReaderDeviceInstanceId = winscard.lookupFunction< Int32 Function( IntPtr hContext, Pointer<Utf16> szReaderName, Pointer<Utf16> szDeviceInstanceId, Pointer<Uint32> pcchDeviceInstanceId), int Function( int hContext, Pointer<Utf16> szReaderName, Pointer<Utf16> szDeviceInstanceId, Pointer<Uint32> pcchDeviceInstanceId)>( 'SCardGetReaderDeviceInstanceIdW'); expect(SCardGetReaderDeviceInstanceId, isA<Function>()); }); } if (windowsBuildNumber >= 9200) { test('Can instantiate SCardGetReaderIcon', () { final winscard = DynamicLibrary.open('winscard.dll'); final SCardGetReaderIcon = winscard.lookupFunction< Int32 Function(IntPtr hContext, Pointer<Utf16> szReaderName, Pointer<Uint8> pbIcon, Pointer<Uint32> pcbIcon), int Function( int hContext, Pointer<Utf16> szReaderName, Pointer<Uint8> pbIcon, Pointer<Uint32> pcbIcon)>('SCardGetReaderIconW'); expect(SCardGetReaderIcon, isA<Function>()); }); } test('Can instantiate SCardGetStatusChange', () { final winscard = DynamicLibrary.open('winscard.dll'); final SCardGetStatusChange = winscard.lookupFunction< Int32 Function(IntPtr hContext, Uint32 dwTimeout, Pointer<SCARD_READERSTATE> rgReaderStates, Uint32 cReaders), int Function( int hContext, int dwTimeout, Pointer<SCARD_READERSTATE> rgReaderStates, int cReaders)>('SCardGetStatusChangeW'); expect(SCardGetStatusChange, isA<Function>()); }); test('Can instantiate SCardGetTransmitCount', () { final winscard = DynamicLibrary.open('winscard.dll'); final SCardGetTransmitCount = winscard.lookupFunction< Int32 Function(IntPtr hCard, Pointer<Uint32> pcTransmitCount), int Function(int hCard, Pointer<Uint32> pcTransmitCount)>('SCardGetTransmitCount'); expect(SCardGetTransmitCount, isA<Function>()); }); test('Can instantiate SCardIntroduceCardType', () { final winscard = DynamicLibrary.open('winscard.dll'); final SCardIntroduceCardType = winscard.lookupFunction< Int32 Function( IntPtr hContext, Pointer<Utf16> szCardName, Pointer<GUID> pguidPrimaryProvider, Pointer<GUID> rgguidInterfaces, Uint32 dwInterfaceCount, Pointer<Uint8> pbAtr, Pointer<Uint8> pbAtrMask, Uint32 cbAtrLen), int Function( int hContext, Pointer<Utf16> szCardName, Pointer<GUID> pguidPrimaryProvider, Pointer<GUID> rgguidInterfaces, int dwInterfaceCount, Pointer<Uint8> pbAtr, Pointer<Uint8> pbAtrMask, int cbAtrLen)>('SCardIntroduceCardTypeW'); expect(SCardIntroduceCardType, isA<Function>()); }); test('Can instantiate SCardIntroduceReader', () { final winscard = DynamicLibrary.open('winscard.dll'); final SCardIntroduceReader = winscard.lookupFunction< Int32 Function(IntPtr hContext, Pointer<Utf16> szReaderName, Pointer<Utf16> szDeviceName), int Function(int hContext, Pointer<Utf16> szReaderName, Pointer<Utf16> szDeviceName)>('SCardIntroduceReaderW'); expect(SCardIntroduceReader, isA<Function>()); }); test('Can instantiate SCardIntroduceReaderGroup', () { final winscard = DynamicLibrary.open('winscard.dll'); final SCardIntroduceReaderGroup = winscard.lookupFunction< Int32 Function(IntPtr hContext, Pointer<Utf16> szGroupName), int Function(int hContext, Pointer<Utf16> szGroupName)>('SCardIntroduceReaderGroupW'); expect(SCardIntroduceReaderGroup, isA<Function>()); }); test('Can instantiate SCardIsValidContext', () { final winscard = DynamicLibrary.open('winscard.dll'); final SCardIsValidContext = winscard.lookupFunction< Int32 Function(IntPtr hContext), int Function(int hContext)>('SCardIsValidContext'); expect(SCardIsValidContext, isA<Function>()); }); test('Can instantiate SCardListCards', () { final winscard = DynamicLibrary.open('winscard.dll'); final SCardListCards = winscard.lookupFunction< Int32 Function( IntPtr hContext, Pointer<Uint8> pbAtr, Pointer<GUID> rgquidInterfaces, Uint32 cguidInterfaceCount, Pointer<Utf16> mszCards, Pointer<Uint32> pcchCards), int Function( int hContext, Pointer<Uint8> pbAtr, Pointer<GUID> rgquidInterfaces, int cguidInterfaceCount, Pointer<Utf16> mszCards, Pointer<Uint32> pcchCards)>('SCardListCardsW'); expect(SCardListCards, isA<Function>()); }); test('Can instantiate SCardListInterfaces', () { final winscard = DynamicLibrary.open('winscard.dll'); final SCardListInterfaces = winscard.lookupFunction< Int32 Function(IntPtr hContext, Pointer<Utf16> szCard, Pointer<GUID> pguidInterfaces, Pointer<Uint32> pcguidInterfaces), int Function( int hContext, Pointer<Utf16> szCard, Pointer<GUID> pguidInterfaces, Pointer<Uint32> pcguidInterfaces)>('SCardListInterfacesW'); expect(SCardListInterfaces, isA<Function>()); }); test('Can instantiate SCardListReaderGroups', () { final winscard = DynamicLibrary.open('winscard.dll'); final SCardListReaderGroups = winscard.lookupFunction< Int32 Function(IntPtr hContext, Pointer<Utf16> mszGroups, Pointer<Uint32> pcchGroups), int Function(int hContext, Pointer<Utf16> mszGroups, Pointer<Uint32> pcchGroups)>('SCardListReaderGroupsW'); expect(SCardListReaderGroups, isA<Function>()); }); test('Can instantiate SCardListReaders', () { final winscard = DynamicLibrary.open('winscard.dll'); final SCardListReaders = winscard.lookupFunction< Int32 Function(IntPtr hContext, Pointer<Utf16> mszGroups, Pointer<Utf16> mszReaders, Pointer<Uint32> pcchReaders), int Function( int hContext, Pointer<Utf16> mszGroups, Pointer<Utf16> mszReaders, Pointer<Uint32> pcchReaders)>('SCardListReadersW'); expect(SCardListReaders, isA<Function>()); }); if (windowsBuildNumber >= 9200) { test('Can instantiate SCardListReadersWithDeviceInstanceId', () { final winscard = DynamicLibrary.open('winscard.dll'); final SCardListReadersWithDeviceInstanceId = winscard.lookupFunction< Int32 Function(IntPtr hContext, Pointer<Utf16> szDeviceInstanceId, Pointer<Utf16> mszReaders, Pointer<Uint32> pcchReaders), int Function( int hContext, Pointer<Utf16> szDeviceInstanceId, Pointer<Utf16> mszReaders, Pointer<Uint32> pcchReaders)>('SCardListReadersWithDeviceInstanceIdW'); expect(SCardListReadersWithDeviceInstanceId, isA<Function>()); }); } test('Can instantiate SCardLocateCards', () { final winscard = DynamicLibrary.open('winscard.dll'); final SCardLocateCards = winscard.lookupFunction< Int32 Function(IntPtr hContext, Pointer<Utf16> mszCards, Pointer<SCARD_READERSTATE> rgReaderStates, Uint32 cReaders), int Function( int hContext, Pointer<Utf16> mszCards, Pointer<SCARD_READERSTATE> rgReaderStates, int cReaders)>('SCardLocateCardsW'); expect(SCardLocateCards, isA<Function>()); }); test('Can instantiate SCardLocateCardsByATR', () { final winscard = DynamicLibrary.open('winscard.dll'); final SCardLocateCardsByATR = winscard.lookupFunction< Int32 Function( IntPtr hContext, Pointer<SCARD_ATRMASK> rgAtrMasks, Uint32 cAtrs, Pointer<SCARD_READERSTATE> rgReaderStates, Uint32 cReaders), int Function( int hContext, Pointer<SCARD_ATRMASK> rgAtrMasks, int cAtrs, Pointer<SCARD_READERSTATE> rgReaderStates, int cReaders)>('SCardLocateCardsByATRW'); expect(SCardLocateCardsByATR, isA<Function>()); }); test('Can instantiate SCardReadCache', () { final winscard = DynamicLibrary.open('winscard.dll'); final SCardReadCache = winscard.lookupFunction< Int32 Function( IntPtr hContext, Pointer<GUID> CardIdentifier, Uint32 FreshnessCounter, Pointer<Utf16> LookupName, Pointer<Uint8> Data, Pointer<Uint32> DataLen), int Function( int hContext, Pointer<GUID> CardIdentifier, int FreshnessCounter, Pointer<Utf16> LookupName, Pointer<Uint8> Data, Pointer<Uint32> DataLen)>('SCardReadCacheW'); expect(SCardReadCache, isA<Function>()); }); test('Can instantiate SCardReconnect', () { final winscard = DynamicLibrary.open('winscard.dll'); final SCardReconnect = winscard.lookupFunction< Int32 Function( IntPtr hCard, Uint32 dwShareMode, Uint32 dwPreferredProtocols, Uint32 dwInitialization, Pointer<Uint32> pdwActiveProtocol), int Function( int hCard, int dwShareMode, int dwPreferredProtocols, int dwInitialization, Pointer<Uint32> pdwActiveProtocol)>('SCardReconnect'); expect(SCardReconnect, isA<Function>()); }); test('Can instantiate SCardReleaseContext', () { final winscard = DynamicLibrary.open('winscard.dll'); final SCardReleaseContext = winscard.lookupFunction< Int32 Function(IntPtr hContext), int Function(int hContext)>('SCardReleaseContext'); expect(SCardReleaseContext, isA<Function>()); }); test('Can instantiate SCardReleaseStartedEvent', () { final winscard = DynamicLibrary.open('winscard.dll'); final SCardReleaseStartedEvent = winscard.lookupFunction<Void Function(), void Function()>( 'SCardReleaseStartedEvent'); expect(SCardReleaseStartedEvent, isA<Function>()); }); test('Can instantiate SCardRemoveReaderFromGroup', () { final winscard = DynamicLibrary.open('winscard.dll'); final SCardRemoveReaderFromGroup = winscard.lookupFunction< Int32 Function(IntPtr hContext, Pointer<Utf16> szReaderName, Pointer<Utf16> szGroupName), int Function(int hContext, Pointer<Utf16> szReaderName, Pointer<Utf16> szGroupName)>('SCardRemoveReaderFromGroupW'); expect(SCardRemoveReaderFromGroup, isA<Function>()); }); test('Can instantiate SCardSetAttrib', () { final winscard = DynamicLibrary.open('winscard.dll'); final SCardSetAttrib = winscard.lookupFunction< Int32 Function(IntPtr hCard, Uint32 dwAttrId, Pointer<Uint8> pbAttr, Uint32 cbAttrLen), int Function(int hCard, int dwAttrId, Pointer<Uint8> pbAttr, int cbAttrLen)>('SCardSetAttrib'); expect(SCardSetAttrib, isA<Function>()); }); test('Can instantiate SCardSetCardTypeProviderName', () { final winscard = DynamicLibrary.open('winscard.dll'); final SCardSetCardTypeProviderName = winscard.lookupFunction< Int32 Function(IntPtr hContext, Pointer<Utf16> szCardName, Uint32 dwProviderId, Pointer<Utf16> szProvider), int Function( int hContext, Pointer<Utf16> szCardName, int dwProviderId, Pointer<Utf16> szProvider)>('SCardSetCardTypeProviderNameW'); expect(SCardSetCardTypeProviderName, isA<Function>()); }); test('Can instantiate SCardStatus', () { final winscard = DynamicLibrary.open('winscard.dll'); final SCardStatus = winscard.lookupFunction< Int32 Function( IntPtr hCard, Pointer<Utf16> mszReaderNames, Pointer<Uint32> pcchReaderLen, Pointer<Uint32> pdwState, Pointer<Uint32> pdwProtocol, Pointer<Uint8> pbAtr, Pointer<Uint32> pcbAtrLen), int Function( int hCard, Pointer<Utf16> mszReaderNames, Pointer<Uint32> pcchReaderLen, Pointer<Uint32> pdwState, Pointer<Uint32> pdwProtocol, Pointer<Uint8> pbAtr, Pointer<Uint32> pcbAtrLen)>('SCardStatusW'); expect(SCardStatus, isA<Function>()); }); test('Can instantiate SCardTransmit', () { final winscard = DynamicLibrary.open('winscard.dll'); final SCardTransmit = winscard.lookupFunction< Int32 Function( IntPtr hCard, Pointer<SCARD_IO_REQUEST> pioSendPci, Pointer<Uint8> pbSendBuffer, Uint32 cbSendLength, Pointer<SCARD_IO_REQUEST> pioRecvPci, Pointer<Uint8> pbRecvBuffer, Pointer<Uint32> pcbRecvLength), int Function( int hCard, Pointer<SCARD_IO_REQUEST> pioSendPci, Pointer<Uint8> pbSendBuffer, int cbSendLength, Pointer<SCARD_IO_REQUEST> pioRecvPci, Pointer<Uint8> pbRecvBuffer, Pointer<Uint32> pcbRecvLength)>('SCardTransmit'); expect(SCardTransmit, isA<Function>()); }); test('Can instantiate SCardWriteCache', () { final winscard = DynamicLibrary.open('winscard.dll'); final SCardWriteCache = winscard.lookupFunction< Int32 Function( IntPtr hContext, Pointer<GUID> CardIdentifier, Uint32 FreshnessCounter, Pointer<Utf16> LookupName, Pointer<Uint8> Data, Uint32 DataLen), int Function( int hContext, Pointer<GUID> CardIdentifier, int FreshnessCounter, Pointer<Utf16> LookupName, Pointer<Uint8> Data, int DataLen)>('SCardWriteCacheW'); expect(SCardWriteCache, isA<Function>()); }); }); group('Test scarddlg functions', () { test('Can instantiate SCardUIDlgSelectCard', () { final scarddlg = DynamicLibrary.open('scarddlg.dll'); final SCardUIDlgSelectCard = scarddlg.lookupFunction< Int32 Function(Pointer<OPENCARDNAME_EX> param0), int Function( Pointer<OPENCARDNAME_EX> param0)>('SCardUIDlgSelectCardW'); expect(SCardUIDlgSelectCard, isA<Function>()); }); }); group('Test setupapi functions', () { test('Can instantiate SetupDiDestroyDeviceInfoList', () { final setupapi = DynamicLibrary.open('setupapi.dll'); final SetupDiDestroyDeviceInfoList = setupapi.lookupFunction< Int32 Function(Pointer DeviceInfoSet), int Function(Pointer DeviceInfoSet)>('SetupDiDestroyDeviceInfoList'); expect(SetupDiDestroyDeviceInfoList, isA<Function>()); }); test('Can instantiate SetupDiEnumDeviceInfo', () { final setupapi = DynamicLibrary.open('setupapi.dll'); final SetupDiEnumDeviceInfo = setupapi.lookupFunction< Int32 Function(Pointer DeviceInfoSet, Uint32 MemberIndex, Pointer<SP_DEVINFO_DATA> DeviceInfoData), int Function(Pointer DeviceInfoSet, int MemberIndex, Pointer<SP_DEVINFO_DATA> DeviceInfoData)>( 'SetupDiEnumDeviceInfo'); expect(SetupDiEnumDeviceInfo, isA<Function>()); }); test('Can instantiate SetupDiGetClassDevs', () { final setupapi = DynamicLibrary.open('setupapi.dll'); final SetupDiGetClassDevs = setupapi.lookupFunction< Pointer Function(Pointer<GUID> ClassGuid, Pointer<Utf16> Enumerator, IntPtr hwndParent, Uint32 Flags), Pointer Function(Pointer<GUID> ClassGuid, Pointer<Utf16> Enumerator, int hwndParent, int Flags)>('SetupDiGetClassDevsW'); expect(SetupDiGetClassDevs, isA<Function>()); }); test('Can instantiate SetupDiOpenDevRegKey', () { final setupapi = DynamicLibrary.open('setupapi.dll'); final SetupDiOpenDevRegKey = setupapi.lookupFunction< IntPtr Function( Pointer DeviceInfoSet, Pointer<SP_DEVINFO_DATA> DeviceInfoData, Uint32 Scope, Uint32 HwProfile, Uint32 KeyType, Uint32 samDesired), int Function( Pointer DeviceInfoSet, Pointer<SP_DEVINFO_DATA> DeviceInfoData, int Scope, int HwProfile, int KeyType, int samDesired)>('SetupDiOpenDevRegKey'); expect(SetupDiOpenDevRegKey, isA<Function>()); }); }); group('Test dbghelp functions', () { test('Can instantiate SymCleanup', () { final dbghelp = DynamicLibrary.open('dbghelp.dll'); final SymCleanup = dbghelp.lookupFunction<Int32 Function(IntPtr hProcess), int Function(int hProcess)>('SymCleanup'); expect(SymCleanup, isA<Function>()); }); test('Can instantiate SymEnumSymbols', () { final dbghelp = DynamicLibrary.open('dbghelp.dll'); final SymEnumSymbols = dbghelp.lookupFunction< Int32 Function( IntPtr hProcess, Uint64 BaseOfDll, Pointer<Utf16> Mask, Pointer<NativeFunction<SymEnumSymbolsProc>> EnumSymbolsCallback, Pointer UserContext), int Function( int hProcess, int BaseOfDll, Pointer<Utf16> Mask, Pointer<NativeFunction<SymEnumSymbolsProc>> EnumSymbolsCallback, Pointer UserContext)>('SymEnumSymbolsW'); expect(SymEnumSymbols, isA<Function>()); }); test('Can instantiate SymFromAddr', () { final dbghelp = DynamicLibrary.open('dbghelp.dll'); final SymFromAddr = dbghelp.lookupFunction< Int32 Function(IntPtr hProcess, Uint64 Address, Pointer<Uint64> Displacement, Pointer<SYMBOL_INFO> Symbol), int Function(int hProcess, int Address, Pointer<Uint64> Displacement, Pointer<SYMBOL_INFO> Symbol)>('SymFromAddrW'); expect(SymFromAddr, isA<Function>()); }); test('Can instantiate SymFromToken', () { final dbghelp = DynamicLibrary.open('dbghelp.dll'); final SymFromToken = dbghelp.lookupFunction< Int32 Function(IntPtr hProcess, Uint64 Base, Uint32 Token, Pointer<SYMBOL_INFO> Symbol), int Function(int hProcess, int Base, int Token, Pointer<SYMBOL_INFO> Symbol)>('SymFromTokenW'); expect(SymFromToken, isA<Function>()); }); if (windowsBuildNumber >= 17134) { test('Can instantiate SymGetExtendedOption', () { final dbghelp = DynamicLibrary.open('dbghelp.dll'); final SymGetExtendedOption = dbghelp.lookupFunction< Int32 Function(Int32 option), int Function(int option)>('SymGetExtendedOption'); expect(SymGetExtendedOption, isA<Function>()); }); } test('Can instantiate SymInitialize', () { final dbghelp = DynamicLibrary.open('dbghelp.dll'); final SymInitialize = dbghelp.lookupFunction< Int32 Function(IntPtr hProcess, Pointer<Utf16> UserSearchPath, Int32 fInvadeProcess), int Function(int hProcess, Pointer<Utf16> UserSearchPath, int fInvadeProcess)>('SymInitializeW'); expect(SymInitialize, isA<Function>()); }); test('Can instantiate SymLoadModuleEx', () { final dbghelp = DynamicLibrary.open('dbghelp.dll'); final SymLoadModuleEx = dbghelp.lookupFunction< Uint64 Function( IntPtr hProcess, IntPtr hFile, Pointer<Utf16> ImageName, Pointer<Utf16> ModuleName, Uint64 BaseOfDll, Uint32 DllSize, Pointer<MODLOAD_DATA> Data, Uint32 Flags), int Function( int hProcess, int hFile, Pointer<Utf16> ImageName, Pointer<Utf16> ModuleName, int BaseOfDll, int DllSize, Pointer<MODLOAD_DATA> Data, int Flags)>('SymLoadModuleExW'); expect(SymLoadModuleEx, isA<Function>()); }); if (windowsBuildNumber >= 17134) { test('Can instantiate SymSetExtendedOption', () { final dbghelp = DynamicLibrary.open('dbghelp.dll'); final SymSetExtendedOption = dbghelp.lookupFunction< Int32 Function(Int32 option, Int32 value), int Function(int option, int value)>('SymSetExtendedOption'); expect(SymSetExtendedOption, isA<Function>()); }); } test('Can instantiate SymSetOptions', () { final dbghelp = DynamicLibrary.open('dbghelp.dll'); final SymSetOptions = dbghelp.lookupFunction< Uint32 Function(Uint32 SymOptions), int Function(int SymOptions)>('SymSetOptions'); expect(SymSetOptions, isA<Function>()); }); test('Can instantiate SymSetParentWindow', () { final dbghelp = DynamicLibrary.open('dbghelp.dll'); final SymSetParentWindow = dbghelp.lookupFunction< Int32 Function(IntPtr hwnd), int Function(int hwnd)>('SymSetParentWindow'); expect(SymSetParentWindow, isA<Function>()); }); test('Can instantiate SymSetScopeFromAddr', () { final dbghelp = DynamicLibrary.open('dbghelp.dll'); final SymSetScopeFromAddr = dbghelp.lookupFunction< Int32 Function(IntPtr hProcess, Uint64 Address), int Function(int hProcess, int Address)>('SymSetScopeFromAddr'); expect(SymSetScopeFromAddr, isA<Function>()); }); test('Can instantiate SymSetScopeFromIndex', () { final dbghelp = DynamicLibrary.open('dbghelp.dll'); final SymSetScopeFromIndex = dbghelp.lookupFunction< Int32 Function(IntPtr hProcess, Uint64 BaseOfDll, Uint32 Index), int Function( int hProcess, int BaseOfDll, int Index)>('SymSetScopeFromIndex'); expect(SymSetScopeFromIndex, isA<Function>()); }); if (windowsBuildNumber >= 9200) { test('Can instantiate SymSetScopeFromInlineContext', () { final dbghelp = DynamicLibrary.open('dbghelp.dll'); final SymSetScopeFromInlineContext = dbghelp.lookupFunction< Int32 Function( IntPtr hProcess, Uint64 Address, Uint32 InlineContext), int Function(int hProcess, int Address, int InlineContext)>('SymSetScopeFromInlineContext'); expect(SymSetScopeFromInlineContext, isA<Function>()); }); } test('Can instantiate SymSetSearchPath', () { final dbghelp = DynamicLibrary.open('dbghelp.dll'); final SymSetSearchPath = dbghelp.lookupFunction< Int32 Function(IntPtr hProcess, Pointer<Utf16> SearchPathA), int Function( int hProcess, Pointer<Utf16> SearchPathA)>('SymSetSearchPathW'); expect(SymSetSearchPath, isA<Function>()); }); test('Can instantiate SymUnloadModule', () { final dbghelp = DynamicLibrary.open('dbghelp.dll'); final SymUnloadModule = dbghelp.lookupFunction< Int32 Function(IntPtr hProcess, Uint32 BaseOfDll), int Function(int hProcess, int BaseOfDll)>('SymUnloadModule'); expect(SymUnloadModule, isA<Function>()); }); test('Can instantiate SymUnloadModule64', () { final dbghelp = DynamicLibrary.open('dbghelp.dll'); final SymUnloadModule64 = dbghelp.lookupFunction< Int32 Function(IntPtr hProcess, Uint64 BaseOfDll), int Function(int hProcess, int BaseOfDll)>('SymUnloadModule64'); expect(SymUnloadModule64, isA<Function>()); }); test('Can instantiate UnDecorateSymbolName', () { final dbghelp = DynamicLibrary.open('dbghelp.dll'); final UnDecorateSymbolName = dbghelp.lookupFunction< Uint32 Function(Pointer<Utf16> name, Pointer<Utf16> outputString, Uint32 maxStringLength, Uint32 flags), int Function(Pointer<Utf16> name, Pointer<Utf16> outputString, int maxStringLength, int flags)>('UnDecorateSymbolNameW'); expect(UnDecorateSymbolName, isA<Function>()); }); }); group('Test api-ms-win-core-winrt-string-l1-1-0 functions', () { if (windowsBuildNumber >= 9200) { test('Can instantiate WindowsCompareStringOrdinal', () { final api_ms_win_core_winrt_string_l1_1_0 = DynamicLibrary.open('api-ms-win-core-winrt-string-l1-1-0.dll'); final WindowsCompareStringOrdinal = api_ms_win_core_winrt_string_l1_1_0.lookupFunction< Int32 Function( IntPtr string1, IntPtr string2, Pointer<Int32> result), int Function(int string1, int string2, Pointer<Int32> result)>('WindowsCompareStringOrdinal'); expect(WindowsCompareStringOrdinal, isA<Function>()); }); } if (windowsBuildNumber >= 9200) { test('Can instantiate WindowsConcatString', () { final api_ms_win_core_winrt_string_l1_1_0 = DynamicLibrary.open('api-ms-win-core-winrt-string-l1-1-0.dll'); final WindowsConcatString = api_ms_win_core_winrt_string_l1_1_0.lookupFunction< Int32 Function( IntPtr string1, IntPtr string2, Pointer<IntPtr> newString), int Function(int string1, int string2, Pointer<IntPtr> newString)>('WindowsConcatString'); expect(WindowsConcatString, isA<Function>()); }); } if (windowsBuildNumber >= 9200) { test('Can instantiate WindowsCreateString', () { final api_ms_win_core_winrt_string_l1_1_0 = DynamicLibrary.open('api-ms-win-core-winrt-string-l1-1-0.dll'); final WindowsCreateString = api_ms_win_core_winrt_string_l1_1_0.lookupFunction< Int32 Function(Pointer<Utf16> sourceString, Uint32 length, Pointer<IntPtr> string), int Function(Pointer<Utf16> sourceString, int length, Pointer<IntPtr> string)>('WindowsCreateString'); expect(WindowsCreateString, isA<Function>()); }); } if (windowsBuildNumber >= 9200) { test('Can instantiate WindowsDeleteString', () { final api_ms_win_core_winrt_string_l1_1_0 = DynamicLibrary.open('api-ms-win-core-winrt-string-l1-1-0.dll'); final WindowsDeleteString = api_ms_win_core_winrt_string_l1_1_0.lookupFunction< Int32 Function(IntPtr string), int Function(int string)>('WindowsDeleteString'); expect(WindowsDeleteString, isA<Function>()); }); } if (windowsBuildNumber >= 9200) { test('Can instantiate WindowsDeleteStringBuffer', () { final api_ms_win_core_winrt_string_l1_1_0 = DynamicLibrary.open('api-ms-win-core-winrt-string-l1-1-0.dll'); final WindowsDeleteStringBuffer = api_ms_win_core_winrt_string_l1_1_0.lookupFunction< Int32 Function(IntPtr bufferHandle), int Function(int bufferHandle)>('WindowsDeleteStringBuffer'); expect(WindowsDeleteStringBuffer, isA<Function>()); }); } if (windowsBuildNumber >= 9200) { test('Can instantiate WindowsDuplicateString', () { final api_ms_win_core_winrt_string_l1_1_0 = DynamicLibrary.open('api-ms-win-core-winrt-string-l1-1-0.dll'); final WindowsDuplicateString = api_ms_win_core_winrt_string_l1_1_0.lookupFunction< Int32 Function(IntPtr string, Pointer<IntPtr> newString), int Function(int string, Pointer<IntPtr> newString)>('WindowsDuplicateString'); expect(WindowsDuplicateString, isA<Function>()); }); } if (windowsBuildNumber >= 9200) { test('Can instantiate WindowsGetStringLen', () { final api_ms_win_core_winrt_string_l1_1_0 = DynamicLibrary.open('api-ms-win-core-winrt-string-l1-1-0.dll'); final WindowsGetStringLen = api_ms_win_core_winrt_string_l1_1_0.lookupFunction< Uint32 Function(IntPtr string), int Function(int string)>('WindowsGetStringLen'); expect(WindowsGetStringLen, isA<Function>()); }); } if (windowsBuildNumber >= 9200) { test('Can instantiate WindowsGetStringRawBuffer', () { final api_ms_win_core_winrt_string_l1_1_0 = DynamicLibrary.open('api-ms-win-core-winrt-string-l1-1-0.dll'); final WindowsGetStringRawBuffer = api_ms_win_core_winrt_string_l1_1_0.lookupFunction< Pointer<Utf16> Function(IntPtr string, Pointer<Uint32> length), Pointer<Utf16> Function(int string, Pointer<Uint32> length)>('WindowsGetStringRawBuffer'); expect(WindowsGetStringRawBuffer, isA<Function>()); }); } if (windowsBuildNumber >= 9200) { test('Can instantiate WindowsIsStringEmpty', () { final api_ms_win_core_winrt_string_l1_1_0 = DynamicLibrary.open('api-ms-win-core-winrt-string-l1-1-0.dll'); final WindowsIsStringEmpty = api_ms_win_core_winrt_string_l1_1_0.lookupFunction< Int32 Function(IntPtr string), int Function(int string)>('WindowsIsStringEmpty'); expect(WindowsIsStringEmpty, isA<Function>()); }); } if (windowsBuildNumber >= 9200) { test('Can instantiate WindowsPreallocateStringBuffer', () { final api_ms_win_core_winrt_string_l1_1_0 = DynamicLibrary.open('api-ms-win-core-winrt-string-l1-1-0.dll'); final WindowsPreallocateStringBuffer = api_ms_win_core_winrt_string_l1_1_0.lookupFunction< Int32 Function( Uint32 length, Pointer<Pointer<Uint16>> charBuffer, Pointer<IntPtr> bufferHandle), int Function( int length, Pointer<Pointer<Uint16>> charBuffer, Pointer<IntPtr> bufferHandle)>( 'WindowsPreallocateStringBuffer'); expect(WindowsPreallocateStringBuffer, isA<Function>()); }); } if (windowsBuildNumber >= 9200) { test('Can instantiate WindowsPromoteStringBuffer', () { final api_ms_win_core_winrt_string_l1_1_0 = DynamicLibrary.open('api-ms-win-core-winrt-string-l1-1-0.dll'); final WindowsPromoteStringBuffer = api_ms_win_core_winrt_string_l1_1_0.lookupFunction< Int32 Function(IntPtr bufferHandle, Pointer<IntPtr> string), int Function(int bufferHandle, Pointer<IntPtr> string)>('WindowsPromoteStringBuffer'); expect(WindowsPromoteStringBuffer, isA<Function>()); }); } if (windowsBuildNumber >= 9200) { test('Can instantiate WindowsReplaceString', () { final api_ms_win_core_winrt_string_l1_1_0 = DynamicLibrary.open('api-ms-win-core-winrt-string-l1-1-0.dll'); final WindowsReplaceString = api_ms_win_core_winrt_string_l1_1_0.lookupFunction< Int32 Function(IntPtr string, IntPtr stringReplaced, IntPtr stringReplaceWith, Pointer<IntPtr> newString), int Function( int string, int stringReplaced, int stringReplaceWith, Pointer<IntPtr> newString)>('WindowsReplaceString'); expect(WindowsReplaceString, isA<Function>()); }); } if (windowsBuildNumber >= 9200) { test('Can instantiate WindowsStringHasEmbeddedNull', () { final api_ms_win_core_winrt_string_l1_1_0 = DynamicLibrary.open('api-ms-win-core-winrt-string-l1-1-0.dll'); final WindowsStringHasEmbeddedNull = api_ms_win_core_winrt_string_l1_1_0.lookupFunction< Int32 Function(IntPtr string, Pointer<Int32> hasEmbedNull), int Function(int string, Pointer<Int32> hasEmbedNull)>( 'WindowsStringHasEmbeddedNull'); expect(WindowsStringHasEmbeddedNull, isA<Function>()); }); } if (windowsBuildNumber >= 9200) { test('Can instantiate WindowsSubstring', () { final api_ms_win_core_winrt_string_l1_1_0 = DynamicLibrary.open('api-ms-win-core-winrt-string-l1-1-0.dll'); final WindowsSubstring = api_ms_win_core_winrt_string_l1_1_0.lookupFunction< Int32 Function(IntPtr string, Uint32 startIndex, Pointer<IntPtr> newString), int Function(int string, int startIndex, Pointer<IntPtr> newString)>('WindowsSubstring'); expect(WindowsSubstring, isA<Function>()); }); } if (windowsBuildNumber >= 9200) { test('Can instantiate WindowsSubstringWithSpecifiedLength', () { final api_ms_win_core_winrt_string_l1_1_0 = DynamicLibrary.open('api-ms-win-core-winrt-string-l1-1-0.dll'); final WindowsSubstringWithSpecifiedLength = api_ms_win_core_winrt_string_l1_1_0.lookupFunction< Int32 Function(IntPtr string, Uint32 startIndex, Uint32 length, Pointer<IntPtr> newString), int Function( int string, int startIndex, int length, Pointer<IntPtr> newString)>('WindowsSubstringWithSpecifiedLength'); expect(WindowsSubstringWithSpecifiedLength, isA<Function>()); }); } if (windowsBuildNumber >= 9200) { test('Can instantiate WindowsTrimStringEnd', () { final api_ms_win_core_winrt_string_l1_1_0 = DynamicLibrary.open('api-ms-win-core-winrt-string-l1-1-0.dll'); final WindowsTrimStringEnd = api_ms_win_core_winrt_string_l1_1_0.lookupFunction< Int32 Function(IntPtr string, IntPtr trimString, Pointer<IntPtr> newString), int Function(int string, int trimString, Pointer<IntPtr> newString)>('WindowsTrimStringEnd'); expect(WindowsTrimStringEnd, isA<Function>()); }); } if (windowsBuildNumber >= 9200) { test('Can instantiate WindowsTrimStringStart', () { final api_ms_win_core_winrt_string_l1_1_0 = DynamicLibrary.open('api-ms-win-core-winrt-string-l1-1-0.dll'); final WindowsTrimStringStart = api_ms_win_core_winrt_string_l1_1_0.lookupFunction< Int32 Function(IntPtr string, IntPtr trimString, Pointer<IntPtr> newString), int Function(int string, int trimString, Pointer<IntPtr> newString)>('WindowsTrimStringStart'); expect(WindowsTrimStringStart, isA<Function>()); }); } }); } <|start_filename|>lib/src/kernel32.dart<|end_filename|> // Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. // Maps FFI prototypes onto the corresponding Win32 API function calls // THIS FILE IS GENERATED AUTOMATICALLY AND SHOULD NOT BE EDITED DIRECTLY. // ignore_for_file: unused_import import 'dart:ffi'; import 'package:ffi/ffi.dart'; import 'callbacks.dart'; import 'combase.dart'; import 'guid.dart'; import 'structs.dart'; import 'structs.g.dart'; final _kernel32 = DynamicLibrary.open('kernel32.dll'); /// The ActivateActCtx function activates the specified activation context. /// It does this by pushing the specified activation context to the top of /// the activation stack. The specified activation context is thus /// associated with the current thread and any appropriate side-by-side API /// functions. /// /// ```c /// BOOL ActivateActCtx( /// HANDLE hActCtx, /// ULONG_PTR *lpCookie /// ); /// ``` /// {@category kernel32} int ActivateActCtx(int hActCtx, Pointer<IntPtr> lpCookie) => _ActivateActCtx(hActCtx, lpCookie); late final _ActivateActCtx = _kernel32.lookupFunction< Int32 Function(IntPtr hActCtx, Pointer<IntPtr> lpCookie), int Function(int hActCtx, Pointer<IntPtr> lpCookie)>('ActivateActCtx'); /// The AddRefActCtx function increments the reference count of the /// specified activation context. /// /// ```c /// void AddRefActCtx( /// HANDLE hActCtx /// ); /// ``` /// {@category kernel32} void AddRefActCtx(int hActCtx) => _AddRefActCtx(hActCtx); late final _AddRefActCtx = _kernel32.lookupFunction< Void Function(IntPtr hActCtx), void Function(int hActCtx)>('AddRefActCtx'); /// Allocates a new console for the calling process. /// /// ```c /// BOOL WINAPI AllocConsole(void); /// ``` /// {@category kernel32} int AllocConsole() => _AllocConsole(); late final _AllocConsole = _kernel32.lookupFunction<Int32 Function(), int Function()>('AllocConsole'); /// Attaches the calling process to the console of the specified process. /// /// ```c /// BOOL WINAPI AttachConsole( /// _In_ DWORD dwProcessId /// ); /// ``` /// {@category kernel32} int AttachConsole(int dwProcessId) => _AttachConsole(dwProcessId); late final _AttachConsole = _kernel32.lookupFunction< Int32 Function(Uint32 dwProcessId), int Function(int dwProcessId)>('AttachConsole'); /// Generates simple tones on the speaker. The function is synchronous; it /// performs an alertable wait and does not return control to its caller /// until the sound finishes. /// /// ```c /// BOOL Beep( /// DWORD dwFreq, /// DWORD dwDuration /// ); /// ``` /// {@category kernel32} int Beep(int dwFreq, int dwDuration) => _Beep(dwFreq, dwDuration); late final _Beep = _kernel32.lookupFunction< Int32 Function(Uint32 dwFreq, Uint32 dwDuration), int Function(int dwFreq, int dwDuration)>('Beep'); /// Retrieves a handle that can be used by the UpdateResource function to /// add, delete, or replace resources in a binary module. /// /// ```c /// HANDLE BeginUpdateResourceW( /// LPCWSTR pFileName, /// BOOL bDeleteExistingResources /// ); /// ``` /// {@category kernel32} int BeginUpdateResource( Pointer<Utf16> pFileName, int bDeleteExistingResources) => _BeginUpdateResource(pFileName, bDeleteExistingResources); late final _BeginUpdateResource = _kernel32.lookupFunction< IntPtr Function(Pointer<Utf16> pFileName, Int32 bDeleteExistingResources), int Function(Pointer<Utf16> pFileName, int bDeleteExistingResources)>('BeginUpdateResourceW'); /// Fills a specified DCB structure with values specified in a /// device-control string. The device-control string uses the syntax of the /// mode command. /// /// ```c /// BOOL BuildCommDCBW( /// LPCWSTR lpDef, /// LPDCB lpDCB /// ); /// ``` /// {@category kernel32} int BuildCommDCB(Pointer<Utf16> lpDef, Pointer<DCB> lpDCB) => _BuildCommDCB(lpDef, lpDCB); late final _BuildCommDCB = _kernel32.lookupFunction< Int32 Function(Pointer<Utf16> lpDef, Pointer<DCB> lpDCB), int Function(Pointer<Utf16> lpDef, Pointer<DCB> lpDCB)>('BuildCommDCBW'); /// Translates a device-definition string into appropriate device-control /// block codes and places them into a device control block. The function /// can also set up time-out values, including the possibility of no /// time-outs, for a device; the function's behavior in this regard depends /// on the contents of the device-definition string. /// /// ```c /// BOOL BuildCommDCBAndTimeoutsW( /// LPCWSTR lpDef, /// LPDCB lpDCB, /// LPCOMMTIMEOUTS lpCommTimeouts /// ); /// ``` /// {@category kernel32} int BuildCommDCBAndTimeouts(Pointer<Utf16> lpDef, Pointer<DCB> lpDCB, Pointer<COMMTIMEOUTS> lpCommTimeouts) => _BuildCommDCBAndTimeouts(lpDef, lpDCB, lpCommTimeouts); late final _BuildCommDCBAndTimeouts = _kernel32.lookupFunction< Int32 Function(Pointer<Utf16> lpDef, Pointer<DCB> lpDCB, Pointer<COMMTIMEOUTS> lpCommTimeouts), int Function(Pointer<Utf16> lpDef, Pointer<DCB> lpDCB, Pointer<COMMTIMEOUTS> lpCommTimeouts)>('BuildCommDCBAndTimeoutsW'); /// Connects to a message-type pipe (and waits if an instance of the pipe /// is not available), writes to and reads from the pipe, and then closes /// the pipe. /// /// ```c /// BOOL CallNamedPipeW( /// LPCWSTR lpNamedPipeName, /// LPVOID lpInBuffer, /// DWORD nInBufferSize, /// LPVOID lpOutBuffer, /// DWORD nOutBufferSize, /// LPDWORD lpBytesRead, /// DWORD nTimeOut /// ); /// ``` /// {@category kernel32} int CallNamedPipe( Pointer<Utf16> lpNamedPipeName, Pointer lpInBuffer, int nInBufferSize, Pointer lpOutBuffer, int nOutBufferSize, Pointer<Uint32> lpBytesRead, int nTimeOut) => _CallNamedPipe(lpNamedPipeName, lpInBuffer, nInBufferSize, lpOutBuffer, nOutBufferSize, lpBytesRead, nTimeOut); late final _CallNamedPipe = _kernel32.lookupFunction< Int32 Function( Pointer<Utf16> lpNamedPipeName, Pointer lpInBuffer, Uint32 nInBufferSize, Pointer lpOutBuffer, Uint32 nOutBufferSize, Pointer<Uint32> lpBytesRead, Uint32 nTimeOut), int Function( Pointer<Utf16> lpNamedPipeName, Pointer lpInBuffer, int nInBufferSize, Pointer lpOutBuffer, int nOutBufferSize, Pointer<Uint32> lpBytesRead, int nTimeOut)>('CallNamedPipeW'); /// Cancels all pending input and output (I/O) operations that are issued /// by the calling thread for the specified file. The function does not /// cancel I/O operations that other threads issue for a file handle. /// /// ```c /// BOOL CancelIo( /// HANDLE hFile /// ); /// ``` /// {@category kernel32} int CancelIo(int hFile) => _CancelIo(hFile); late final _CancelIo = _kernel32.lookupFunction<Int32 Function(IntPtr hFile), int Function(int hFile)>('CancelIo'); /// Marks any outstanding I/O operations for the specified file handle. The /// function only cancels I/O operations in the current process, regardless /// of which thread created the I/O operation. /// /// ```c /// BOOL CancelIoEx( /// HANDLE hFile, /// LPOVERLAPPED lpOverlapped /// ); /// ``` /// {@category kernel32} int CancelIoEx(int hFile, Pointer<OVERLAPPED> lpOverlapped) => _CancelIoEx(hFile, lpOverlapped); late final _CancelIoEx = _kernel32.lookupFunction< Int32 Function(IntPtr hFile, Pointer<OVERLAPPED> lpOverlapped), int Function(int hFile, Pointer<OVERLAPPED> lpOverlapped)>('CancelIoEx'); /// Marks pending synchronous I/O operations that are issued by the /// specified thread as canceled. /// /// ```c /// BOOL CancelSynchronousIo( /// HANDLE hThread /// ); /// ``` /// {@category kernel32} int CancelSynchronousIo(int hThread) => _CancelSynchronousIo(hThread); late final _CancelSynchronousIo = _kernel32.lookupFunction< Int32 Function(IntPtr hThread), int Function(int hThread)>('CancelSynchronousIo'); /// Determines whether the specified process is being debugged. /// /// ```c /// BOOL CheckRemoteDebuggerPresent( /// HANDLE hProcess, /// PBOOL pbDebuggerPresent /// ); /// ``` /// {@category kernel32} int CheckRemoteDebuggerPresent( int hProcess, Pointer<Int32> pbDebuggerPresent) => _CheckRemoteDebuggerPresent(hProcess, pbDebuggerPresent); late final _CheckRemoteDebuggerPresent = _kernel32.lookupFunction< Int32 Function(IntPtr hProcess, Pointer<Int32> pbDebuggerPresent), int Function(int hProcess, Pointer<Int32> pbDebuggerPresent)>('CheckRemoteDebuggerPresent'); /// Restores character transmission for a specified communications device /// and places the transmission line in a nonbreak state. /// /// ```c /// BOOL ClearCommBreak( /// HANDLE hFile /// ); /// ``` /// {@category kernel32} int ClearCommBreak(int hFile) => _ClearCommBreak(hFile); late final _ClearCommBreak = _kernel32.lookupFunction< Int32 Function(IntPtr hFile), int Function(int hFile)>('ClearCommBreak'); /// Retrieves information about a communications error and reports the /// current status of a communications device. The function is called when /// a communications error occurs, and it clears the device's error flag to /// enable additional input and output (I/O) operations. /// /// ```c /// BOOL ClearCommError( /// HANDLE hFile, /// LPDWORD lpErrors, /// LPCOMSTAT lpStat /// ); /// ``` /// {@category kernel32} int ClearCommError( int hFile, Pointer<Uint32> lpErrors, Pointer<COMSTAT> lpStat) => _ClearCommError(hFile, lpErrors, lpStat); late final _ClearCommError = _kernel32.lookupFunction< Int32 Function( IntPtr hFile, Pointer<Uint32> lpErrors, Pointer<COMSTAT> lpStat), int Function(int hFile, Pointer<Uint32> lpErrors, Pointer<COMSTAT> lpStat)>('ClearCommError'); /// Closes an open object handle. /// /// ```c /// BOOL CloseHandle( /// HANDLE hObject /// ); /// ``` /// {@category kernel32} int CloseHandle(int hObject) => _CloseHandle(hObject); late final _CloseHandle = _kernel32.lookupFunction< Int32 Function(IntPtr hObject), int Function(int hObject)>('CloseHandle'); /// Closes a pseudoconsole from the given handle. /// /// ```c /// void WINAPI ClosePseudoConsole( /// _In_ HPCON hPC /// ); /// ``` /// {@category kernel32} void ClosePseudoConsole(int hPC) => _ClosePseudoConsole(hPC); late final _ClosePseudoConsole = _kernel32.lookupFunction<Void Function(IntPtr hPC), void Function(int hPC)>( 'ClosePseudoConsole'); /// Displays a driver-supplied configuration dialog box. /// /// ```c /// BOOL CommConfigDialogW( /// LPCWSTR lpszName, /// HWND hWnd, /// LPCOMMCONFIG lpCC /// ); /// ``` /// {@category kernel32} int CommConfigDialog( Pointer<Utf16> lpszName, int hWnd, Pointer<COMMCONFIG> lpCC) => _CommConfigDialog(lpszName, hWnd, lpCC); late final _CommConfigDialog = _kernel32.lookupFunction< Int32 Function( Pointer<Utf16> lpszName, IntPtr hWnd, Pointer<COMMCONFIG> lpCC), int Function(Pointer<Utf16> lpszName, int hWnd, Pointer<COMMCONFIG> lpCC)>('CommConfigDialogW'); /// Enables a named pipe server process to wait for a client process to /// connect to an instance of a named pipe. A client process connects by /// calling either the CreateFile or CallNamedPipe function. /// /// ```c /// BOOL ConnectNamedPipe( /// HANDLE hNamedPipe, /// LPOVERLAPPED lpOverlapped); /// ``` /// {@category kernel32} int ConnectNamedPipe(int hNamedPipe, Pointer<OVERLAPPED> lpOverlapped) => _ConnectNamedPipe(hNamedPipe, lpOverlapped); late final _ConnectNamedPipe = _kernel32.lookupFunction< Int32 Function(IntPtr hNamedPipe, Pointer<OVERLAPPED> lpOverlapped), int Function( int hNamedPipe, Pointer<OVERLAPPED> lpOverlapped)>('ConnectNamedPipe'); /// Enables a debugger to continue a thread that previously reported a /// debugging event. /// /// ```c /// BOOL ContinueDebugEvent( /// DWORD dwProcessId, /// DWORD dwThreadId, /// DWORD dwContinueStatus /// ); /// ``` /// {@category kernel32} int ContinueDebugEvent(int dwProcessId, int dwThreadId, int dwContinueStatus) => _ContinueDebugEvent(dwProcessId, dwThreadId, dwContinueStatus); late final _ContinueDebugEvent = _kernel32.lookupFunction< Int32 Function( Uint32 dwProcessId, Uint32 dwThreadId, Uint32 dwContinueStatus), int Function(int dwProcessId, int dwThreadId, int dwContinueStatus)>('ContinueDebugEvent'); /// The CreateActCtx function creates an activation context. /// /// ```c /// HANDLE CreateActCtxW( /// PCACTCTXW pActCtx /// ); /// ``` /// {@category kernel32} int CreateActCtx(Pointer<ACTCTX> pActCtx) => _CreateActCtx(pActCtx); late final _CreateActCtx = _kernel32.lookupFunction< IntPtr Function(Pointer<ACTCTX> pActCtx), int Function(Pointer<ACTCTX> pActCtx)>('CreateActCtxW'); /// Creates a console screen buffer. /// /// ```c /// HANDLE WINAPI CreateConsoleScreenBuffer( /// _In_             DWORD               dwDesiredAccess, /// _In_             DWORD               dwShareMode, /// _In_opt_   const SECURITY_ATTRIBUTES *lpSecurityAttributes, /// _In_             DWORD               dwFlags, /// _Reserved_       LPVOID              lpScreenBufferData /// ); /// ``` /// {@category kernel32} int CreateConsoleScreenBuffer( int dwDesiredAccess, int dwShareMode, Pointer<SECURITY_ATTRIBUTES> lpSecurityAttributes, int dwFlags, Pointer lpScreenBufferData) => _CreateConsoleScreenBuffer(dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwFlags, lpScreenBufferData); late final _CreateConsoleScreenBuffer = _kernel32.lookupFunction< IntPtr Function( Uint32 dwDesiredAccess, Uint32 dwShareMode, Pointer<SECURITY_ATTRIBUTES> lpSecurityAttributes, Uint32 dwFlags, Pointer lpScreenBufferData), int Function( int dwDesiredAccess, int dwShareMode, Pointer<SECURITY_ATTRIBUTES> lpSecurityAttributes, int dwFlags, Pointer lpScreenBufferData)>('CreateConsoleScreenBuffer'); /// Creates a new directory. If the underlying file system supports /// security on files and directories, the function applies a specified /// security descriptor to the new directory. /// /// ```c /// BOOL CreateDirectoryW( /// LPCWSTR lpPathName, /// LPSECURITY_ATTRIBUTES lpSecurityAttributes /// ); /// ``` /// {@category kernel32} int CreateDirectory(Pointer<Utf16> lpPathName, Pointer<SECURITY_ATTRIBUTES> lpSecurityAttributes) => _CreateDirectory(lpPathName, lpSecurityAttributes); late final _CreateDirectory = _kernel32.lookupFunction< Int32 Function(Pointer<Utf16> lpPathName, Pointer<SECURITY_ATTRIBUTES> lpSecurityAttributes), int Function(Pointer<Utf16> lpPathName, Pointer<SECURITY_ATTRIBUTES> lpSecurityAttributes)>('CreateDirectoryW'); /// Creates or opens a named or unnamed event object. /// /// ```c /// HANDLE CreateEventW( /// LPSECURITY_ATTRIBUTES lpEventAttributes, /// BOOL bManualReset, /// BOOL bInitialState, /// LPCWSTR lpName /// ); /// ``` /// {@category kernel32} int CreateEvent(Pointer<SECURITY_ATTRIBUTES> lpEventAttributes, int bManualReset, int bInitialState, Pointer<Utf16> lpName) => _CreateEvent(lpEventAttributes, bManualReset, bInitialState, lpName); late final _CreateEvent = _kernel32.lookupFunction< IntPtr Function(Pointer<SECURITY_ATTRIBUTES> lpEventAttributes, Int32 bManualReset, Int32 bInitialState, Pointer<Utf16> lpName), int Function( Pointer<SECURITY_ATTRIBUTES> lpEventAttributes, int bManualReset, int bInitialState, Pointer<Utf16> lpName)>('CreateEventW'); /// Creates or opens a named or unnamed event object and returns a handle /// to the object. /// /// ```c /// HANDLE CreateEventExW( /// LPSECURITY_ATTRIBUTES lpEventAttributes, /// LPCWSTR lpName, /// DWORD dwFlags, /// DWORD dwDesiredAccess /// ); /// ``` /// {@category kernel32} int CreateEventEx(Pointer<SECURITY_ATTRIBUTES> lpEventAttributes, Pointer<Utf16> lpName, int dwFlags, int dwDesiredAccess) => _CreateEventEx(lpEventAttributes, lpName, dwFlags, dwDesiredAccess); late final _CreateEventEx = _kernel32.lookupFunction< IntPtr Function(Pointer<SECURITY_ATTRIBUTES> lpEventAttributes, Pointer<Utf16> lpName, Uint32 dwFlags, Uint32 dwDesiredAccess), int Function( Pointer<SECURITY_ATTRIBUTES> lpEventAttributes, Pointer<Utf16> lpName, int dwFlags, int dwDesiredAccess)>('CreateEventExW'); /// Creates or opens a file or I/O device. The most commonly used I/O /// devices are as follows: file, file stream, directory, physical disk, /// volume, console buffer, tape drive, communications resource, mailslot, /// and pipe. The function returns a handle that can be used to access the /// file or device for various types of I/O depending on the file or device /// and the flags and attributes specified. /// /// ```c /// HANDLE CreateFileW( /// LPCWSTR lpFileName, /// DWORD dwDesiredAccess, /// DWORD dwShareMode, /// LPSECURITY_ATTRIBUTES lpSecurityAttributes, /// DWORD dwCreationDisposition, /// DWORD dwFlagsAndAttributes, /// HANDLE hTemplateFile /// ); /// ``` /// {@category kernel32} int CreateFile( Pointer<Utf16> lpFileName, int dwDesiredAccess, int dwShareMode, Pointer<SECURITY_ATTRIBUTES> lpSecurityAttributes, int dwCreationDisposition, int dwFlagsAndAttributes, int hTemplateFile) => _CreateFile(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile); late final _CreateFile = _kernel32.lookupFunction< IntPtr Function( Pointer<Utf16> lpFileName, Uint32 dwDesiredAccess, Uint32 dwShareMode, Pointer<SECURITY_ATTRIBUTES> lpSecurityAttributes, Uint32 dwCreationDisposition, Uint32 dwFlagsAndAttributes, IntPtr hTemplateFile), int Function( Pointer<Utf16> lpFileName, int dwDesiredAccess, int dwShareMode, Pointer<SECURITY_ATTRIBUTES> lpSecurityAttributes, int dwCreationDisposition, int dwFlagsAndAttributes, int hTemplateFile)>('CreateFileW'); /// Creates an input/output (I/O) completion port and associates it with a /// specified file handle, or creates an I/O completion port that is not /// yet associated with a file handle, allowing association at a later /// time. /// /// ```c /// HANDLE CreateIoCompletionPort( /// HANDLE FileHandle, /// HANDLE ExistingCompletionPort, /// ULONG_PTR CompletionKey, /// DWORD NumberOfConcurrentThreads /// ); /// ``` /// {@category kernel32} int CreateIoCompletionPort(int FileHandle, int ExistingCompletionPort, int CompletionKey, int NumberOfConcurrentThreads) => _CreateIoCompletionPort(FileHandle, ExistingCompletionPort, CompletionKey, NumberOfConcurrentThreads); late final _CreateIoCompletionPort = _kernel32.lookupFunction< IntPtr Function(IntPtr FileHandle, IntPtr ExistingCompletionPort, IntPtr CompletionKey, Uint32 NumberOfConcurrentThreads), int Function(int FileHandle, int ExistingCompletionPort, int CompletionKey, int NumberOfConcurrentThreads)>('CreateIoCompletionPort'); /// Creates an instance of a named pipe and returns a handle for subsequent /// pipe operations. A named pipe server process uses this function either /// to create the first instance of a specific named pipe and establish its /// basic attributes or to create a new instance of an existing named pipe. /// /// ```c /// HANDLE CreateNamedPipeW( /// LPCWSTR lpName, /// DWORD dwOpenMode, /// DWORD dwPipeMode, /// DWORD nMaxInstances, /// DWORD nOutBufferSize, /// DWORD nInBufferSize, /// DWORD nDefaultTimeOut, /// LPSECURITY_ATTRIBUTES lpSecurityAttributes); /// ``` /// {@category kernel32} int CreateNamedPipe( Pointer<Utf16> lpName, int dwOpenMode, int dwPipeMode, int nMaxInstances, int nOutBufferSize, int nInBufferSize, int nDefaultTimeOut, Pointer<SECURITY_ATTRIBUTES> lpSecurityAttributes) => _CreateNamedPipe(lpName, dwOpenMode, dwPipeMode, nMaxInstances, nOutBufferSize, nInBufferSize, nDefaultTimeOut, lpSecurityAttributes); late final _CreateNamedPipe = _kernel32.lookupFunction< IntPtr Function( Pointer<Utf16> lpName, Uint32 dwOpenMode, Uint32 dwPipeMode, Uint32 nMaxInstances, Uint32 nOutBufferSize, Uint32 nInBufferSize, Uint32 nDefaultTimeOut, Pointer<SECURITY_ATTRIBUTES> lpSecurityAttributes), int Function( Pointer<Utf16> lpName, int dwOpenMode, int dwPipeMode, int nMaxInstances, int nOutBufferSize, int nInBufferSize, int nDefaultTimeOut, Pointer<SECURITY_ATTRIBUTES> lpSecurityAttributes)>('CreateNamedPipeW'); /// Creates an anonymous pipe, and returns handles to the read and write /// ends of the pipe. /// /// ```c /// BOOL CreatePipe( /// PHANDLE hReadPipe, /// PHANDLE hWritePipe, /// LPSECURITY_ATTRIBUTES lpPipeAttributes, /// DWORD nSize /// ); /// ``` /// {@category kernel32} int CreatePipe(Pointer<IntPtr> hReadPipe, Pointer<IntPtr> hWritePipe, Pointer<SECURITY_ATTRIBUTES> lpPipeAttributes, int nSize) => _CreatePipe(hReadPipe, hWritePipe, lpPipeAttributes, nSize); late final _CreatePipe = _kernel32.lookupFunction< Int32 Function(Pointer<IntPtr> hReadPipe, Pointer<IntPtr> hWritePipe, Pointer<SECURITY_ATTRIBUTES> lpPipeAttributes, Uint32 nSize), int Function( Pointer<IntPtr> hReadPipe, Pointer<IntPtr> hWritePipe, Pointer<SECURITY_ATTRIBUTES> lpPipeAttributes, int nSize)>('CreatePipe'); /// Creates a new process and its primary thread. The new process runs in /// the security context of the calling process. /// /// ```c /// BOOL CreateProcessW( /// LPCWSTR lpApplicationName, /// LPWSTR lpCommandLine, /// LPSECURITY_ATTRIBUTES lpProcessAttributes, /// LPSECURITY_ATTRIBUTES lpThreadAttributes, /// BOOL bInheritHandles, /// DWORD dwCreationFlags, /// LPVOID lpEnvironment, /// LPCWSTR lpCurrentDirectory, /// LPSTARTUPINFOW lpStartupInfo, /// LPPROCESS_INFORMATION lpProcessInformation /// ); /// ``` /// {@category kernel32} int CreateProcess( Pointer<Utf16> lpApplicationName, Pointer<Utf16> lpCommandLine, Pointer<SECURITY_ATTRIBUTES> lpProcessAttributes, Pointer<SECURITY_ATTRIBUTES> lpThreadAttributes, int bInheritHandles, int dwCreationFlags, Pointer lpEnvironment, Pointer<Utf16> lpCurrentDirectory, Pointer<STARTUPINFO> lpStartupInfo, Pointer<PROCESS_INFORMATION> lpProcessInformation) => _CreateProcess( lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bInheritHandles, dwCreationFlags, lpEnvironment, lpCurrentDirectory, lpStartupInfo, lpProcessInformation); late final _CreateProcess = _kernel32.lookupFunction< Int32 Function( Pointer<Utf16> lpApplicationName, Pointer<Utf16> lpCommandLine, Pointer<SECURITY_ATTRIBUTES> lpProcessAttributes, Pointer<SECURITY_ATTRIBUTES> lpThreadAttributes, Int32 bInheritHandles, Uint32 dwCreationFlags, Pointer lpEnvironment, Pointer<Utf16> lpCurrentDirectory, Pointer<STARTUPINFO> lpStartupInfo, Pointer<PROCESS_INFORMATION> lpProcessInformation), int Function( Pointer<Utf16> lpApplicationName, Pointer<Utf16> lpCommandLine, Pointer<SECURITY_ATTRIBUTES> lpProcessAttributes, Pointer<SECURITY_ATTRIBUTES> lpThreadAttributes, int bInheritHandles, int dwCreationFlags, Pointer lpEnvironment, Pointer<Utf16> lpCurrentDirectory, Pointer<STARTUPINFO> lpStartupInfo, Pointer<PROCESS_INFORMATION> lpProcessInformation)>('CreateProcessW'); /// Creates a new pseudoconsole object for the calling process. /// /// ```c /// HRESULT WINAPI CreatePseudoConsole( /// _In_ COORD size, /// _In_ HANDLE hInput, /// _In_ HANDLE hOutput, /// _In_ DWORD dwFlags, /// _Out_ HPCON* phPC /// ); /// ``` /// {@category kernel32} int CreatePseudoConsole(COORD size, int hInput, int hOutput, int dwFlags, Pointer<IntPtr> phPC) => _CreatePseudoConsole(size, hInput, hOutput, dwFlags, phPC); late final _CreatePseudoConsole = _kernel32.lookupFunction< Int32 Function(COORD size, IntPtr hInput, IntPtr hOutput, Uint32 dwFlags, Pointer<IntPtr> phPC), int Function(COORD size, int hInput, int hOutput, int dwFlags, Pointer<IntPtr> phPC)>('CreatePseudoConsole'); /// Creates a thread that runs in the virtual address space of another /// process. Use the CreateRemoteThreadEx function to create a thread that /// runs in the virtual address space of another process and optionally /// specify extended attributes. /// /// ```c /// HANDLE CreateRemoteThread( /// HANDLE hProcess, /// LPSECURITY_ATTRIBUTES lpThreadAttributes, /// SIZE_T dwStackSize, /// LPTHREAD_START_ROUTINE lpStartAddress, /// LPVOID lpParameter, /// DWORD dwCreationFlags, /// LPDWORD lpThreadId /// ); /// ``` /// {@category kernel32} int CreateRemoteThread( int hProcess, Pointer<SECURITY_ATTRIBUTES> lpThreadAttributes, int dwStackSize, Pointer<NativeFunction<ThreadProc>> lpStartAddress, Pointer lpParameter, int dwCreationFlags, Pointer<Uint32> lpThreadId) => _CreateRemoteThread(hProcess, lpThreadAttributes, dwStackSize, lpStartAddress, lpParameter, dwCreationFlags, lpThreadId); late final _CreateRemoteThread = _kernel32.lookupFunction< IntPtr Function( IntPtr hProcess, Pointer<SECURITY_ATTRIBUTES> lpThreadAttributes, IntPtr dwStackSize, Pointer<NativeFunction<ThreadProc>> lpStartAddress, Pointer lpParameter, Uint32 dwCreationFlags, Pointer<Uint32> lpThreadId), int Function( int hProcess, Pointer<SECURITY_ATTRIBUTES> lpThreadAttributes, int dwStackSize, Pointer<NativeFunction<ThreadProc>> lpStartAddress, Pointer lpParameter, int dwCreationFlags, Pointer<Uint32> lpThreadId)>('CreateRemoteThread'); /// Creates a thread that runs in the virtual address space of another /// process and optionally specifies extended attributes such as processor /// group affinity. /// /// ```c /// HANDLE CreateRemoteThreadEx( /// HANDLE hProcess, /// LPSECURITY_ATTRIBUTES lpThreadAttributes, /// SIZE_T dwStackSize, /// LPTHREAD_START_ROUTINE lpStartAddress, /// LPVOID lpParameter, /// DWORD dwCreationFlags, /// LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList, /// LPDWORD lpThreadId /// ); /// ``` /// {@category kernel32} int CreateRemoteThreadEx( int hProcess, Pointer<SECURITY_ATTRIBUTES> lpThreadAttributes, int dwStackSize, Pointer<NativeFunction<ThreadProc>> lpStartAddress, Pointer lpParameter, int dwCreationFlags, Pointer lpAttributeList, Pointer<Uint32> lpThreadId) => _CreateRemoteThreadEx( hProcess, lpThreadAttributes, dwStackSize, lpStartAddress, lpParameter, dwCreationFlags, lpAttributeList, lpThreadId); late final _CreateRemoteThreadEx = _kernel32.lookupFunction< IntPtr Function( IntPtr hProcess, Pointer<SECURITY_ATTRIBUTES> lpThreadAttributes, IntPtr dwStackSize, Pointer<NativeFunction<ThreadProc>> lpStartAddress, Pointer lpParameter, Uint32 dwCreationFlags, Pointer lpAttributeList, Pointer<Uint32> lpThreadId), int Function( int hProcess, Pointer<SECURITY_ATTRIBUTES> lpThreadAttributes, int dwStackSize, Pointer<NativeFunction<ThreadProc>> lpStartAddress, Pointer lpParameter, int dwCreationFlags, Pointer lpAttributeList, Pointer<Uint32> lpThreadId)>('CreateRemoteThreadEx'); /// Creates a thread to execute within the virtual address space of the /// calling process. /// /// ```c /// HANDLE CreateThread( /// LPSECURITY_ATTRIBUTES lpThreadAttributes, /// SIZE_T dwStackSize, /// LPTHREAD_START_ROUTINE lpStartAddress, /// LPVOID lpParameter, /// DWORD dwCreationFlags, /// LPDWORD lpThreadId /// ); /// ``` /// {@category kernel32} int CreateThread( Pointer<SECURITY_ATTRIBUTES> lpThreadAttributes, int dwStackSize, Pointer<NativeFunction<ThreadProc>> lpStartAddress, Pointer lpParameter, int dwCreationFlags, Pointer<Uint32> lpThreadId) => _CreateThread(lpThreadAttributes, dwStackSize, lpStartAddress, lpParameter, dwCreationFlags, lpThreadId); late final _CreateThread = _kernel32.lookupFunction< IntPtr Function( Pointer<SECURITY_ATTRIBUTES> lpThreadAttributes, IntPtr dwStackSize, Pointer<NativeFunction<ThreadProc>> lpStartAddress, Pointer lpParameter, Uint32 dwCreationFlags, Pointer<Uint32> lpThreadId), int Function( Pointer<SECURITY_ATTRIBUTES> lpThreadAttributes, int dwStackSize, Pointer<NativeFunction<ThreadProc>> lpStartAddress, Pointer lpParameter, int dwCreationFlags, Pointer<Uint32> lpThreadId)>('CreateThread'); /// The DeactivateActCtx function deactivates the activation context /// corresponding to the specified cookie. /// /// ```c /// BOOL DeactivateActCtx( /// DWORD dwFlags, /// ULONG_PTR ulCookie /// ); /// ``` /// {@category kernel32} int DeactivateActCtx(int dwFlags, int ulCookie) => _DeactivateActCtx(dwFlags, ulCookie); late final _DeactivateActCtx = _kernel32.lookupFunction< Int32 Function(Uint32 dwFlags, IntPtr ulCookie), int Function(int dwFlags, int ulCookie)>('DeactivateActCtx'); /// Causes a breakpoint exception to occur in the current process. This /// allows the calling thread to signal the debugger to handle the /// exception. /// /// ```c /// void DebugBreak(); /// ``` /// {@category kernel32} void DebugBreak() => _DebugBreak(); late final _DebugBreak = _kernel32.lookupFunction<Void Function(), void Function()>('DebugBreak'); /// Causes a breakpoint exception to occur in the specified process. This /// allows the calling thread to signal the debugger to handle the /// exception. /// /// ```c /// BOOL DebugBreakProcess( /// HANDLE Process /// ); /// ``` /// {@category kernel32} int DebugBreakProcess(int Process) => _DebugBreakProcess(Process); late final _DebugBreakProcess = _kernel32.lookupFunction< Int32 Function(IntPtr Process), int Function(int Process)>('DebugBreakProcess'); /// Sets the action to be performed when the calling thread exits. /// /// ```c /// BOOL DebugSetProcessKillOnExit( /// BOOL KillOnExit /// ); /// ``` /// {@category kernel32} int DebugSetProcessKillOnExit(int KillOnExit) => _DebugSetProcessKillOnExit(KillOnExit); late final _DebugSetProcessKillOnExit = _kernel32.lookupFunction< Int32 Function(Int32 KillOnExit), int Function(int KillOnExit)>('DebugSetProcessKillOnExit'); /// Deletes an existing file. /// /// ```c /// BOOL DeleteFileW( /// LPCWSTR lpFileName /// ); /// ``` /// {@category kernel32} int DeleteFile(Pointer<Utf16> lpFileName) => _DeleteFile(lpFileName); late final _DeleteFile = _kernel32.lookupFunction< Int32 Function(Pointer<Utf16> lpFileName), int Function(Pointer<Utf16> lpFileName)>('DeleteFileW'); /// Sends a control code directly to a specified device driver, causing the /// corresponding device to perform the corresponding operation. /// /// ```c /// BOOL DeviceIoControl( /// HANDLE hDevice, /// DWORD dwIoControlCode, /// LPVOID lpInBuffer, /// DWORD nInBufferSize, /// LPVOID lpOutBuffer, /// DWORD nOutBufferSize, /// LPDWORD lpBytesReturned, /// LPOVERLAPPED lpOverlapped /// ); /// ``` /// {@category kernel32} int DeviceIoControl( int hDevice, int dwIoControlCode, Pointer lpInBuffer, int nInBufferSize, Pointer lpOutBuffer, int nOutBufferSize, Pointer<Uint32> lpBytesReturned, Pointer<OVERLAPPED> lpOverlapped) => _DeviceIoControl(hDevice, dwIoControlCode, lpInBuffer, nInBufferSize, lpOutBuffer, nOutBufferSize, lpBytesReturned, lpOverlapped); late final _DeviceIoControl = _kernel32.lookupFunction< Int32 Function( IntPtr hDevice, Uint32 dwIoControlCode, Pointer lpInBuffer, Uint32 nInBufferSize, Pointer lpOutBuffer, Uint32 nOutBufferSize, Pointer<Uint32> lpBytesReturned, Pointer<OVERLAPPED> lpOverlapped), int Function( int hDevice, int dwIoControlCode, Pointer lpInBuffer, int nInBufferSize, Pointer lpOutBuffer, int nOutBufferSize, Pointer<Uint32> lpBytesReturned, Pointer<OVERLAPPED> lpOverlapped)>('DeviceIoControl'); /// Disconnects the server end of a named pipe instance from a client /// process. /// /// ```c /// BOOL DisconnectNamedPipe( /// HANDLE hNamedPipe); /// ``` /// {@category kernel32} int DisconnectNamedPipe(int hNamedPipe) => _DisconnectNamedPipe(hNamedPipe); late final _DisconnectNamedPipe = _kernel32.lookupFunction< Int32 Function(IntPtr hNamedPipe), int Function(int hNamedPipe)>('DisconnectNamedPipe'); /// Converts a DNS-style host name to a NetBIOS-style computer name. /// /// ```c /// BOOL DnsHostnameToComputerNameW( /// LPCWSTR Hostname, /// LPWSTR ComputerName, /// LPDWORD nSize /// ); /// ``` /// {@category kernel32} int DnsHostnameToComputerName(Pointer<Utf16> Hostname, Pointer<Utf16> ComputerName, Pointer<Uint32> nSize) => _DnsHostnameToComputerName(Hostname, ComputerName, nSize); late final _DnsHostnameToComputerName = _kernel32.lookupFunction< Int32 Function(Pointer<Utf16> Hostname, Pointer<Utf16> ComputerName, Pointer<Uint32> nSize), int Function(Pointer<Utf16> Hostname, Pointer<Utf16> ComputerName, Pointer<Uint32> nSize)>('DnsHostnameToComputerNameW'); /// Converts MS-DOS date and time values to a file time. /// /// ```c /// BOOL DosDateTimeToFileTime( /// WORD wFatDate, /// WORD wFatTime, /// LPFILETIME lpFileTime /// ); /// ``` /// {@category kernel32} int DosDateTimeToFileTime( int wFatDate, int wFatTime, Pointer<FILETIME> lpFileTime) => _DosDateTimeToFileTime(wFatDate, wFatTime, lpFileTime); late final _DosDateTimeToFileTime = _kernel32.lookupFunction< Int32 Function( Uint16 wFatDate, Uint16 wFatTime, Pointer<FILETIME> lpFileTime), int Function(int wFatDate, int wFatTime, Pointer<FILETIME> lpFileTime)>('DosDateTimeToFileTime'); /// Duplicates an object handle. /// /// ```c /// BOOL DuplicateHandle( /// HANDLE hSourceProcessHandle, /// HANDLE hSourceHandle, /// HANDLE hTargetProcessHandle, /// LPHANDLE lpTargetHandle, /// DWORD dwDesiredAccess, /// BOOL bInheritHandle, /// DWORD dwOptions /// ); /// ``` /// {@category kernel32} int DuplicateHandle( int hSourceProcessHandle, int hSourceHandle, int hTargetProcessHandle, Pointer<IntPtr> lpTargetHandle, int dwDesiredAccess, int bInheritHandle, int dwOptions) => _DuplicateHandle(hSourceProcessHandle, hSourceHandle, hTargetProcessHandle, lpTargetHandle, dwDesiredAccess, bInheritHandle, dwOptions); late final _DuplicateHandle = _kernel32.lookupFunction< Int32 Function( IntPtr hSourceProcessHandle, IntPtr hSourceHandle, IntPtr hTargetProcessHandle, Pointer<IntPtr> lpTargetHandle, Uint32 dwDesiredAccess, Int32 bInheritHandle, Uint32 dwOptions), int Function( int hSourceProcessHandle, int hSourceHandle, int hTargetProcessHandle, Pointer<IntPtr> lpTargetHandle, int dwDesiredAccess, int bInheritHandle, int dwOptions)>('DuplicateHandle'); /// Commits or discards changes made prior to a call to UpdateResource. /// /// ```c /// BOOL EndUpdateResourceW( /// HANDLE hUpdate, /// BOOL fDiscard /// ); /// ``` /// {@category kernel32} int EndUpdateResource(int hUpdate, int fDiscard) => _EndUpdateResource(hUpdate, fDiscard); late final _EndUpdateResource = _kernel32.lookupFunction< Int32 Function(IntPtr hUpdate, Int32 fDiscard), int Function(int hUpdate, int fDiscard)>('EndUpdateResourceW'); /// Retrieves the process identifier for each process object in the system. /// /// ```c /// BOOL K32EnumProcesses( /// DWORD *lpidProcess, /// DWORD cb, /// LPDWORD lpcbNeeded /// ); /// ``` /// {@category kernel32} int EnumProcesses( Pointer<Uint32> lpidProcess, int cb, Pointer<Uint32> lpcbNeeded) => _K32EnumProcesses(lpidProcess, cb, lpcbNeeded); late final _K32EnumProcesses = _kernel32.lookupFunction< Int32 Function( Pointer<Uint32> lpidProcess, Uint32 cb, Pointer<Uint32> lpcbNeeded), int Function(Pointer<Uint32> lpidProcess, int cb, Pointer<Uint32> lpcbNeeded)>('K32EnumProcesses'); /// Retrieves a handle for each module in the specified process. /// /// ```c /// BOOL K32EnumProcessModules( /// HANDLE hProcess, /// HMODULE *lphModule, /// DWORD cb, /// LPDWORD lpcbNeeded /// ); /// ``` /// {@category kernel32} int EnumProcessModules(int hProcess, Pointer<IntPtr> lphModule, int cb, Pointer<Uint32> lpcbNeeded) => _K32EnumProcessModules(hProcess, lphModule, cb, lpcbNeeded); late final _K32EnumProcessModules = _kernel32.lookupFunction< Int32 Function(IntPtr hProcess, Pointer<IntPtr> lphModule, Uint32 cb, Pointer<Uint32> lpcbNeeded), int Function(int hProcess, Pointer<IntPtr> lphModule, int cb, Pointer<Uint32> lpcbNeeded)>('K32EnumProcessModules'); /// Retrieves a handle for each module in the specified process that meets /// the specified filter criteria. /// /// ```c /// BOOL K32EnumProcessModulesEx( /// HANDLE hProcess, /// HMODULE *lphModule, /// DWORD cb, /// LPDWORD lpcbNeeded, /// DWORD dwFilterFlag /// ); /// ``` /// {@category kernel32} int EnumProcessModulesEx(int hProcess, Pointer<IntPtr> lphModule, int cb, Pointer<Uint32> lpcbNeeded, int dwFilterFlag) => _K32EnumProcessModulesEx(hProcess, lphModule, cb, lpcbNeeded, dwFilterFlag); late final _K32EnumProcessModulesEx = _kernel32.lookupFunction< Int32 Function(IntPtr hProcess, Pointer<IntPtr> lphModule, Uint32 cb, Pointer<Uint32> lpcbNeeded, Uint32 dwFilterFlag), int Function( int hProcess, Pointer<IntPtr> lphModule, int cb, Pointer<Uint32> lpcbNeeded, int dwFilterFlag)>('K32EnumProcessModulesEx'); /// Enumerates resources of a specified type within a binary module. For /// Windows Vista and later, this is typically a language-neutral Portable /// Executable (LN file), and the enumeration will also include resources /// from the corresponding language-specific resource files (.mui files) /// that contain localizable language resources. It is also possible for /// hModule to specify an .mui file, in which case only that file is /// searched for resources. /// /// ```c /// BOOL EnumResourceNamesW( /// HMODULE hModule, /// LPCWSTR lpType, /// ENUMRESNAMEPROCW lpEnumFunc, /// LONG_PTR lParam /// ); /// ``` /// {@category kernel32} int EnumResourceNames(int hModule, Pointer<Utf16> lpType, Pointer<NativeFunction<EnumResNameProc>> lpEnumFunc, int lParam) => _EnumResourceNames(hModule, lpType, lpEnumFunc, lParam); late final _EnumResourceNames = _kernel32.lookupFunction< Int32 Function(IntPtr hModule, Pointer<Utf16> lpType, Pointer<NativeFunction<EnumResNameProc>> lpEnumFunc, IntPtr lParam), int Function( int hModule, Pointer<Utf16> lpType, Pointer<NativeFunction<EnumResNameProc>> lpEnumFunc, int lParam)>('EnumResourceNamesW'); /// Enumerates resource types within a binary module. Starting with Windows /// Vista, this is typically a language-neutral Portable Executable (LN /// file), and the enumeration also includes resources from one of the /// corresponding language-specific resource files (.mui files)—if one /// exists—that contain localizable language resources. It is also possible /// to use hModule to specify a .mui file, in which case only that file is /// searched for resource types. /// /// ```c /// BOOL EnumResourceTypesW( /// HMODULE hModule, /// ENUMRESTYPEPROCW lpEnumFunc, /// LONG_PTR lParam /// ); /// ``` /// {@category kernel32} int EnumResourceTypes(int hModule, Pointer<NativeFunction<EnumResTypeProc>> lpEnumFunc, int lParam) => _EnumResourceTypes(hModule, lpEnumFunc, lParam); late final _EnumResourceTypes = _kernel32.lookupFunction< Int32 Function(IntPtr hModule, Pointer<NativeFunction<EnumResTypeProc>> lpEnumFunc, IntPtr lParam), int Function( int hModule, Pointer<NativeFunction<EnumResTypeProc>> lpEnumFunc, int lParam)>('EnumResourceTypesW'); /// Directs the specified communications device to perform an extended /// function. /// /// ```c /// BOOL EscapeCommFunction( /// HANDLE hFile, /// DWORD dwFunc /// ); /// ``` /// {@category kernel32} int EscapeCommFunction(int hFile, int dwFunc) => _EscapeCommFunction(hFile, dwFunc); late final _EscapeCommFunction = _kernel32.lookupFunction< Int32 Function(IntPtr hFile, Uint32 dwFunc), int Function(int hFile, int dwFunc)>('EscapeCommFunction'); /// Ends the calling process and all its threads. /// /// ```c /// void ExitProcess( /// UINT uExitCode /// ); /// ``` /// {@category kernel32} void ExitProcess(int uExitCode) => _ExitProcess(uExitCode); late final _ExitProcess = _kernel32.lookupFunction< Void Function(Uint32 uExitCode), void Function(int uExitCode)>('ExitProcess'); /// Ends the calling thread. /// /// ```c /// void ExitThread( /// DWORD dwExitCode /// ); /// ``` /// {@category kernel32} void ExitThread(int dwExitCode) => _ExitThread(dwExitCode); late final _ExitThread = _kernel32.lookupFunction< Void Function(Uint32 dwExitCode), void Function(int dwExitCode)>('ExitThread'); /// Converts a file time to MS-DOS date and time values. /// /// ```c /// BOOL FileTimeToDosDateTime( /// const FILETIME *lpFileTime, /// LPWORD lpFatDate, /// LPWORD lpFatTime /// ); /// ``` /// {@category kernel32} int FileTimeToDosDateTime(Pointer<FILETIME> lpFileTime, Pointer<Uint16> lpFatDate, Pointer<Uint16> lpFatTime) => _FileTimeToDosDateTime(lpFileTime, lpFatDate, lpFatTime); late final _FileTimeToDosDateTime = _kernel32.lookupFunction< Int32 Function(Pointer<FILETIME> lpFileTime, Pointer<Uint16> lpFatDate, Pointer<Uint16> lpFatTime), int Function(Pointer<FILETIME> lpFileTime, Pointer<Uint16> lpFatDate, Pointer<Uint16> lpFatTime)>('FileTimeToDosDateTime'); /// Sets the character attributes for a specified number of character /// cells, beginning at the specified coordinates in a screen buffer. /// /// ```c /// BOOL WINAPI FillConsoleOutputAttribute( /// _In_ HANDLE hConsoleOutput, /// _In_ WORD wAttribute, /// _In_ DWORD nLength, /// _In_ COORD dwWriteCoord, /// _Out_ LPDWORD lpNumberOfAttrsWritten /// ); /// ``` /// {@category kernel32} int FillConsoleOutputAttribute(int hConsoleOutput, int wAttribute, int nLength, COORD dwWriteCoord, Pointer<Uint32> lpNumberOfAttrsWritten) => _FillConsoleOutputAttribute(hConsoleOutput, wAttribute, nLength, dwWriteCoord, lpNumberOfAttrsWritten); late final _FillConsoleOutputAttribute = _kernel32.lookupFunction< Int32 Function(IntPtr hConsoleOutput, Uint16 wAttribute, Uint32 nLength, COORD dwWriteCoord, Pointer<Uint32> lpNumberOfAttrsWritten), int Function( int hConsoleOutput, int wAttribute, int nLength, COORD dwWriteCoord, Pointer<Uint32> lpNumberOfAttrsWritten)>('FillConsoleOutputAttribute'); /// Writes a character to the console screen buffer a specified number of /// times, beginning at the specified coordinates. /// /// ```c /// BOOL WINAPI FillConsoleOutputCharacterW( /// _In_ HANDLE hConsoleOutput, /// _In_ WCHAR cCharacter, /// _In_ DWORD nLength, /// _In_ COORD dwWriteCoord, /// _Out_ LPDWORD lpNumberOfCharsWritten /// ); /// ``` /// {@category kernel32} int FillConsoleOutputCharacter(int hConsoleOutput, int cCharacter, int nLength, COORD dwWriteCoord, Pointer<Uint32> lpNumberOfCharsWritten) => _FillConsoleOutputCharacter(hConsoleOutput, cCharacter, nLength, dwWriteCoord, lpNumberOfCharsWritten); late final _FillConsoleOutputCharacter = _kernel32.lookupFunction< Int32 Function(IntPtr hConsoleOutput, Uint16 cCharacter, Uint32 nLength, COORD dwWriteCoord, Pointer<Uint32> lpNumberOfCharsWritten), int Function( int hConsoleOutput, int cCharacter, int nLength, COORD dwWriteCoord, Pointer<Uint32> lpNumberOfCharsWritten)>('FillConsoleOutputCharacterW'); /// Closes a file search handle opened by the FindFirstFile, /// FindFirstFileEx, FindFirstFileNameW, FindFirstFileNameTransactedW, /// FindFirstFileTransacted, FindFirstStreamTransactedW, or /// FindFirstStreamW functions. /// /// ```c /// BOOL FindClose( /// HANDLE hFindFile /// ); /// ``` /// {@category kernel32} int FindClose(int hFindFile) => _FindClose(hFindFile); late final _FindClose = _kernel32.lookupFunction< Int32 Function(IntPtr hFindFile), int Function(int hFindFile)>('FindClose'); /// Stops change notification handle monitoring. /// /// ```c /// BOOL FindCloseChangeNotification( /// HANDLE hChangeHandle /// ); /// ``` /// {@category kernel32} int FindCloseChangeNotification(int hChangeHandle) => _FindCloseChangeNotification(hChangeHandle); late final _FindCloseChangeNotification = _kernel32.lookupFunction< Int32 Function(IntPtr hChangeHandle), int Function(int hChangeHandle)>('FindCloseChangeNotification'); /// Creates a change notification handle and sets up initial change /// notification filter conditions. A wait on a notification handle /// succeeds when a change matching the filter conditions occurs in the /// specified directory or subtree. The function does not report changes to /// the specified directory itself. /// /// ```c /// HANDLE FindFirstChangeNotificationW( /// LPCWSTR lpPathName, /// BOOL bWatchSubtree, /// DWORD dwNotifyFilter /// ); /// ``` /// {@category kernel32} int FindFirstChangeNotification( Pointer<Utf16> lpPathName, int bWatchSubtree, int dwNotifyFilter) => _FindFirstChangeNotification(lpPathName, bWatchSubtree, dwNotifyFilter); late final _FindFirstChangeNotification = _kernel32.lookupFunction< IntPtr Function( Pointer<Utf16> lpPathName, Int32 bWatchSubtree, Uint32 dwNotifyFilter), int Function(Pointer<Utf16> lpPathName, int bWatchSubtree, int dwNotifyFilter)>('FindFirstChangeNotificationW'); /// Searches a directory for a file or subdirectory with a name that /// matches a specific name (or partial name if wildcards are used). /// /// ```c /// HANDLE FindFirstFileW( /// LPCWSTR lpFileName, /// LPWIN32_FIND_DATAW lpFindFileData /// ); /// ``` /// {@category kernel32} int FindFirstFile( Pointer<Utf16> lpFileName, Pointer<WIN32_FIND_DATA> lpFindFileData) => _FindFirstFile(lpFileName, lpFindFileData); late final _FindFirstFile = _kernel32.lookupFunction< IntPtr Function( Pointer<Utf16> lpFileName, Pointer<WIN32_FIND_DATA> lpFindFileData), int Function(Pointer<Utf16> lpFileName, Pointer<WIN32_FIND_DATA> lpFindFileData)>('FindFirstFileW'); /// Retrieves the name of a volume on a computer. FindFirstVolume is used /// to begin scanning the volumes of a computer. /// /// ```c /// HANDLE FindFirstVolumeW( /// LPWSTR lpszVolumeName, /// DWORD cchBufferLength /// ); /// ``` /// {@category kernel32} int FindFirstVolume(Pointer<Utf16> lpszVolumeName, int cchBufferLength) => _FindFirstVolume(lpszVolumeName, cchBufferLength); late final _FindFirstVolume = _kernel32.lookupFunction< IntPtr Function(Pointer<Utf16> lpszVolumeName, Uint32 cchBufferLength), int Function(Pointer<Utf16> lpszVolumeName, int cchBufferLength)>('FindFirstVolumeW'); /// Requests that the operating system signal a change notification handle /// the next time it detects an appropriate change. /// /// ```c /// BOOL FindNextChangeNotification( /// HANDLE hChangeHandle /// ); /// ``` /// {@category kernel32} int FindNextChangeNotification(int hChangeHandle) => _FindNextChangeNotification(hChangeHandle); late final _FindNextChangeNotification = _kernel32.lookupFunction< Int32 Function(IntPtr hChangeHandle), int Function(int hChangeHandle)>('FindNextChangeNotification'); /// Continues a file search from a previous call to the FindFirstFile, /// FindFirstFileEx, or FindFirstFileTransacted functions. /// /// ```c /// BOOL FindNextFileW( /// HANDLE hFindFile, /// LPWIN32_FIND_DATAW lpFindFileData /// ); /// ``` /// {@category kernel32} int FindNextFile(int hFindFile, Pointer<WIN32_FIND_DATA> lpFindFileData) => _FindNextFile(hFindFile, lpFindFileData); late final _FindNextFile = _kernel32.lookupFunction< Int32 Function(IntPtr hFindFile, Pointer<WIN32_FIND_DATA> lpFindFileData), int Function(int hFindFile, Pointer<WIN32_FIND_DATA> lpFindFileData)>('FindNextFileW'); /// Continues a volume search started by a call to the FindFirstVolume /// function. FindNextVolume finds one volume per call. /// /// ```c /// BOOL FindNextVolumeW( /// HANDLE hFindVolume, /// LPWSTR lpszVolumeName, /// DWORD cchBufferLength /// ); /// ``` /// {@category kernel32} int FindNextVolume( int hFindVolume, Pointer<Utf16> lpszVolumeName, int cchBufferLength) => _FindNextVolume(hFindVolume, lpszVolumeName, cchBufferLength); late final _FindNextVolume = _kernel32.lookupFunction< Int32 Function(IntPtr hFindVolume, Pointer<Utf16> lpszVolumeName, Uint32 cchBufferLength), int Function(int hFindVolume, Pointer<Utf16> lpszVolumeName, int cchBufferLength)>('FindNextVolumeW'); /// Finds the packages with the specified family name for the current user. /// /// ```c /// LONG FindPackagesByPackageFamily( /// PCWSTR packageFamilyName, /// UINT32 packageFilters, /// UINT32 *count, /// PWSTR *packageFullNames, /// UINT32 *bufferLength, /// WCHAR *buffer, /// UINT32 *packageProperties /// ); /// ``` /// {@category kernel32} int FindPackagesByPackageFamily( Pointer<Utf16> packageFamilyName, int packageFilters, Pointer<Uint32> count, Pointer<Pointer<Utf16>> packageFullNames, Pointer<Uint32> bufferLength, Pointer<Utf16> buffer, Pointer<Uint32> packageProperties) => _FindPackagesByPackageFamily(packageFamilyName, packageFilters, count, packageFullNames, bufferLength, buffer, packageProperties); late final _FindPackagesByPackageFamily = _kernel32.lookupFunction< Int32 Function( Pointer<Utf16> packageFamilyName, Uint32 packageFilters, Pointer<Uint32> count, Pointer<Pointer<Utf16>> packageFullNames, Pointer<Uint32> bufferLength, Pointer<Utf16> buffer, Pointer<Uint32> packageProperties), int Function( Pointer<Utf16> packageFamilyName, int packageFilters, Pointer<Uint32> count, Pointer<Pointer<Utf16>> packageFullNames, Pointer<Uint32> bufferLength, Pointer<Utf16> buffer, Pointer<Uint32> packageProperties)>('FindPackagesByPackageFamily'); /// Determines the location of a resource with the specified type and name /// in the specified module. /// /// ```c /// HRSRC FindResourceW( /// HMODULE hModule, /// LPCWSTR lpName, /// LPCWSTR lpType /// ); /// ``` /// {@category kernel32} int FindResource(int hModule, Pointer<Utf16> lpName, Pointer<Utf16> lpType) => _FindResource(hModule, lpName, lpType); late final _FindResource = _kernel32.lookupFunction< IntPtr Function( IntPtr hModule, Pointer<Utf16> lpName, Pointer<Utf16> lpType), int Function(int hModule, Pointer<Utf16> lpName, Pointer<Utf16> lpType)>('FindResourceW'); /// Determines the location of the resource with the specified type, name, /// and language in the specified module. /// /// ```c /// HRSRC FindResourceExW( /// HMODULE hModule, /// LPCWSTR lpType, /// LPCWSTR lpName, /// WORD wLanguage /// ); /// ``` /// {@category kernel32} int FindResourceEx(int hModule, Pointer<Utf16> lpType, Pointer<Utf16> lpName, int wLanguage) => _FindResourceEx(hModule, lpType, lpName, wLanguage); late final _FindResourceEx = _kernel32.lookupFunction< IntPtr Function(IntPtr hModule, Pointer<Utf16> lpType, Pointer<Utf16> lpName, Uint16 wLanguage), int Function(int hModule, Pointer<Utf16> lpType, Pointer<Utf16> lpName, int wLanguage)>('FindResourceExW'); /// Closes the specified volume search handle. The FindFirstVolume and /// FindNextVolume functions use this search handle to locate volumes. /// /// ```c /// BOOL FindVolumeClose( /// HANDLE hFindVolume /// ); /// ``` /// {@category kernel32} int FindVolumeClose(int hFindVolume) => _FindVolumeClose(hFindVolume); late final _FindVolumeClose = _kernel32.lookupFunction< Int32 Function(IntPtr hFindVolume), int Function(int hFindVolume)>('FindVolumeClose'); /// Flushes the console input buffer. All input records currently in the /// input buffer are discarded. /// /// ```c /// BOOL WINAPI FlushConsoleInputBuffer( /// _In_ HANDLE hConsoleInput /// ); /// ``` /// {@category kernel32} int FlushConsoleInputBuffer(int hConsoleInput) => _FlushConsoleInputBuffer(hConsoleInput); late final _FlushConsoleInputBuffer = _kernel32.lookupFunction< Int32 Function(IntPtr hConsoleInput), int Function(int hConsoleInput)>('FlushConsoleInputBuffer'); /// Formats a message string. The function requires a message definition as /// input. The message definition can come from a buffer passed into the /// function. It can come from a message table resource in an /// already-loaded module. Or the caller can ask the function to search the /// system's message table resource(s) for the message definition. The /// function finds the message definition in a message table resource based /// on a message identifier and a language identifier. The function copies /// the formatted message text to an output buffer, processing any embedded /// insert sequences if requested. /// /// ```c /// DWORD FormatMessageW( /// DWORD dwFlags, /// LPCVOID lpSource, /// DWORD dwMessageId, /// DWORD dwLanguageId, /// LPWSTR lpBuffer, /// DWORD nSize, /// va_list *Arguments /// ); /// ``` /// {@category kernel32} int FormatMessage( int dwFlags, Pointer lpSource, int dwMessageId, int dwLanguageId, Pointer<Utf16> lpBuffer, int nSize, Pointer<Pointer<Int8>> Arguments) => _FormatMessage(dwFlags, lpSource, dwMessageId, dwLanguageId, lpBuffer, nSize, Arguments); late final _FormatMessage = _kernel32.lookupFunction< Uint32 Function( Uint32 dwFlags, Pointer lpSource, Uint32 dwMessageId, Uint32 dwLanguageId, Pointer<Utf16> lpBuffer, Uint32 nSize, Pointer<Pointer<Int8>> Arguments), int Function( int dwFlags, Pointer lpSource, int dwMessageId, int dwLanguageId, Pointer<Utf16> lpBuffer, int nSize, Pointer<Pointer<Int8>> Arguments)>('FormatMessageW'); /// Detaches the calling process from its console. /// /// ```c /// BOOL WINAPI FreeConsole(void); /// ``` /// {@category kernel32} int FreeConsole() => _FreeConsole(); late final _FreeConsole = _kernel32.lookupFunction<Int32 Function(), int Function()>('FreeConsole'); /// Frees the loaded dynamic-link library (DLL) module and, if necessary, /// decrements its reference count. When the reference count reaches zero, /// the module is unloaded from the address space of the calling process /// and the handle is no longer valid. /// /// ```c /// BOOL FreeLibrary( /// HMODULE hLibModule /// ); /// ``` /// {@category kernel32} int FreeLibrary(int hLibModule) => _FreeLibrary(hLibModule); late final _FreeLibrary = _kernel32.lookupFunction< Int32 Function(IntPtr hLibModule), int Function(int hLibModule)>('FreeLibrary'); /// Returns the number of active processors in a processor group or in the /// system. /// /// ```c /// DWORD GetActiveProcessorCount( /// WORD GroupNumber /// ); /// ``` /// {@category kernel32} int GetActiveProcessorCount(int GroupNumber) => _GetActiveProcessorCount(GroupNumber); late final _GetActiveProcessorCount = _kernel32.lookupFunction< Uint32 Function(Uint16 GroupNumber), int Function(int GroupNumber)>('GetActiveProcessorCount'); /// Returns the number of active processor groups in the system. /// /// ```c /// WORD GetActiveProcessorGroupCount(); /// ``` /// {@category kernel32} int GetActiveProcessorGroupCount() => _GetActiveProcessorGroupCount(); late final _GetActiveProcessorGroupCount = _kernel32.lookupFunction<Uint16 Function(), int Function()>( 'GetActiveProcessorGroupCount'); /// Determines whether a file is an executable (.exe) file, and if so, /// which subsystem runs the executable file. /// /// ```c /// BOOL GetBinaryTypeW( /// LPCWSTR lpApplicationName, /// LPDWORD lpBinaryType); /// ``` /// {@category kernel32} int GetBinaryType( Pointer<Utf16> lpApplicationName, Pointer<Uint32> lpBinaryType) => _GetBinaryType(lpApplicationName, lpBinaryType); late final _GetBinaryType = _kernel32.lookupFunction< Int32 Function( Pointer<Utf16> lpApplicationName, Pointer<Uint32> lpBinaryType), int Function(Pointer<Utf16> lpApplicationName, Pointer<Uint32> lpBinaryType)>('GetBinaryTypeW'); /// Parses a Unicode command line string and returns an array of pointers /// to the command line arguments, along with a count of such arguments, in /// a way that is similar to the standard C run-time argv and argc values. /// /// ```c /// LPWSTR GetCommandLineW(); /// ``` /// {@category kernel32} Pointer<Utf16> GetCommandLine() => _GetCommandLine(); late final _GetCommandLine = _kernel32.lookupFunction<Pointer<Utf16> Function(), Pointer<Utf16> Function()>('GetCommandLineW'); /// Retrieves the current configuration of a communications device. /// /// ```c /// BOOL GetCommConfig( /// HANDLE hCommDev, /// LPCOMMCONFIG lpCC, /// LPDWORD lpdwSize /// ); /// ``` /// {@category kernel32} int GetCommConfig( int hCommDev, Pointer<COMMCONFIG> lpCC, Pointer<Uint32> lpdwSize) => _GetCommConfig(hCommDev, lpCC, lpdwSize); late final _GetCommConfig = _kernel32.lookupFunction< Int32 Function( IntPtr hCommDev, Pointer<COMMCONFIG> lpCC, Pointer<Uint32> lpdwSize), int Function(int hCommDev, Pointer<COMMCONFIG> lpCC, Pointer<Uint32> lpdwSize)>('GetCommConfig'); /// Retrieves the value of the event mask for a specified communications /// device. /// /// ```c /// BOOL GetCommMask( /// HANDLE hFile, /// LPDWORD lpEvtMask /// ); /// ``` /// {@category kernel32} int GetCommMask(int hFile, Pointer<Uint32> lpEvtMask) => _GetCommMask(hFile, lpEvtMask); late final _GetCommMask = _kernel32.lookupFunction< Int32 Function(IntPtr hFile, Pointer<Uint32> lpEvtMask), int Function(int hFile, Pointer<Uint32> lpEvtMask)>('GetCommMask'); /// Retrieves the modem control-register values. /// /// ```c /// BOOL GetCommModemStatus( /// HANDLE hFile, /// LPDWORD lpModemStat /// ); /// ``` /// {@category kernel32} int GetCommModemStatus(int hFile, Pointer<Uint32> lpModemStat) => _GetCommModemStatus(hFile, lpModemStat); late final _GetCommModemStatus = _kernel32.lookupFunction< Int32 Function(IntPtr hFile, Pointer<Uint32> lpModemStat), int Function(int hFile, Pointer<Uint32> lpModemStat)>('GetCommModemStatus'); /// Retrieves information about the communications properties for a /// specified communications device. /// /// ```c /// BOOL GetCommProperties( /// HANDLE hFile, /// LPCOMMPROP lpCommProp /// ); /// ``` /// {@category kernel32} int GetCommProperties(int hFile, Pointer<COMMPROP> lpCommProp) => _GetCommProperties(hFile, lpCommProp); late final _GetCommProperties = _kernel32.lookupFunction< Int32 Function(IntPtr hFile, Pointer<COMMPROP> lpCommProp), int Function(int hFile, Pointer<COMMPROP> lpCommProp)>('GetCommProperties'); /// Retrieves the current control settings for a specified communications /// device. /// /// ```c /// BOOL GetCommState( /// HANDLE hFile, /// LPDCB lpDCB /// ); /// ``` /// {@category kernel32} int GetCommState(int hFile, Pointer<DCB> lpDCB) => _GetCommState(hFile, lpDCB); late final _GetCommState = _kernel32.lookupFunction< Int32 Function(IntPtr hFile, Pointer<DCB> lpDCB), int Function(int hFile, Pointer<DCB> lpDCB)>('GetCommState'); /// Retrieves the time-out parameters for all read and write operations on /// a specified communications device. /// /// ```c /// BOOL GetCommTimeouts( /// HANDLE hFile, /// LPCOMMTIMEOUTS lpCommTimeouts /// ); /// ``` /// {@category kernel32} int GetCommTimeouts(int hFile, Pointer<COMMTIMEOUTS> lpCommTimeouts) => _GetCommTimeouts(hFile, lpCommTimeouts); late final _GetCommTimeouts = _kernel32.lookupFunction< Int32 Function(IntPtr hFile, Pointer<COMMTIMEOUTS> lpCommTimeouts), int Function( int hFile, Pointer<COMMTIMEOUTS> lpCommTimeouts)>('GetCommTimeouts'); /// Retrieves the actual number of bytes of disk storage used to store a /// specified file. If the file is located on a volume that supports /// compression and the file is compressed, the value obtained is the /// compressed size of the specified file. If the file is located on a /// volume that supports sparse files and the file is a sparse file, the /// value obtained is the sparse size of the specified file. /// /// ```c /// DWORD GetCompressedFileSizeW( /// LPCWSTR lpFileName, /// LPDWORD lpFileSizeHigh /// ); /// ``` /// {@category kernel32} int GetCompressedFileSize( Pointer<Utf16> lpFileName, Pointer<Uint32> lpFileSizeHigh) => _GetCompressedFileSize(lpFileName, lpFileSizeHigh); late final _GetCompressedFileSize = _kernel32.lookupFunction< Uint32 Function(Pointer<Utf16> lpFileName, Pointer<Uint32> lpFileSizeHigh), int Function(Pointer<Utf16> lpFileName, Pointer<Uint32> lpFileSizeHigh)>('GetCompressedFileSizeW'); /// Retrieves the NetBIOS name of the local computer. This name is /// established at system startup, when the system reads it from the /// registry. /// /// ```c /// BOOL GetComputerNameW( /// LPWSTR lpBuffer, /// LPDWORD nSize /// ); /// ``` /// {@category kernel32} int GetComputerName(Pointer<Utf16> lpBuffer, Pointer<Uint32> nSize) => _GetComputerName(lpBuffer, nSize); late final _GetComputerName = _kernel32.lookupFunction< Int32 Function(Pointer<Utf16> lpBuffer, Pointer<Uint32> nSize), int Function( Pointer<Utf16> lpBuffer, Pointer<Uint32> nSize)>('GetComputerNameW'); /// Retrieves a NetBIOS or DNS name associated with the local computer. The /// names are established at system startup, when the system reads them /// from the registry. /// /// ```c /// BOOL GetComputerNameExW( /// COMPUTER_NAME_FORMAT NameType, /// LPWSTR lpBuffer, /// LPDWORD nSize /// ); /// ``` /// {@category kernel32} int GetComputerNameEx( int NameType, Pointer<Utf16> lpBuffer, Pointer<Uint32> nSize) => _GetComputerNameEx(NameType, lpBuffer, nSize); late final _GetComputerNameEx = _kernel32.lookupFunction< Int32 Function( Int32 NameType, Pointer<Utf16> lpBuffer, Pointer<Uint32> nSize), int Function(int NameType, Pointer<Utf16> lpBuffer, Pointer<Uint32> nSize)>('GetComputerNameExW'); /// Retrieves information about the size and visibility of the cursor for /// the specified console screen buffer. /// /// ```c /// BOOL WINAPI GetConsoleCursorInfo( /// _In_ HANDLE hConsoleOutput, /// _Out_ PCONSOLE_CURSOR_INFO lpConsoleCursorInfo /// ); /// ``` /// {@category kernel32} int GetConsoleCursorInfo( int hConsoleOutput, Pointer<CONSOLE_CURSOR_INFO> lpConsoleCursorInfo) => _GetConsoleCursorInfo(hConsoleOutput, lpConsoleCursorInfo); late final _GetConsoleCursorInfo = _kernel32.lookupFunction< Int32 Function(IntPtr hConsoleOutput, Pointer<CONSOLE_CURSOR_INFO> lpConsoleCursorInfo), int Function(int hConsoleOutput, Pointer<CONSOLE_CURSOR_INFO> lpConsoleCursorInfo)>( 'GetConsoleCursorInfo'); /// Retrieves the current input mode of a console's input buffer or the /// current output mode of a console screen buffer. /// /// ```c /// BOOL WINAPI GetConsoleMode( /// _In_ HANDLE hConsoleHandle, /// _Out_ LPDWORD lpMode /// ); /// ``` /// {@category kernel32} int GetConsoleMode(int hConsoleHandle, Pointer<Uint32> lpMode) => _GetConsoleMode(hConsoleHandle, lpMode); late final _GetConsoleMode = _kernel32.lookupFunction< Int32 Function(IntPtr hConsoleHandle, Pointer<Uint32> lpMode), int Function(int hConsoleHandle, Pointer<Uint32> lpMode)>('GetConsoleMode'); /// Retrieves information about the specified console screen buffer. /// /// ```c /// BOOL WINAPI GetConsoleScreenBufferInfo( /// _In_ HANDLE hConsoleOutput, /// _Out_ PCONSOLE_SCREEN_BUFFER_INFO lpConsoleScreenBufferInfo /// ); /// ``` /// {@category kernel32} int GetConsoleScreenBufferInfo(int hConsoleOutput, Pointer<CONSOLE_SCREEN_BUFFER_INFO> lpConsoleScreenBufferInfo) => _GetConsoleScreenBufferInfo(hConsoleOutput, lpConsoleScreenBufferInfo); late final _GetConsoleScreenBufferInfo = _kernel32.lookupFunction< Int32 Function(IntPtr hConsoleOutput, Pointer<CONSOLE_SCREEN_BUFFER_INFO> lpConsoleScreenBufferInfo), int Function(int hConsoleOutput, Pointer<CONSOLE_SCREEN_BUFFER_INFO> lpConsoleScreenBufferInfo)>( 'GetConsoleScreenBufferInfo'); /// Retrieves information about the current console selection. /// /// ```c /// BOOL WINAPI GetConsoleSelectionInfo( /// _Out_ PCONSOLE_SELECTION_INFO lpConsoleSelectionInfo /// ); /// ``` /// {@category kernel32} int GetConsoleSelectionInfo( Pointer<CONSOLE_SELECTION_INFO> lpConsoleSelectionInfo) => _GetConsoleSelectionInfo(lpConsoleSelectionInfo); late final _GetConsoleSelectionInfo = _kernel32.lookupFunction< Int32 Function(Pointer<CONSOLE_SELECTION_INFO> lpConsoleSelectionInfo), int Function(Pointer<CONSOLE_SELECTION_INFO> lpConsoleSelectionInfo)>( 'GetConsoleSelectionInfo'); /// Retrieves the title for the current console window. /// /// ```c /// DWORD WINAPI GetConsoleTitleW( /// _Out_ LPTSTR lpConsoleTitle, /// _In_ DWORD nSize /// ); /// ``` /// {@category kernel32} int GetConsoleTitle(Pointer<Utf16> lpConsoleTitle, int nSize) => _GetConsoleTitle(lpConsoleTitle, nSize); late final _GetConsoleTitle = _kernel32.lookupFunction< Uint32 Function(Pointer<Utf16> lpConsoleTitle, Uint32 nSize), int Function(Pointer<Utf16> lpConsoleTitle, int nSize)>('GetConsoleTitleW'); /// Retrieves the window handle used by the console associated with the /// calling process. /// /// ```c /// HWND WINAPI GetConsoleWindow(void); /// ``` /// {@category kernel32} int GetConsoleWindow() => _GetConsoleWindow(); late final _GetConsoleWindow = _kernel32 .lookupFunction<IntPtr Function(), int Function()>('GetConsoleWindow'); /// The GetCurrentActCtx function returns the handle to the active /// activation context of the calling thread. /// /// ```c /// BOOL GetCurrentActCtx( /// HANDLE *lphActCtx /// ); /// ``` /// {@category kernel32} int GetCurrentActCtx(Pointer<IntPtr> lphActCtx) => _GetCurrentActCtx(lphActCtx); late final _GetCurrentActCtx = _kernel32.lookupFunction< Int32 Function(Pointer<IntPtr> lphActCtx), int Function(Pointer<IntPtr> lphActCtx)>('GetCurrentActCtx'); /// Retrieves a pseudo handle for the current process. /// /// ```c /// HANDLE GetCurrentProcess(); /// ``` /// {@category kernel32} int GetCurrentProcess() => _GetCurrentProcess(); late final _GetCurrentProcess = _kernel32 .lookupFunction<IntPtr Function(), int Function()>('GetCurrentProcess'); /// Retrieves the process identifier of the calling process. /// /// ```c /// DWORD GetCurrentProcessId(); /// ``` /// {@category kernel32} int GetCurrentProcessId() => _GetCurrentProcessId(); late final _GetCurrentProcessId = _kernel32 .lookupFunction<Uint32 Function(), int Function()>('GetCurrentProcessId'); /// Retrieves the number of the processor the current thread was running on /// during the call to this function. /// /// ```c /// DWORD GetCurrentProcessorNumber(); /// ``` /// {@category kernel32} int GetCurrentProcessorNumber() => _GetCurrentProcessorNumber(); late final _GetCurrentProcessorNumber = _kernel32.lookupFunction<Uint32 Function(), int Function()>( 'GetCurrentProcessorNumber'); /// Retrieves a pseudo handle for the calling thread. /// /// ```c /// HANDLE GetCurrentThread(); /// ``` /// {@category kernel32} int GetCurrentThread() => _GetCurrentThread(); late final _GetCurrentThread = _kernel32 .lookupFunction<IntPtr Function(), int Function()>('GetCurrentThread'); /// Retrieves the thread identifier of the calling thread. /// /// ```c /// DWORD GetCurrentThreadId(); /// ``` /// {@category kernel32} int GetCurrentThreadId() => _GetCurrentThreadId(); late final _GetCurrentThreadId = _kernel32 .lookupFunction<Uint32 Function(), int Function()>('GetCurrentThreadId'); /// Retrieves the default configuration for the specified communications /// device. /// /// ```c /// BOOL GetDefaultCommConfigW( /// LPCWSTR lpszName, /// LPCOMMCONFIG lpCC, /// LPDWORD lpdwSize /// ); /// ``` /// {@category kernel32} int GetDefaultCommConfig(Pointer<Utf16> lpszName, Pointer<COMMCONFIG> lpCC, Pointer<Uint32> lpdwSize) => _GetDefaultCommConfig(lpszName, lpCC, lpdwSize); late final _GetDefaultCommConfig = _kernel32.lookupFunction< Int32 Function(Pointer<Utf16> lpszName, Pointer<COMMCONFIG> lpCC, Pointer<Uint32> lpdwSize), int Function(Pointer<Utf16> lpszName, Pointer<COMMCONFIG> lpCC, Pointer<Uint32> lpdwSize)>('GetDefaultCommConfigW'); /// Retrieves information about the specified disk, including the amount of /// free space on the disk. /// /// ```c /// BOOL GetDiskFreeSpaceW( /// LPCWSTR lpRootPathName, /// LPDWORD lpSectorsPerCluster, /// LPDWORD lpBytesPerSector, /// LPDWORD lpNumberOfFreeClusters, /// LPDWORD lpTotalNumberOfClusters /// ); /// ``` /// {@category kernel32} int GetDiskFreeSpace( Pointer<Utf16> lpRootPathName, Pointer<Uint32> lpSectorsPerCluster, Pointer<Uint32> lpBytesPerSector, Pointer<Uint32> lpNumberOfFreeClusters, Pointer<Uint32> lpTotalNumberOfClusters) => _GetDiskFreeSpace(lpRootPathName, lpSectorsPerCluster, lpBytesPerSector, lpNumberOfFreeClusters, lpTotalNumberOfClusters); late final _GetDiskFreeSpace = _kernel32.lookupFunction< Int32 Function( Pointer<Utf16> lpRootPathName, Pointer<Uint32> lpSectorsPerCluster, Pointer<Uint32> lpBytesPerSector, Pointer<Uint32> lpNumberOfFreeClusters, Pointer<Uint32> lpTotalNumberOfClusters), int Function( Pointer<Utf16> lpRootPathName, Pointer<Uint32> lpSectorsPerCluster, Pointer<Uint32> lpBytesPerSector, Pointer<Uint32> lpNumberOfFreeClusters, Pointer<Uint32> lpTotalNumberOfClusters)>('GetDiskFreeSpaceW'); /// Retrieves the application-specific portion of the search path used to /// locate DLLs for the application. /// /// ```c /// DWORD GetDllDirectoryW( /// DWORD nBufferLength, /// LPWSTR lpBuffer /// ); /// ``` /// {@category kernel32} int GetDllDirectory(int nBufferLength, Pointer<Utf16> lpBuffer) => _GetDllDirectory(nBufferLength, lpBuffer); late final _GetDllDirectory = _kernel32.lookupFunction< Uint32 Function(Uint32 nBufferLength, Pointer<Utf16> lpBuffer), int Function( int nBufferLength, Pointer<Utf16> lpBuffer)>('GetDllDirectoryW'); /// Determines whether a disk drive is a removable, fixed, CD-ROM, RAM /// disk, or network drive. /// /// ```c /// UINT GetDriveTypeW( /// LPCWSTR lpRootPathName /// ); /// ``` /// {@category kernel32} int GetDriveType(Pointer<Utf16> lpRootPathName) => _GetDriveType(lpRootPathName); late final _GetDriveType = _kernel32.lookupFunction< Uint32 Function(Pointer<Utf16> lpRootPathName), int Function(Pointer<Utf16> lpRootPathName)>('GetDriveTypeW'); /// Retrieves the termination status of the specified process. /// /// ```c /// BOOL GetExitCodeProcess( /// HANDLE hProcess, /// LPDWORD lpExitCode); /// ``` /// {@category kernel32} int GetExitCodeProcess(int hProcess, Pointer<Uint32> lpExitCode) => _GetExitCodeProcess(hProcess, lpExitCode); late final _GetExitCodeProcess = _kernel32.lookupFunction< Int32 Function(IntPtr hProcess, Pointer<Uint32> lpExitCode), int Function( int hProcess, Pointer<Uint32> lpExitCode)>('GetExitCodeProcess'); /// Retrieves file system attributes for a specified file or directory. /// /// ```c /// DWORD GetFileAttributesW( /// LPCWSTR lpFileName /// ); /// ``` /// {@category kernel32} int GetFileAttributes(Pointer<Utf16> lpFileName) => _GetFileAttributes(lpFileName); late final _GetFileAttributes = _kernel32.lookupFunction< Uint32 Function(Pointer<Utf16> lpFileName), int Function(Pointer<Utf16> lpFileName)>('GetFileAttributesW'); /// Retrieves attributes for a specified file or directory. /// /// ```c /// BOOL GetFileAttributesExW( /// LPCWSTR lpFileName, /// GET_FILEEX_INFO_LEVELS fInfoLevelId, /// LPVOID lpFileInformation /// ); /// ``` /// {@category kernel32} int GetFileAttributesEx(Pointer<Utf16> lpFileName, int fInfoLevelId, Pointer lpFileInformation) => _GetFileAttributesEx(lpFileName, fInfoLevelId, lpFileInformation); late final _GetFileAttributesEx = _kernel32.lookupFunction< Int32 Function(Pointer<Utf16> lpFileName, Int32 fInfoLevelId, Pointer lpFileInformation), int Function(Pointer<Utf16> lpFileName, int fInfoLevelId, Pointer lpFileInformation)>('GetFileAttributesExW'); /// Retrieves file information for the specified file. /// /// ```c /// BOOL GetFileInformationByHandle( /// HANDLE hFile, /// LPBY_HANDLE_FILE_INFORMATION lpFileInformation /// ); /// ``` /// {@category kernel32} int GetFileInformationByHandle( int hFile, Pointer<BY_HANDLE_FILE_INFORMATION> lpFileInformation) => _GetFileInformationByHandle(hFile, lpFileInformation); late final _GetFileInformationByHandle = _kernel32.lookupFunction< Int32 Function(IntPtr hFile, Pointer<BY_HANDLE_FILE_INFORMATION> lpFileInformation), int Function( int hFile, Pointer<BY_HANDLE_FILE_INFORMATION> lpFileInformation)>( 'GetFileInformationByHandle'); /// Retrieves the size of the specified file, in bytes. It is recommended /// that you use GetFileSizeEx. /// /// ```c /// DWORD GetFileSize( /// HANDLE hFile, /// LPDWORD lpFileSizeHigh /// ); /// ``` /// {@category kernel32} int GetFileSize(int hFile, Pointer<Uint32> lpFileSizeHigh) => _GetFileSize(hFile, lpFileSizeHigh); late final _GetFileSize = _kernel32.lookupFunction< Uint32 Function(IntPtr hFile, Pointer<Uint32> lpFileSizeHigh), int Function(int hFile, Pointer<Uint32> lpFileSizeHigh)>('GetFileSize'); /// Retrieves the size of the specified file. /// /// ```c /// BOOL GetFileSizeEx( /// HANDLE hFile, /// PLARGE_INTEGER lpFileSize /// ); /// ``` /// {@category kernel32} int GetFileSizeEx(int hFile, Pointer<Int64> lpFileSize) => _GetFileSizeEx(hFile, lpFileSize); late final _GetFileSizeEx = _kernel32.lookupFunction< Int32 Function(IntPtr hFile, Pointer<Int64> lpFileSize), int Function(int hFile, Pointer<Int64> lpFileSize)>('GetFileSizeEx'); /// Retrieves the file type of the specified file. /// /// ```c /// DWORD GetFileType( /// HANDLE hFile /// ); /// ``` /// {@category kernel32} int GetFileType(int hFile) => _GetFileType(hFile); late final _GetFileType = _kernel32.lookupFunction< Uint32 Function(IntPtr hFile), int Function(int hFile)>('GetFileType'); /// Retrieves the final path for the specified file. /// /// ```c /// DWORD GetFinalPathNameByHandleW( /// HANDLE hFile, /// LPWSTR lpszFilePath, /// DWORD cchFilePath, /// DWORD dwFlags /// ); /// ``` /// {@category kernel32} int GetFinalPathNameByHandle( int hFile, Pointer<Utf16> lpszFilePath, int cchFilePath, int dwFlags) => _GetFinalPathNameByHandle(hFile, lpszFilePath, cchFilePath, dwFlags); late final _GetFinalPathNameByHandle = _kernel32.lookupFunction< Uint32 Function(IntPtr hFile, Pointer<Utf16> lpszFilePath, Uint32 cchFilePath, Uint32 dwFlags), int Function(int hFile, Pointer<Utf16> lpszFilePath, int cchFilePath, int dwFlags)>('GetFinalPathNameByHandleW'); /// Retrieves the full path and file name of the specified file. /// /// ```c /// DWORD GetFullPathNameW( /// LPCWSTR lpFileName, /// DWORD nBufferLength, /// LPWSTR lpBuffer, /// LPWSTR *lpFilePart /// ); /// ``` /// {@category kernel32} int GetFullPathName(Pointer<Utf16> lpFileName, int nBufferLength, Pointer<Utf16> lpBuffer, Pointer<Pointer<Utf16>> lpFilePart) => _GetFullPathName(lpFileName, nBufferLength, lpBuffer, lpFilePart); late final _GetFullPathName = _kernel32.lookupFunction< Uint32 Function(Pointer<Utf16> lpFileName, Uint32 nBufferLength, Pointer<Utf16> lpBuffer, Pointer<Pointer<Utf16>> lpFilePart), int Function( Pointer<Utf16> lpFileName, int nBufferLength, Pointer<Utf16> lpBuffer, Pointer<Pointer<Utf16>> lpFilePart)>('GetFullPathNameW'); /// Retrieves certain properties of an object handle. /// /// ```c /// BOOL GetHandleInformation( /// HANDLE hObject, /// LPDWORD lpdwFlags /// ); /// ``` /// {@category kernel32} int GetHandleInformation(int hObject, Pointer<Uint32> lpdwFlags) => _GetHandleInformation(hObject, lpdwFlags); late final _GetHandleInformation = _kernel32.lookupFunction< Int32 Function(IntPtr hObject, Pointer<Uint32> lpdwFlags), int Function( int hObject, Pointer<Uint32> lpdwFlags)>('GetHandleInformation'); /// Retrieves the size of the largest possible console window, based on the /// current font and the size of the display. /// /// ```c /// COORD WINAPI GetLargestConsoleWindowSize( /// _In_ HANDLE hConsoleOutput /// ); /// ``` /// {@category kernel32} COORD GetLargestConsoleWindowSize(int hConsoleOutput) => _GetLargestConsoleWindowSize(hConsoleOutput); late final _GetLargestConsoleWindowSize = _kernel32.lookupFunction< COORD Function(IntPtr hConsoleOutput), COORD Function(int hConsoleOutput)>('GetLargestConsoleWindowSize'); /// Retrieves the calling thread's last-error code value. The last-error /// code is maintained on a per-thread basis. Multiple threads do not /// overwrite each other's last-error code. /// /// ```c /// DWORD GetLastError(); /// ``` /// {@category kernel32} int GetLastError() => _GetLastError(); late final _GetLastError = _kernel32.lookupFunction<Uint32 Function(), int Function()>('GetLastError'); /// Retrieves information about a locale specified by name. /// /// ```c /// int GetLocaleInfoEx( /// LPCWSTR lpLocaleName, /// LCTYPE LCType, /// LPWSTR lpLCData, /// int cchData /// ); /// ``` /// {@category kernel32} int GetLocaleInfoEx(Pointer<Utf16> lpLocaleName, int LCType, Pointer<Utf16> lpLCData, int cchData) => _GetLocaleInfoEx(lpLocaleName, LCType, lpLCData, cchData); late final _GetLocaleInfoEx = _kernel32.lookupFunction< Int32 Function(Pointer<Utf16> lpLocaleName, Uint32 LCType, Pointer<Utf16> lpLCData, Int32 cchData), int Function(Pointer<Utf16> lpLocaleName, int LCType, Pointer<Utf16> lpLCData, int cchData)>('GetLocaleInfoEx'); /// Retrieves the current local date and time. /// /// ```c /// void GetLocalTime( /// LPSYSTEMTIME lpSystemTime /// ); /// ``` /// {@category kernel32} void GetLocalTime(Pointer<SYSTEMTIME> lpSystemTime) => _GetLocalTime(lpSystemTime); late final _GetLocalTime = _kernel32.lookupFunction< Void Function(Pointer<SYSTEMTIME> lpSystemTime), void Function(Pointer<SYSTEMTIME> lpSystemTime)>('GetLocalTime'); /// Retrieves a bitmask representing the currently available disk drives. /// /// ```c /// DWORD GetLogicalDrives(); /// ``` /// {@category kernel32} int GetLogicalDrives() => _GetLogicalDrives(); late final _GetLogicalDrives = _kernel32 .lookupFunction<Uint32 Function(), int Function()>('GetLogicalDrives'); /// Fills a buffer with strings that specify valid drives in the system. /// /// ```c /// DWORD GetLogicalDriveStringsW( /// DWORD nBufferLength, /// LPWSTR lpBuffer /// ); /// ``` /// {@category kernel32} int GetLogicalDriveStrings(int nBufferLength, Pointer<Utf16> lpBuffer) => _GetLogicalDriveStrings(nBufferLength, lpBuffer); late final _GetLogicalDriveStrings = _kernel32.lookupFunction< Uint32 Function(Uint32 nBufferLength, Pointer<Utf16> lpBuffer), int Function( int nBufferLength, Pointer<Utf16> lpBuffer)>('GetLogicalDriveStringsW'); /// Queries if the specified architecture is supported on the current /// system, either natively or by any form of compatibility or emulation /// layer. /// /// ```c /// HRESULT GetMachineTypeAttributes( /// USHORT Machine, /// MACHINE_ATTRIBUTES *MachineTypeAttributes /// ); /// ``` /// {@category kernel32} int GetMachineTypeAttributes( int Machine, Pointer<Uint32> MachineTypeAttributes) => _GetMachineTypeAttributes(Machine, MachineTypeAttributes); late final _GetMachineTypeAttributes = _kernel32.lookupFunction< Int32 Function(Uint16 Machine, Pointer<Uint32> MachineTypeAttributes), int Function(int Machine, Pointer<Uint32> MachineTypeAttributes)>('GetMachineTypeAttributes'); /// Returns the maximum number of logical processors that a processor group /// or the system can have. /// /// ```c /// DWORD GetMaximumProcessorCount( /// WORD GroupNumber /// ); /// ``` /// {@category kernel32} int GetMaximumProcessorCount(int GroupNumber) => _GetMaximumProcessorCount(GroupNumber); late final _GetMaximumProcessorCount = _kernel32.lookupFunction< Uint32 Function(Uint16 GroupNumber), int Function(int GroupNumber)>('GetMaximumProcessorCount'); /// Returns the maximum number of processor groups that the system can /// have. /// /// ```c /// WORD GetMaximumProcessorGroupCount(); /// ``` /// {@category kernel32} int GetMaximumProcessorGroupCount() => _GetMaximumProcessorGroupCount(); late final _GetMaximumProcessorGroupCount = _kernel32.lookupFunction<Uint16 Function(), int Function()>( 'GetMaximumProcessorGroupCount'); /// Retrieves the base name of the specified module. /// /// ```c /// DWORD K32GetModuleBaseNameW( /// HANDLE hProcess, /// HMODULE hModule, /// LPWSTR lpBaseName, /// DWORD nSize /// ); /// ``` /// {@category kernel32} int GetModuleBaseName( int hProcess, int hModule, Pointer<Utf16> lpBaseName, int nSize) => _K32GetModuleBaseName(hProcess, hModule, lpBaseName, nSize); late final _K32GetModuleBaseName = _kernel32.lookupFunction< Uint32 Function(IntPtr hProcess, IntPtr hModule, Pointer<Utf16> lpBaseName, Uint32 nSize), int Function(int hProcess, int hModule, Pointer<Utf16> lpBaseName, int nSize)>('K32GetModuleBaseNameW'); /// Retrieves the fully qualified path for the file that contains the /// specified module. The module must have been loaded by the current /// process. /// /// ```c /// DWORD GetModuleFileNameW( /// HMODULE hModule, /// LPWSTR lpFilename, /// DWORD nSize /// ); /// ``` /// {@category kernel32} int GetModuleFileName(int hModule, Pointer<Utf16> lpFilename, int nSize) => _GetModuleFileName(hModule, lpFilename, nSize); late final _GetModuleFileName = _kernel32.lookupFunction< Uint32 Function(IntPtr hModule, Pointer<Utf16> lpFilename, Uint32 nSize), int Function(int hModule, Pointer<Utf16> lpFilename, int nSize)>('GetModuleFileNameW'); /// Retrieves the fully qualified path for the file containing the /// specified module. /// /// ```c /// DWORD K32GetModuleFileNameExW( /// HANDLE hProcess, /// HMODULE hModule, /// LPWSTR lpFilename, /// DWORD nSize /// ); /// ``` /// {@category kernel32} int GetModuleFileNameEx( int hProcess, int hModule, Pointer<Utf16> lpFilename, int nSize) => _K32GetModuleFileNameEx(hProcess, hModule, lpFilename, nSize); late final _K32GetModuleFileNameEx = _kernel32.lookupFunction< Uint32 Function(IntPtr hProcess, IntPtr hModule, Pointer<Utf16> lpFilename, Uint32 nSize), int Function(int hProcess, int hModule, Pointer<Utf16> lpFilename, int nSize)>('K32GetModuleFileNameExW'); /// Retrieves a module handle for the specified module. The module must /// have been loaded by the calling process. /// /// ```c /// HMODULE GetModuleHandleW( /// LPCWSTR lpModuleName /// ); /// ``` /// {@category kernel32} int GetModuleHandle(Pointer<Utf16> lpModuleName) => _GetModuleHandle(lpModuleName); late final _GetModuleHandle = _kernel32.lookupFunction< IntPtr Function(Pointer<Utf16> lpModuleName), int Function(Pointer<Utf16> lpModuleName)>('GetModuleHandleW'); /// Retrieves the client computer name for the specified named pipe. /// /// ```c /// BOOL GetNamedPipeClientComputerNameW( /// HANDLE Pipe, /// LPWSTR ClientComputerName, /// ULONG ClientComputerNameLength /// ); /// ``` /// {@category kernel32} int GetNamedPipeClientComputerName(int Pipe, Pointer<Utf16> ClientComputerName, int ClientComputerNameLength) => _GetNamedPipeClientComputerName( Pipe, ClientComputerName, ClientComputerNameLength); late final _GetNamedPipeClientComputerName = _kernel32.lookupFunction< Int32 Function(IntPtr Pipe, Pointer<Utf16> ClientComputerName, Uint32 ClientComputerNameLength), int Function(int Pipe, Pointer<Utf16> ClientComputerName, int ClientComputerNameLength)>('GetNamedPipeClientComputerNameW'); /// Retrieves the client process identifier for the specified named pipe. /// /// ```c /// BOOL GetNamedPipeClientProcessId( /// HANDLE Pipe, /// PULONG ClientProcessId /// ); /// ``` /// {@category kernel32} int GetNamedPipeClientProcessId(int Pipe, Pointer<Uint32> ClientProcessId) => _GetNamedPipeClientProcessId(Pipe, ClientProcessId); late final _GetNamedPipeClientProcessId = _kernel32.lookupFunction< Int32 Function(IntPtr Pipe, Pointer<Uint32> ClientProcessId), int Function(int Pipe, Pointer<Uint32> ClientProcessId)>('GetNamedPipeClientProcessId'); /// Retrieves the client process identifier for the specified named pipe. /// /// ```c /// BOOL GetNamedPipeClientSessionId( /// HANDLE Pipe, /// PULONG ClientSessionId /// ); /// ``` /// {@category kernel32} int GetNamedPipeClientSessionId(int Pipe, Pointer<Uint32> ClientSessionId) => _GetNamedPipeClientSessionId(Pipe, ClientSessionId); late final _GetNamedPipeClientSessionId = _kernel32.lookupFunction< Int32 Function(IntPtr Pipe, Pointer<Uint32> ClientSessionId), int Function(int Pipe, Pointer<Uint32> ClientSessionId)>('GetNamedPipeClientSessionId'); /// Retrieves information about a specified named pipe. The information /// returned can vary during the lifetime of an instance of the named pipe. /// /// ```c /// BOOL GetNamedPipeHandleStateW( /// HANDLE hNamedPipe, /// LPDWORD lpState, /// LPDWORD lpCurInstances, /// LPDWORD lpMaxCollectionCount, /// LPDWORD lpCollectDataTimeout, /// LPWSTR lpUserName, /// DWORD nMaxUserNameSize /// ); /// ``` /// {@category kernel32} int GetNamedPipeHandleState( int hNamedPipe, Pointer<Uint32> lpState, Pointer<Uint32> lpCurInstances, Pointer<Uint32> lpMaxCollectionCount, Pointer<Uint32> lpCollectDataTimeout, Pointer<Utf16> lpUserName, int nMaxUserNameSize) => _GetNamedPipeHandleState( hNamedPipe, lpState, lpCurInstances, lpMaxCollectionCount, lpCollectDataTimeout, lpUserName, nMaxUserNameSize); late final _GetNamedPipeHandleState = _kernel32.lookupFunction< Int32 Function( IntPtr hNamedPipe, Pointer<Uint32> lpState, Pointer<Uint32> lpCurInstances, Pointer<Uint32> lpMaxCollectionCount, Pointer<Uint32> lpCollectDataTimeout, Pointer<Utf16> lpUserName, Uint32 nMaxUserNameSize), int Function( int hNamedPipe, Pointer<Uint32> lpState, Pointer<Uint32> lpCurInstances, Pointer<Uint32> lpMaxCollectionCount, Pointer<Uint32> lpCollectDataTimeout, Pointer<Utf16> lpUserName, int nMaxUserNameSize)>('GetNamedPipeHandleStateW'); /// Retrieves information about the specified named pipe. /// /// ```c /// BOOL GetNamedPipeInfo( /// HANDLE hNamedPipe, /// LPDWORD lpFlags, /// LPDWORD lpOutBufferSize, /// LPDWORD lpInBufferSize, /// LPDWORD lpMaxInstances); /// ``` /// {@category kernel32} int GetNamedPipeInfo( int hNamedPipe, Pointer<Uint32> lpFlags, Pointer<Uint32> lpOutBufferSize, Pointer<Uint32> lpInBufferSize, Pointer<Uint32> lpMaxInstances) => _GetNamedPipeInfo( hNamedPipe, lpFlags, lpOutBufferSize, lpInBufferSize, lpMaxInstances); late final _GetNamedPipeInfo = _kernel32.lookupFunction< Int32 Function( IntPtr hNamedPipe, Pointer<Uint32> lpFlags, Pointer<Uint32> lpOutBufferSize, Pointer<Uint32> lpInBufferSize, Pointer<Uint32> lpMaxInstances), int Function( int hNamedPipe, Pointer<Uint32> lpFlags, Pointer<Uint32> lpOutBufferSize, Pointer<Uint32> lpInBufferSize, Pointer<Uint32> lpMaxInstances)>('GetNamedPipeInfo'); /// Retrieves information about the current system to an application /// running under WOW64. If the function is called from a 64-bit /// application, or on a 64-bit system that does not have an Intel64 or x64 /// processor (such as ARM64), it is equivalent to the GetSystemInfo /// function. /// /// ```c /// void GetNativeSystemInfo( /// LPSYSTEM_INFO lpSystemInfo /// ); /// ``` /// {@category kernel32} void GetNativeSystemInfo(Pointer<SYSTEM_INFO> lpSystemInfo) => _GetNativeSystemInfo(lpSystemInfo); late final _GetNativeSystemInfo = _kernel32.lookupFunction< Void Function(Pointer<SYSTEM_INFO> lpSystemInfo), void Function(Pointer<SYSTEM_INFO> lpSystemInfo)>('GetNativeSystemInfo'); /// Retrieves the results of an overlapped operation on the specified file, /// named pipe, or communications device. To specify a timeout interval or /// wait on an alertable thread, use GetOverlappedResultEx. /// /// ```c /// BOOL GetOverlappedResult( /// HANDLE hFile, /// LPOVERLAPPED lpOverlapped, /// LPDWORD lpNumberOfBytesTransferred, /// BOOL bWait /// ); /// ``` /// {@category kernel32} int GetOverlappedResult(int hFile, Pointer<OVERLAPPED> lpOverlapped, Pointer<Uint32> lpNumberOfBytesTransferred, int bWait) => _GetOverlappedResult( hFile, lpOverlapped, lpNumberOfBytesTransferred, bWait); late final _GetOverlappedResult = _kernel32.lookupFunction< Int32 Function(IntPtr hFile, Pointer<OVERLAPPED> lpOverlapped, Pointer<Uint32> lpNumberOfBytesTransferred, Int32 bWait), int Function( int hFile, Pointer<OVERLAPPED> lpOverlapped, Pointer<Uint32> lpNumberOfBytesTransferred, int bWait)>('GetOverlappedResult'); /// Retrieves the results of an overlapped operation on the specified file, /// named pipe, or communications device within the specified time-out /// interval. The calling thread can perform an alertable wait. /// /// ```c /// BOOL GetOverlappedResultEx( /// HANDLE hFile, /// LPOVERLAPPED lpOverlapped, /// LPDWORD lpNumberOfBytesTransferred, /// DWORD dwMilliseconds, /// BOOL bAlertable /// ); /// ``` /// {@category kernel32} int GetOverlappedResultEx( int hFile, Pointer<OVERLAPPED> lpOverlapped, Pointer<Uint32> lpNumberOfBytesTransferred, int dwMilliseconds, int bAlertable) => _GetOverlappedResultEx(hFile, lpOverlapped, lpNumberOfBytesTransferred, dwMilliseconds, bAlertable); late final _GetOverlappedResultEx = _kernel32.lookupFunction< Int32 Function( IntPtr hFile, Pointer<OVERLAPPED> lpOverlapped, Pointer<Uint32> lpNumberOfBytesTransferred, Uint32 dwMilliseconds, Int32 bAlertable), int Function( int hFile, Pointer<OVERLAPPED> lpOverlapped, Pointer<Uint32> lpNumberOfBytesTransferred, int dwMilliseconds, int bAlertable)>('GetOverlappedResultEx'); /// Retrieves the amount of RAM that is physically installed on the /// computer. /// /// ```c /// BOOL GetPhysicallyInstalledSystemMemory( /// PULONGLONG TotalMemoryInKilobytes /// ); /// ``` /// {@category kernel32} int GetPhysicallyInstalledSystemMemory( Pointer<Uint64> TotalMemoryInKilobytes) => _GetPhysicallyInstalledSystemMemory(TotalMemoryInKilobytes); late final _GetPhysicallyInstalledSystemMemory = _kernel32.lookupFunction< Int32 Function(Pointer<Uint64> TotalMemoryInKilobytes), int Function(Pointer<Uint64> TotalMemoryInKilobytes)>( 'GetPhysicallyInstalledSystemMemory'); /// Retrieves the address of an exported function or variable from the /// specified dynamic-link library (DLL). /// /// ```c /// FARPROC GetProcAddress( /// HMODULE hModule, /// LPCSTR lpProcName /// ); /// ``` /// {@category kernel32} Pointer GetProcAddress(int hModule, Pointer<Utf8> lpProcName) => _GetProcAddress(hModule, lpProcName); late final _GetProcAddress = _kernel32.lookupFunction< Pointer Function(IntPtr hModule, Pointer<Utf8> lpProcName), Pointer Function(int hModule, Pointer<Utf8> lpProcName)>('GetProcAddress'); /// Retrieves a handle to the default heap of the calling process. This /// handle can then be used in subsequent calls to the heap functions. /// /// ```c /// HANDLE GetProcessHeap(); /// ``` /// {@category kernel32} int GetProcessHeap() => _GetProcessHeap(); late final _GetProcessHeap = _kernel32 .lookupFunction<IntPtr Function(), int Function()>('GetProcessHeap'); /// Returns the number of active heaps and retrieves handles to all of the /// active heaps for the calling process. /// /// ```c /// DWORD GetProcessHeaps( /// DWORD NumberOfHeaps, /// PHANDLE ProcessHeaps /// ); /// ``` /// {@category kernel32} int GetProcessHeaps(int NumberOfHeaps, Pointer<IntPtr> ProcessHeaps) => _GetProcessHeaps(NumberOfHeaps, ProcessHeaps); late final _GetProcessHeaps = _kernel32.lookupFunction< Uint32 Function(Uint32 NumberOfHeaps, Pointer<IntPtr> ProcessHeaps), int Function( int NumberOfHeaps, Pointer<IntPtr> ProcessHeaps)>('GetProcessHeaps'); /// Retrieves the process identifier of the specified process. /// /// ```c /// DWORD GetProcessId( /// HANDLE Process /// ); /// ``` /// {@category kernel32} int GetProcessId(int Process) => _GetProcessId(Process); late final _GetProcessId = _kernel32.lookupFunction< Uint32 Function(IntPtr Process), int Function(int Process)>('GetProcessId'); /// Retrieves the shutdown parameters for the currently calling process. /// /// ```c /// BOOL GetProcessShutdownParameters( /// LPDWORD lpdwLevel, /// LPDWORD lpdwFlags /// ); /// ``` /// {@category kernel32} int GetProcessShutdownParameters( Pointer<Uint32> lpdwLevel, Pointer<Uint32> lpdwFlags) => _GetProcessShutdownParameters(lpdwLevel, lpdwFlags); late final _GetProcessShutdownParameters = _kernel32.lookupFunction< Int32 Function(Pointer<Uint32> lpdwLevel, Pointer<Uint32> lpdwFlags), int Function(Pointer<Uint32> lpdwLevel, Pointer<Uint32> lpdwFlags)>('GetProcessShutdownParameters'); /// Retrieves the major and minor version numbers of the system on which /// the specified process expects to run. /// /// ```c /// DWORD GetProcessVersion( /// DWORD ProcessId /// ); /// ``` /// {@category kernel32} int GetProcessVersion(int ProcessId) => _GetProcessVersion(ProcessId); late final _GetProcessVersion = _kernel32.lookupFunction< Uint32 Function(Uint32 ProcessId), int Function(int ProcessId)>('GetProcessVersion'); /// Retrieves the minimum and maximum working set sizes of the specified /// process. /// /// ```c /// BOOL GetProcessWorkingSetSize( /// HANDLE hProcess, /// PSIZE_T lpMinimumWorkingSetSize, /// PSIZE_T lpMaximumWorkingSetSize /// ); /// ``` /// {@category kernel32} int GetProcessWorkingSetSize( int hProcess, Pointer<IntPtr> lpMinimumWorkingSetSize, Pointer<IntPtr> lpMaximumWorkingSetSize) => _GetProcessWorkingSetSize( hProcess, lpMinimumWorkingSetSize, lpMaximumWorkingSetSize); late final _GetProcessWorkingSetSize = _kernel32.lookupFunction< Int32 Function(IntPtr hProcess, Pointer<IntPtr> lpMinimumWorkingSetSize, Pointer<IntPtr> lpMaximumWorkingSetSize), int Function(int hProcess, Pointer<IntPtr> lpMinimumWorkingSetSize, Pointer<IntPtr> lpMaximumWorkingSetSize)>('GetProcessWorkingSetSize'); /// Retrieves the product type for the operating system on the local /// computer, and maps the type to the product types supported by the /// specified operating system. /// /// ```c /// BOOL GetProductInfo( /// DWORD dwOSMajorVersion, /// DWORD dwOSMinorVersion, /// DWORD dwSpMajorVersion, /// DWORD dwSpMinorVersion, /// PDWORD pdwReturnedProductType /// ); /// ``` /// {@category kernel32} int GetProductInfo( int dwOSMajorVersion, int dwOSMinorVersion, int dwSpMajorVersion, int dwSpMinorVersion, Pointer<Uint32> pdwReturnedProductType) => _GetProductInfo(dwOSMajorVersion, dwOSMinorVersion, dwSpMajorVersion, dwSpMinorVersion, pdwReturnedProductType); late final _GetProductInfo = _kernel32.lookupFunction< Int32 Function( Uint32 dwOSMajorVersion, Uint32 dwOSMinorVersion, Uint32 dwSpMajorVersion, Uint32 dwSpMinorVersion, Pointer<Uint32> pdwReturnedProductType), int Function( int dwOSMajorVersion, int dwOSMinorVersion, int dwSpMajorVersion, int dwSpMinorVersion, Pointer<Uint32> pdwReturnedProductType)>('GetProductInfo'); /// Attempts to dequeue an I/O completion packet from the specified I/O /// completion port. If there is no completion packet queued, the function /// waits for a pending I/O operation associated with the completion port /// to complete. /// /// ```c /// BOOL GetQueuedCompletionStatus( /// HANDLE CompletionPort, /// LPDWORD lpNumberOfBytesTransferred, /// PULONG_PTR lpCompletionKey, /// LPOVERLAPPED *lpOverlapped, /// DWORD dwMilliseconds /// ); /// ``` /// {@category kernel32} int GetQueuedCompletionStatus( int CompletionPort, Pointer<Uint32> lpNumberOfBytesTransferred, Pointer<IntPtr> lpCompletionKey, Pointer<Pointer<OVERLAPPED>> lpOverlapped, int dwMilliseconds) => _GetQueuedCompletionStatus(CompletionPort, lpNumberOfBytesTransferred, lpCompletionKey, lpOverlapped, dwMilliseconds); late final _GetQueuedCompletionStatus = _kernel32.lookupFunction< Int32 Function( IntPtr CompletionPort, Pointer<Uint32> lpNumberOfBytesTransferred, Pointer<IntPtr> lpCompletionKey, Pointer<Pointer<OVERLAPPED>> lpOverlapped, Uint32 dwMilliseconds), int Function( int CompletionPort, Pointer<Uint32> lpNumberOfBytesTransferred, Pointer<IntPtr> lpCompletionKey, Pointer<Pointer<OVERLAPPED>> lpOverlapped, int dwMilliseconds)>('GetQueuedCompletionStatus'); /// Retrieves multiple completion port entries simultaneously. It waits for /// pending I/O operations that are associated with the specified /// completion port to complete. /// /// ```c /// BOOL GetQueuedCompletionStatusEx( /// HANDLE CompletionPort, /// LPOVERLAPPED_ENTRY lpCompletionPortEntries, /// ULONG ulCount, /// PULONG ulNumEntriesRemoved, /// DWORD dwMilliseconds, /// BOOL fAlertable /// ); /// ``` /// {@category kernel32} int GetQueuedCompletionStatusEx( int CompletionPort, Pointer<OVERLAPPED_ENTRY> lpCompletionPortEntries, int ulCount, Pointer<Uint32> ulNumEntriesRemoved, int dwMilliseconds, int fAlertable) => _GetQueuedCompletionStatusEx(CompletionPort, lpCompletionPortEntries, ulCount, ulNumEntriesRemoved, dwMilliseconds, fAlertable); late final _GetQueuedCompletionStatusEx = _kernel32.lookupFunction< Int32 Function( IntPtr CompletionPort, Pointer<OVERLAPPED_ENTRY> lpCompletionPortEntries, Uint32 ulCount, Pointer<Uint32> ulNumEntriesRemoved, Uint32 dwMilliseconds, Int32 fAlertable), int Function( int CompletionPort, Pointer<OVERLAPPED_ENTRY> lpCompletionPortEntries, int ulCount, Pointer<Uint32> ulNumEntriesRemoved, int dwMilliseconds, int fAlertable)>('GetQueuedCompletionStatusEx'); /// Retrieves the contents of the STARTUPINFO structure that was specified /// when the calling process was created. /// /// ```c /// void GetStartupInfoW( /// LPSTARTUPINFOW lpStartupInfo /// ); /// ``` /// {@category kernel32} void GetStartupInfo(Pointer<STARTUPINFO> lpStartupInfo) => _GetStartupInfo(lpStartupInfo); late final _GetStartupInfo = _kernel32.lookupFunction< Void Function(Pointer<STARTUPINFO> lpStartupInfo), void Function(Pointer<STARTUPINFO> lpStartupInfo)>('GetStartupInfoW'); /// Retrieves a handle to the specified standard device (standard input, /// standard output, or standard error). /// /// ```c /// HANDLE WINAPI GetStdHandle( /// _In_ DWORD nStdHandle /// ); /// ``` /// {@category kernel32} int GetStdHandle(int nStdHandle) => _GetStdHandle(nStdHandle); late final _GetStdHandle = _kernel32.lookupFunction< IntPtr Function(Uint32 nStdHandle), int Function(int nStdHandle)>('GetStdHandle'); /// Returns the language identifier for the system locale. /// /// ```c /// LANGID GetSystemDefaultLangID(); /// ``` /// {@category kernel32} int GetSystemDefaultLangID() => _GetSystemDefaultLangID(); late final _GetSystemDefaultLangID = _kernel32.lookupFunction<Uint16 Function(), int Function()>( 'GetSystemDefaultLangID'); /// Retrieves the system default locale name. /// /// ```c /// int GetSystemDefaultLocaleName( /// LPWSTR lpLocaleName, /// int cchLocaleName /// ); /// ``` /// {@category kernel32} int GetSystemDefaultLocaleName( Pointer<Utf16> lpLocaleName, int cchLocaleName) => _GetSystemDefaultLocaleName(lpLocaleName, cchLocaleName); late final _GetSystemDefaultLocaleName = _kernel32.lookupFunction< Int32 Function(Pointer<Utf16> lpLocaleName, Int32 cchLocaleName), int Function(Pointer<Utf16> lpLocaleName, int cchLocaleName)>('GetSystemDefaultLocaleName'); /// Retrieves the path of the system directory. The system directory /// contains system files such as dynamic-link libraries and drivers. /// /// ```c /// UINT GetSystemDirectoryW( /// LPWSTR lpBuffer, /// UINT uSize /// ); /// ``` /// {@category kernel32} int GetSystemDirectory(Pointer<Utf16> lpBuffer, int uSize) => _GetSystemDirectory(lpBuffer, uSize); late final _GetSystemDirectory = _kernel32.lookupFunction< Uint32 Function(Pointer<Utf16> lpBuffer, Uint32 uSize), int Function(Pointer<Utf16> lpBuffer, int uSize)>('GetSystemDirectoryW'); /// Retrieves information about the current system. To retrieve accurate /// information for an application running on WOW64, call the /// GetNativeSystemInfo function. /// /// ```c /// void GetSystemInfo( /// LPSYSTEM_INFO lpSystemInfo /// ); /// ``` /// {@category kernel32} void GetSystemInfo(Pointer<SYSTEM_INFO> lpSystemInfo) => _GetSystemInfo(lpSystemInfo); late final _GetSystemInfo = _kernel32.lookupFunction< Void Function(Pointer<SYSTEM_INFO> lpSystemInfo), void Function(Pointer<SYSTEM_INFO> lpSystemInfo)>('GetSystemInfo'); /// Retrieves the power status of the system. The status indicates whether /// the system is running on AC or DC power, whether the battery is /// currently charging, how much battery life remains, and if battery saver /// is on or off. /// /// ```c /// BOOL GetSystemPowerStatus( /// LPSYSTEM_POWER_STATUS lpSystemPowerStatus /// ); /// ``` /// {@category kernel32} int GetSystemPowerStatus(Pointer<SYSTEM_POWER_STATUS> lpSystemPowerStatus) => _GetSystemPowerStatus(lpSystemPowerStatus); late final _GetSystemPowerStatus = _kernel32.lookupFunction< Int32 Function(Pointer<SYSTEM_POWER_STATUS> lpSystemPowerStatus), int Function(Pointer<SYSTEM_POWER_STATUS> lpSystemPowerStatus)>( 'GetSystemPowerStatus'); /// Retrieves the current local date and time. /// /// ```c /// void GetSystemTime( /// LPSYSTEMTIME lpSystemTime /// ); /// ``` /// {@category kernel32} void GetSystemTime(Pointer<SYSTEMTIME> lpSystemTime) => _GetSystemTime(lpSystemTime); late final _GetSystemTime = _kernel32.lookupFunction< Void Function(Pointer<SYSTEMTIME> lpSystemTime), void Function(Pointer<SYSTEMTIME> lpSystemTime)>('GetSystemTime'); /// Retrieves system timing information. On a multiprocessor system, the /// values returned are the sum of the designated times across all /// processors. /// /// ```c /// BOOL GetSystemTimes( /// PFILETIME lpIdleTime, /// PFILETIME lpKernelTime, /// PFILETIME lpUserTime /// ); /// ``` /// {@category kernel32} int GetSystemTimes(Pointer<FILETIME> lpIdleTime, Pointer<FILETIME> lpKernelTime, Pointer<FILETIME> lpUserTime) => _GetSystemTimes(lpIdleTime, lpKernelTime, lpUserTime); late final _GetSystemTimes = _kernel32.lookupFunction< Int32 Function(Pointer<FILETIME> lpIdleTime, Pointer<FILETIME> lpKernelTime, Pointer<FILETIME> lpUserTime), int Function(Pointer<FILETIME> lpIdleTime, Pointer<FILETIME> lpKernelTime, Pointer<FILETIME> lpUserTime)>('GetSystemTimes'); /// Retrieves the path of the directory designated for temporary files. /// /// ```c /// DWORD GetTempPathW( /// DWORD nBufferLength, /// LPWSTR lpBuffer /// ); /// ``` /// {@category kernel32} int GetTempPath(int nBufferLength, Pointer<Utf16> lpBuffer) => _GetTempPath(nBufferLength, lpBuffer); late final _GetTempPath = _kernel32.lookupFunction< Uint32 Function(Uint32 nBufferLength, Pointer<Utf16> lpBuffer), int Function(int nBufferLength, Pointer<Utf16> lpBuffer)>('GetTempPathW'); /// Retrieves the thread identifier of the specified thread. /// /// ```c /// DWORD GetThreadId( /// HANDLE Thread /// ); /// ``` /// {@category kernel32} int GetThreadId(int Thread) => _GetThreadId(Thread); late final _GetThreadId = _kernel32.lookupFunction< Uint32 Function(IntPtr Thread), int Function(int Thread)>('GetThreadId'); /// Returns the locale identifier of the current locale for the calling /// thread. /// /// ```c /// LCID GetThreadLocale(); /// ``` /// {@category kernel32} int GetThreadLocale() => _GetThreadLocale(); late final _GetThreadLocale = _kernel32 .lookupFunction<Uint32 Function(), int Function()>('GetThreadLocale'); /// Retrieves timing information for the specified thread. /// /// ```c /// BOOL GetThreadTimes( /// HANDLE hThread, /// LPFILETIME lpCreationTime, /// LPFILETIME lpExitTime, /// LPFILETIME lpKernelTime, /// LPFILETIME lpUserTime /// ); /// ``` /// {@category kernel32} int GetThreadTimes( int hThread, Pointer<FILETIME> lpCreationTime, Pointer<FILETIME> lpExitTime, Pointer<FILETIME> lpKernelTime, Pointer<FILETIME> lpUserTime) => _GetThreadTimes( hThread, lpCreationTime, lpExitTime, lpKernelTime, lpUserTime); late final _GetThreadTimes = _kernel32.lookupFunction< Int32 Function( IntPtr hThread, Pointer<FILETIME> lpCreationTime, Pointer<FILETIME> lpExitTime, Pointer<FILETIME> lpKernelTime, Pointer<FILETIME> lpUserTime), int Function( int hThread, Pointer<FILETIME> lpCreationTime, Pointer<FILETIME> lpExitTime, Pointer<FILETIME> lpKernelTime, Pointer<FILETIME> lpUserTime)>('GetThreadTimes'); /// Returns the language identifier of the first user interface language /// for the current thread. /// /// ```c /// LANGID GetThreadUILanguage(); /// ``` /// {@category kernel32} int GetThreadUILanguage() => _GetThreadUILanguage(); late final _GetThreadUILanguage = _kernel32 .lookupFunction<Uint16 Function(), int Function()>('GetThreadUILanguage'); /// Returns the language identifier of the Region Format setting for the /// current user. /// /// ```c /// LANGID GetUserDefaultLangID(); /// ``` /// {@category kernel32} int GetUserDefaultLangID() => _GetUserDefaultLangID(); late final _GetUserDefaultLangID = _kernel32 .lookupFunction<Uint16 Function(), int Function()>('GetUserDefaultLangID'); /// Returns the locale identifier for the user default locale. /// /// ```c /// LCID GetUserDefaultLCID(); /// ``` /// {@category kernel32} int GetUserDefaultLCID() => _GetUserDefaultLCID(); late final _GetUserDefaultLCID = _kernel32 .lookupFunction<Uint32 Function(), int Function()>('GetUserDefaultLCID'); /// Retrieves the user default locale name. /// /// ```c /// int GetUserDefaultLocaleName( /// LPWSTR lpLocaleName, /// int cchLocaleName /// ); /// ``` /// {@category kernel32} int GetUserDefaultLocaleName(Pointer<Utf16> lpLocaleName, int cchLocaleName) => _GetUserDefaultLocaleName(lpLocaleName, cchLocaleName); late final _GetUserDefaultLocaleName = _kernel32.lookupFunction< Int32 Function(Pointer<Utf16> lpLocaleName, Int32 cchLocaleName), int Function(Pointer<Utf16> lpLocaleName, int cchLocaleName)>('GetUserDefaultLocaleName'); /// Gets information about the operating system version. /// /// ```c /// BOOL GetVersionExW( /// LPOSVERSIONINFOW lpVersionInformation /// ); /// ``` /// {@category kernel32} int GetVersionEx(Pointer<OSVERSIONINFO> lpVersionInformation) => _GetVersionEx(lpVersionInformation); late final _GetVersionEx = _kernel32.lookupFunction< Int32 Function(Pointer<OSVERSIONINFO> lpVersionInformation), int Function(Pointer<OSVERSIONINFO> lpVersionInformation)>('GetVersionExW'); /// Retrieves the volume mount point where the specified path is mounted. /// /// ```c /// BOOL GetVolumePathNameW( /// LPCWSTR lpszFileName, /// LPWSTR lpszVolumePathName, /// DWORD cchBufferLength); /// ``` /// {@category kernel32} int GetVolumePathName(Pointer<Utf16> lpszFileName, Pointer<Utf16> lpszVolumePathName, int cchBufferLength) => _GetVolumePathName(lpszFileName, lpszVolumePathName, cchBufferLength); late final _GetVolumePathName = _kernel32.lookupFunction< Int32 Function(Pointer<Utf16> lpszFileName, Pointer<Utf16> lpszVolumePathName, Uint32 cchBufferLength), int Function(Pointer<Utf16> lpszFileName, Pointer<Utf16> lpszVolumePathName, int cchBufferLength)>('GetVolumePathNameW'); /// Retrieves a list of drive letters and mounted folder paths for the /// specified volume. /// /// ```c /// BOOL GetVolumePathNamesForVolumeNameW( /// LPCWSTR lpszVolumeName, /// LPWCH lpszVolumePathNames, /// DWORD cchBufferLength, /// PDWORD lpcchReturnLength /// ); /// ``` /// {@category kernel32} int GetVolumePathNamesForVolumeName( Pointer<Utf16> lpszVolumeName, Pointer<Utf16> lpszVolumePathNames, int cchBufferLength, Pointer<Uint32> lpcchReturnLength) => _GetVolumePathNamesForVolumeName(lpszVolumeName, lpszVolumePathNames, cchBufferLength, lpcchReturnLength); late final _GetVolumePathNamesForVolumeName = _kernel32.lookupFunction< Int32 Function( Pointer<Utf16> lpszVolumeName, Pointer<Utf16> lpszVolumePathNames, Uint32 cchBufferLength, Pointer<Uint32> lpcchReturnLength), int Function( Pointer<Utf16> lpszVolumeName, Pointer<Utf16> lpszVolumePathNames, int cchBufferLength, Pointer<Uint32> lpcchReturnLength)>('GetVolumePathNamesForVolumeNameW'); /// Allocates the specified number of bytes from the heap. /// /// ```c /// HGLOBAL GlobalAlloc( /// UINT uFlags, /// SIZE_T dwBytes /// ); /// ``` /// {@category kernel32} int GlobalAlloc(int uFlags, int dwBytes) => _GlobalAlloc(uFlags, dwBytes); late final _GlobalAlloc = _kernel32.lookupFunction< IntPtr Function(Uint32 uFlags, IntPtr dwBytes), int Function(int uFlags, int dwBytes)>('GlobalAlloc'); /// Frees the specified global memory object and invalidates its handle. /// /// ```c /// HGLOBAL GlobalFree( /// _Frees_ptr_opt_ HGLOBAL hMem /// ); /// ``` /// {@category kernel32} int GlobalFree(int hMem) => _GlobalFree(hMem); late final _GlobalFree = _kernel32.lookupFunction<IntPtr Function(IntPtr hMem), int Function(int hMem)>('GlobalFree'); /// Locks a global memory object and returns a pointer to the first byte of /// the object's memory block. /// /// ```c /// LPVOID GlobalLock( /// HGLOBAL hMem /// ); /// ``` /// {@category kernel32} Pointer GlobalLock(int hMem) => _GlobalLock(hMem); late final _GlobalLock = _kernel32.lookupFunction<Pointer Function(IntPtr hMem), Pointer Function(int hMem)>('GlobalLock'); /// Retrieves the current size of the specified global memory object, in /// bytes. /// /// ```c /// SIZE_T GlobalSize( /// HGLOBAL hMem /// ); /// ``` /// {@category kernel32} int GlobalSize(int hMem) => _GlobalSize(hMem); late final _GlobalSize = _kernel32.lookupFunction<IntPtr Function(IntPtr hMem), int Function(int hMem)>('GlobalSize'); /// Decrements the lock count associated with a memory object that was /// allocated with GMEM_MOVEABLE. This function has no effect on memory /// objects allocated with GMEM_FIXED. /// /// ```c /// BOOL GlobalUnlock( /// HGLOBAL hMem /// ); /// ``` /// {@category kernel32} int GlobalUnlock(int hMem) => _GlobalUnlock(hMem); late final _GlobalUnlock = _kernel32.lookupFunction<Int32 Function(IntPtr hMem), int Function(int hMem)>('GlobalUnlock'); /// Allocates a block of memory from a heap. The allocated memory is not /// movable. /// /// ```c /// LPVOID HeapAlloc( /// HANDLE hHeap, /// DWORD dwFlags, /// SIZE_T dwBytes /// ); /// ``` /// {@category kernel32} Pointer HeapAlloc(int hHeap, int dwFlags, int dwBytes) => _HeapAlloc(hHeap, dwFlags, dwBytes); late final _HeapAlloc = _kernel32.lookupFunction< Pointer Function(IntPtr hHeap, Uint32 dwFlags, IntPtr dwBytes), Pointer Function(int hHeap, int dwFlags, int dwBytes)>('HeapAlloc'); /// Returns the size of the largest committed free block in the specified /// heap. If the Disable heap coalesce on free global flag is set, this /// function also coalesces adjacent free blocks of memory in the heap. /// /// ```c /// SIZE_T HeapCompact( /// HANDLE hHeap, /// DWORD dwFlags /// ); /// ``` /// {@category kernel32} int HeapCompact(int hHeap, int dwFlags) => _HeapCompact(hHeap, dwFlags); late final _HeapCompact = _kernel32.lookupFunction< IntPtr Function(IntPtr hHeap, Uint32 dwFlags), int Function(int hHeap, int dwFlags)>('HeapCompact'); /// Creates a private heap object that can be used by the calling process. /// The function reserves space in the virtual address space of the process /// and allocates physical storage for a specified initial portion of this /// block. /// /// ```c /// HANDLE HeapCreate( /// DWORD flOptions, /// SIZE_T dwInitialSize, /// SIZE_T dwMaximumSize /// ); /// ``` /// {@category kernel32} int HeapCreate(int flOptions, int dwInitialSize, int dwMaximumSize) => _HeapCreate(flOptions, dwInitialSize, dwMaximumSize); late final _HeapCreate = _kernel32.lookupFunction< IntPtr Function( Uint32 flOptions, IntPtr dwInitialSize, IntPtr dwMaximumSize), int Function( int flOptions, int dwInitialSize, int dwMaximumSize)>('HeapCreate'); /// Destroys the specified heap object. It decommits and releases all the /// pages of a private heap object, and it invalidates the handle to the /// heap. /// /// ```c /// BOOL HeapDestroy( /// HANDLE hHeap /// ); /// ``` /// {@category kernel32} int HeapDestroy(int hHeap) => _HeapDestroy(hHeap); late final _HeapDestroy = _kernel32.lookupFunction<Int32 Function(IntPtr hHeap), int Function(int hHeap)>('HeapDestroy'); /// Frees a memory block allocated from a heap by the HeapAlloc or /// HeapReAlloc function. /// /// ```c /// BOOL HeapFree( /// HANDLE hHeap, /// DWORD dwFlags, /// _Frees_ptr_opt_ LPVOID lpMem /// ); /// ``` /// {@category kernel32} int HeapFree(int hHeap, int dwFlags, Pointer lpMem) => _HeapFree(hHeap, dwFlags, lpMem); late final _HeapFree = _kernel32.lookupFunction< Int32 Function(IntPtr hHeap, Uint32 dwFlags, Pointer lpMem), int Function(int hHeap, int dwFlags, Pointer lpMem)>('HeapFree'); /// Attempts to acquire the critical section object, or lock, that is /// associated with a specified heap. /// /// ```c /// BOOL HeapLock( /// HANDLE hHeap /// ); /// ``` /// {@category kernel32} int HeapLock(int hHeap) => _HeapLock(hHeap); late final _HeapLock = _kernel32.lookupFunction<Int32 Function(IntPtr hHeap), int Function(int hHeap)>('HeapLock'); /// Retrieves information about the specified heap. /// /// ```c /// BOOL HeapQueryInformation( /// HANDLE HeapHandle, /// HEAP_INFORMATION_CLASS HeapInformationClass, /// PVOID HeapInformation, /// SIZE_T HeapInformationLength, /// PSIZE_T ReturnLength /// ); /// ``` /// {@category kernel32} int HeapQueryInformation( int HeapHandle, int HeapInformationClass, Pointer HeapInformation, int HeapInformationLength, Pointer<IntPtr> ReturnLength) => _HeapQueryInformation(HeapHandle, HeapInformationClass, HeapInformation, HeapInformationLength, ReturnLength); late final _HeapQueryInformation = _kernel32.lookupFunction< Int32 Function( IntPtr HeapHandle, Int32 HeapInformationClass, Pointer HeapInformation, IntPtr HeapInformationLength, Pointer<IntPtr> ReturnLength), int Function( int HeapHandle, int HeapInformationClass, Pointer HeapInformation, int HeapInformationLength, Pointer<IntPtr> ReturnLength)>('HeapQueryInformation'); /// Retrieves information about the specified heap. /// /// ```c /// DECLSPEC_ALLOCATOR LPVOID HeapReAlloc( /// HANDLE hHeap, /// DWORD dwFlags, /// _Frees_ptr_opt_ LPVOID lpMem, /// SIZE_T dwBytes /// ); /// ``` /// {@category kernel32} Pointer HeapReAlloc(int hHeap, int dwFlags, Pointer lpMem, int dwBytes) => _HeapReAlloc(hHeap, dwFlags, lpMem, dwBytes); late final _HeapReAlloc = _kernel32.lookupFunction< Pointer Function( IntPtr hHeap, Uint32 dwFlags, Pointer lpMem, IntPtr dwBytes), Pointer Function( int hHeap, int dwFlags, Pointer lpMem, int dwBytes)>('HeapReAlloc'); /// Enables features for a specified heap. /// /// ```c /// BOOL HeapSetInformation( /// HANDLE HeapHandle, /// HEAP_INFORMATION_CLASS HeapInformationClass, /// PVOID HeapInformation, /// SIZE_T HeapInformationLength /// ); /// ``` /// {@category kernel32} int HeapSetInformation(int HeapHandle, int HeapInformationClass, Pointer HeapInformation, int HeapInformationLength) => _HeapSetInformation(HeapHandle, HeapInformationClass, HeapInformation, HeapInformationLength); late final _HeapSetInformation = _kernel32.lookupFunction< Int32 Function(IntPtr HeapHandle, Int32 HeapInformationClass, Pointer HeapInformation, IntPtr HeapInformationLength), int Function( int HeapHandle, int HeapInformationClass, Pointer HeapInformation, int HeapInformationLength)>('HeapSetInformation'); /// Retrieves the size of a memory block allocated from a heap by the /// HeapAlloc or HeapReAlloc function. /// /// ```c /// SIZE_T HeapSize( /// HANDLE hHeap, /// DWORD dwFlags, /// LPCVOID lpMem /// ); /// ``` /// {@category kernel32} int HeapSize(int hHeap, int dwFlags, Pointer lpMem) => _HeapSize(hHeap, dwFlags, lpMem); late final _HeapSize = _kernel32.lookupFunction< IntPtr Function(IntPtr hHeap, Uint32 dwFlags, Pointer lpMem), int Function(int hHeap, int dwFlags, Pointer lpMem)>('HeapSize'); /// Releases ownership of the critical section object, or lock, that is /// associated with a specified heap. It reverses the action of the /// HeapLock function. /// /// ```c /// BOOL HeapUnlock( /// HANDLE hHeap /// ); /// ``` /// {@category kernel32} int HeapUnlock(int hHeap) => _HeapUnlock(hHeap); late final _HeapUnlock = _kernel32.lookupFunction<Int32 Function(IntPtr hHeap), int Function(int hHeap)>('HeapUnlock'); /// Validates the specified heap. The function scans all the memory blocks /// in the heap and verifies that the heap control structures maintained by /// the heap manager are in a consistent state. You can also use the /// HeapValidate function to validate a single memory block within a /// specified heap without checking the validity of the entire heap. /// /// ```c /// BOOL HeapValidate( /// HANDLE hHeap, /// DWORD dwFlags, /// LPCVOID lpMem /// ); /// ``` /// {@category kernel32} int HeapValidate(int hHeap, int dwFlags, Pointer lpMem) => _HeapValidate(hHeap, dwFlags, lpMem); late final _HeapValidate = _kernel32.lookupFunction< Int32 Function(IntPtr hHeap, Uint32 dwFlags, Pointer lpMem), int Function(int hHeap, int dwFlags, Pointer lpMem)>('HeapValidate'); /// Enumerates the memory blocks in the specified heap. /// /// ```c /// BOOL HeapWalk( /// HANDLE hHeap, /// LPPROCESS_HEAP_ENTRY lpEntry /// ); /// ``` /// {@category kernel32} int HeapWalk(int hHeap, Pointer<PROCESS_HEAP_ENTRY> lpEntry) => _HeapWalk(hHeap, lpEntry); late final _HeapWalk = _kernel32.lookupFunction< Int32 Function(IntPtr hHeap, Pointer<PROCESS_HEAP_ENTRY> lpEntry), int Function(int hHeap, Pointer<PROCESS_HEAP_ENTRY> lpEntry)>('HeapWalk'); /// Initializes the specified list of attributes for process and thread /// creation. /// /// ```c /// BOOL InitializeProcThreadAttributeList( /// LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList, /// DWORD dwAttributeCount, /// DWORD dwFlags, /// PSIZE_T lpSize /// ); /// ``` /// {@category kernel32} int InitializeProcThreadAttributeList(Pointer lpAttributeList, int dwAttributeCount, int dwFlags, Pointer<IntPtr> lpSize) => _InitializeProcThreadAttributeList( lpAttributeList, dwAttributeCount, dwFlags, lpSize); late final _InitializeProcThreadAttributeList = _kernel32.lookupFunction< Int32 Function(Pointer lpAttributeList, Uint32 dwAttributeCount, Uint32 dwFlags, Pointer<IntPtr> lpSize), int Function(Pointer lpAttributeList, int dwAttributeCount, int dwFlags, Pointer<IntPtr> lpSize)>('InitializeProcThreadAttributeList'); /// Determines whether the calling process is being debugged by a user-mode /// debugger. /// /// ```c /// BOOL IsDebuggerPresent(); /// ``` /// {@category kernel32} int IsDebuggerPresent() => _IsDebuggerPresent(); late final _IsDebuggerPresent = _kernel32 .lookupFunction<Int32 Function(), int Function()>('IsDebuggerPresent'); /// Indicates if the OS was booted from a VHD container. /// /// ```c /// BOOL IsNativeVhdBoot( /// PBOOL NativeVhdBoot /// ); /// ``` /// {@category kernel32} int IsNativeVhdBoot(Pointer<Int32> NativeVhdBoot) => _IsNativeVhdBoot(NativeVhdBoot); late final _IsNativeVhdBoot = _kernel32.lookupFunction< Int32 Function(Pointer<Int32> NativeVhdBoot), int Function(Pointer<Int32> NativeVhdBoot)>('IsNativeVhdBoot'); /// Determines the current state of the computer. /// /// ```c /// BOOL IsSystemResumeAutomatic(); /// ``` /// {@category kernel32} int IsSystemResumeAutomatic() => _IsSystemResumeAutomatic(); late final _IsSystemResumeAutomatic = _kernel32.lookupFunction<Int32 Function(), int Function()>( 'IsSystemResumeAutomatic'); /// Determines if the specified locale name is valid for a locale that is /// installed or supported on the operating system. /// /// ```c /// BOOL IsValidLocaleName( /// LPCWSTR lpLocaleName /// ); /// ``` /// {@category kernel32} int IsValidLocaleName(Pointer<Utf16> lpLocaleName) => _IsValidLocaleName(lpLocaleName); late final _IsValidLocaleName = _kernel32.lookupFunction< Int32 Function(Pointer<Utf16> lpLocaleName), int Function(Pointer<Utf16> lpLocaleName)>('IsValidLocaleName'); /// Determines whether the specified process is running under WOW64. Also /// returns additional machine process and architecture information. /// /// ```c /// BOOL IsWow64Process2( /// HANDLE hProcess, /// USHORT *pProcessMachine, /// USHORT *pNativeMachine /// ); /// ``` /// {@category kernel32} int IsWow64Process2(int hProcess, Pointer<Uint16> pProcessMachine, Pointer<Uint16> pNativeMachine) => _IsWow64Process2(hProcess, pProcessMachine, pNativeMachine); late final _IsWow64Process2 = _kernel32.lookupFunction< Int32 Function(IntPtr hProcess, Pointer<Uint16> pProcessMachine, Pointer<Uint16> pNativeMachine), int Function(int hProcess, Pointer<Uint16> pProcessMachine, Pointer<Uint16> pNativeMachine)>('IsWow64Process2'); /// Loads the specified module into the address space of the calling /// process. The specified module may cause other modules to be loaded. /// /// ```c /// HMODULE LoadLibraryW( /// LPCWSTR lpLibFileName /// ); /// ``` /// {@category kernel32} int LoadLibrary(Pointer<Utf16> lpLibFileName) => _LoadLibrary(lpLibFileName); late final _LoadLibrary = _kernel32.lookupFunction< IntPtr Function(Pointer<Utf16> lpLibFileName), int Function(Pointer<Utf16> lpLibFileName)>('LoadLibraryW'); /// Retrieves a handle that can be used to obtain a pointer to the first /// byte of the specified resource in memory. /// /// ```c /// HGLOBAL LoadResource( /// HMODULE hModule, /// HRSRC hResInfo /// ); /// ``` /// {@category kernel32} int LoadResource(int hModule, int hResInfo) => _LoadResource(hModule, hResInfo); late final _LoadResource = _kernel32.lookupFunction< IntPtr Function(IntPtr hModule, IntPtr hResInfo), int Function(int hModule, int hResInfo)>('LoadResource'); /// Frees the specified local memory object and invalidates its handle. /// /// ```c /// HLOCAL LocalFree( /// _Frees_ptr_opt_ HLOCAL hMem /// ); /// ``` /// {@category kernel32} int LocalFree(int hMem) => _LocalFree(hMem); late final _LocalFree = _kernel32.lookupFunction<IntPtr Function(IntPtr hMem), int Function(int hMem)>('LocalFree'); /// Retrieves a pointer to the specified resource in memory. /// /// ```c /// LPVOID LockResource( /// HGLOBAL hResData /// ); /// ``` /// {@category kernel32} Pointer LockResource(int hResData) => _LockResource(hResData); late final _LockResource = _kernel32.lookupFunction< Pointer Function(IntPtr hResData), Pointer Function(int hResData)>('LockResource'); /// Moves an existing file or a directory, including its children. /// /// ```c /// BOOL MoveFileW( /// LPCWSTR lpExistingFileName, /// LPCWSTR lpNewFileName /// ); /// ``` /// {@category kernel32} int MoveFile(Pointer<Utf16> lpExistingFileName, Pointer<Utf16> lpNewFileName) => _MoveFile(lpExistingFileName, lpNewFileName); late final _MoveFile = _kernel32.lookupFunction< Int32 Function( Pointer<Utf16> lpExistingFileName, Pointer<Utf16> lpNewFileName), int Function(Pointer<Utf16> lpExistingFileName, Pointer<Utf16> lpNewFileName)>('MoveFileW'); /// Opens an existing named event object. /// /// ```c /// HANDLE OpenEventW( /// DWORD dwDesiredAccess, /// BOOL bInheritHandle, /// LPCWSTR lpName /// ); /// ``` /// {@category kernel32} int OpenEvent(int dwDesiredAccess, int bInheritHandle, Pointer<Utf16> lpName) => _OpenEvent(dwDesiredAccess, bInheritHandle, lpName); late final _OpenEvent = _kernel32.lookupFunction< IntPtr Function( Uint32 dwDesiredAccess, Int32 bInheritHandle, Pointer<Utf16> lpName), int Function(int dwDesiredAccess, int bInheritHandle, Pointer<Utf16> lpName)>('OpenEventW'); /// Opens an existing local process object. /// /// ```c /// HANDLE OpenProcess( /// DWORD dwDesiredAccess, /// BOOL bInheritHandle, /// DWORD dwProcessId /// ); /// ``` /// {@category kernel32} int OpenProcess(int dwDesiredAccess, int bInheritHandle, int dwProcessId) => _OpenProcess(dwDesiredAccess, bInheritHandle, dwProcessId); late final _OpenProcess = _kernel32.lookupFunction< IntPtr Function( Uint32 dwDesiredAccess, Int32 bInheritHandle, Uint32 dwProcessId), int Function(int dwDesiredAccess, int bInheritHandle, int dwProcessId)>('OpenProcess'); /// Sends a string to the debugger for display. /// /// ```c /// void OutputDebugStringW( /// LPCWSTR lpOutputString /// ); /// ``` /// {@category kernel32} void OutputDebugString(Pointer<Utf16> lpOutputString) => _OutputDebugString(lpOutputString); late final _OutputDebugString = _kernel32.lookupFunction< Void Function(Pointer<Utf16> lpOutputString), void Function(Pointer<Utf16> lpOutputString)>('OutputDebugStringW'); /// Gets the package family name for the specified package full name. /// /// ```c /// LONG PackageFamilyNameFromFullName( /// PCWSTR packageFullName, /// UINT32 *packageFamilyNameLength, /// PWSTR packageFamilyName /// ); /// ``` /// {@category kernel32} int PackageFamilyNameFromFullName( Pointer<Utf16> packageFullName, Pointer<Uint32> packageFamilyNameLength, Pointer<Utf16> packageFamilyName) => _PackageFamilyNameFromFullName( packageFullName, packageFamilyNameLength, packageFamilyName); late final _PackageFamilyNameFromFullName = _kernel32.lookupFunction< Int32 Function( Pointer<Utf16> packageFullName, Pointer<Uint32> packageFamilyNameLength, Pointer<Utf16> packageFamilyName), int Function( Pointer<Utf16> packageFullName, Pointer<Uint32> packageFamilyNameLength, Pointer<Utf16> packageFamilyName)>('PackageFamilyNameFromFullName'); /// Copies data from a named or anonymous pipe into a buffer without /// removing it from the pipe. It also returns information about data in /// the pipe. /// /// ```c /// BOOL PeekNamedPipe( /// HANDLE hNamedPipe, /// LPVOID lpBuffer, /// DWORD nBufferSize, /// LPDWORD lpBytesRead, /// LPDWORD lpTotalBytesAvail, /// LPDWORD lpBytesLeftThisMessage); /// ``` /// {@category kernel32} int PeekNamedPipe( int hNamedPipe, Pointer lpBuffer, int nBufferSize, Pointer<Uint32> lpBytesRead, Pointer<Uint32> lpTotalBytesAvail, Pointer<Uint32> lpBytesLeftThisMessage) => _PeekNamedPipe(hNamedPipe, lpBuffer, nBufferSize, lpBytesRead, lpTotalBytesAvail, lpBytesLeftThisMessage); late final _PeekNamedPipe = _kernel32.lookupFunction< Int32 Function( IntPtr hNamedPipe, Pointer lpBuffer, Uint32 nBufferSize, Pointer<Uint32> lpBytesRead, Pointer<Uint32> lpTotalBytesAvail, Pointer<Uint32> lpBytesLeftThisMessage), int Function( int hNamedPipe, Pointer lpBuffer, int nBufferSize, Pointer<Uint32> lpBytesRead, Pointer<Uint32> lpTotalBytesAvail, Pointer<Uint32> lpBytesLeftThisMessage)>('PeekNamedPipe'); /// Posts an I/O completion packet to an I/O completion port. /// /// ```c /// BOOL PostQueuedCompletionStatus( /// HANDLE CompletionPort, /// DWORD dwNumberOfBytesTransferred, /// ULONG_PTR dwCompletionKey, /// LPOVERLAPPED lpOverlapped /// ); /// ``` /// {@category kernel32} int PostQueuedCompletionStatus( int CompletionPort, int dwNumberOfBytesTransferred, int dwCompletionKey, Pointer<OVERLAPPED> lpOverlapped) => _PostQueuedCompletionStatus(CompletionPort, dwNumberOfBytesTransferred, dwCompletionKey, lpOverlapped); late final _PostQueuedCompletionStatus = _kernel32.lookupFunction< Int32 Function(IntPtr CompletionPort, Uint32 dwNumberOfBytesTransferred, IntPtr dwCompletionKey, Pointer<OVERLAPPED> lpOverlapped), int Function( int CompletionPort, int dwNumberOfBytesTransferred, int dwCompletionKey, Pointer<OVERLAPPED> lpOverlapped)>('PostQueuedCompletionStatus'); /// Discards all characters from the output or input buffer of a specified /// communications resource. It can also terminate pending read or write /// operations on the resource. /// /// ```c /// BOOL PurgeComm( /// HANDLE hFile, /// DWORD dwFlags /// ); /// ``` /// {@category kernel32} int PurgeComm(int hFile, int dwFlags) => _PurgeComm(hFile, dwFlags); late final _PurgeComm = _kernel32.lookupFunction< Int32 Function(IntPtr hFile, Uint32 dwFlags), int Function(int hFile, int dwFlags)>('PurgeComm'); /// Retrieves information about MS-DOS device names. The function can /// obtain the current mapping for a particular MS-DOS device name. The /// function can also obtain a list of all existing MS-DOS device names. /// /// ```c /// DWORD QueryDosDeviceW( /// LPCWSTR lpDeviceName, /// LPWSTR lpTargetPath, /// DWORD ucchMax /// ); /// ``` /// {@category kernel32} int QueryDosDevice(Pointer<Utf16> lpDeviceName, Pointer<Utf16> lpTargetPath, int ucchMax) => _QueryDosDevice(lpDeviceName, lpTargetPath, ucchMax); late final _QueryDosDevice = _kernel32.lookupFunction< Uint32 Function(Pointer<Utf16> lpDeviceName, Pointer<Utf16> lpTargetPath, Uint32 ucchMax), int Function(Pointer<Utf16> lpDeviceName, Pointer<Utf16> lpTargetPath, int ucchMax)>('QueryDosDeviceW'); /// Retrieves the current value of the performance counter, which is a high /// resolution (<1us) time stamp that can be used for time-interval /// measurements. /// /// ```c /// BOOL QueryPerformanceCounter( /// LARGE_INTEGER *lpPerformanceCount /// ); /// ``` /// {@category kernel32} int QueryPerformanceCounter(Pointer<Int64> lpPerformanceCount) => _QueryPerformanceCounter(lpPerformanceCount); late final _QueryPerformanceCounter = _kernel32.lookupFunction< Int32 Function(Pointer<Int64> lpPerformanceCount), int Function(Pointer<Int64> lpPerformanceCount)>('QueryPerformanceCounter'); /// Retrieves the frequency of the performance counter. The frequency of /// the performance counter is fixed at system boot and is consistent /// across all processors. Therefore, the frequency need only be queried /// upon application initialization, and the result can be cached. /// /// ```c /// BOOL QueryPerformanceFrequency( /// LARGE_INTEGER *lpFrequency /// ); /// ``` /// {@category kernel32} int QueryPerformanceFrequency(Pointer<Int64> lpFrequency) => _QueryPerformanceFrequency(lpFrequency); late final _QueryPerformanceFrequency = _kernel32.lookupFunction< Int32 Function(Pointer<Int64> lpFrequency), int Function(Pointer<Int64> lpFrequency)>('QueryPerformanceFrequency'); /// Reads character input from the console input buffer and removes it from /// the buffer. /// /// ```c /// BOOL WINAPI ReadConsoleW( /// _In_     HANDLE  hConsoleInput, /// _Out_    LPVOID  lpBuffer, /// _In_     DWORD   nNumberOfCharsToRead, /// _Out_    LPDWORD lpNumberOfCharsRead, /// _In_opt_ LPVOID  pInputControl /// ); /// ``` /// {@category kernel32} int ReadConsole( int hConsoleInput, Pointer lpBuffer, int nNumberOfCharsToRead, Pointer<Uint32> lpNumberOfCharsRead, Pointer<CONSOLE_READCONSOLE_CONTROL> pInputControl) => _ReadConsole(hConsoleInput, lpBuffer, nNumberOfCharsToRead, lpNumberOfCharsRead, pInputControl); late final _ReadConsole = _kernel32.lookupFunction< Int32 Function( IntPtr hConsoleInput, Pointer lpBuffer, Uint32 nNumberOfCharsToRead, Pointer<Uint32> lpNumberOfCharsRead, Pointer<CONSOLE_READCONSOLE_CONTROL> pInputControl), int Function( int hConsoleInput, Pointer lpBuffer, int nNumberOfCharsToRead, Pointer<Uint32> lpNumberOfCharsRead, Pointer<CONSOLE_READCONSOLE_CONTROL> pInputControl)>('ReadConsoleW'); /// Reads data from the specified file or input/output (I/O) device. Reads /// occur at the position specified by the file pointer if supported by the /// device. /// /// ```c /// BOOL ReadFile( /// HANDLE hFile, /// LPVOID lpBuffer, /// DWORD nNumberOfBytesToRead, /// LPDWORD lpNumberOfBytesRead, /// LPOVERLAPPED lpOverlapped /// ); /// ``` /// {@category kernel32} int ReadFile( int hFile, Pointer lpBuffer, int nNumberOfBytesToRead, Pointer<Uint32> lpNumberOfBytesRead, Pointer<OVERLAPPED> lpOverlapped) => _ReadFile(hFile, lpBuffer, nNumberOfBytesToRead, lpNumberOfBytesRead, lpOverlapped); late final _ReadFile = _kernel32.lookupFunction< Int32 Function(IntPtr hFile, Pointer lpBuffer, Uint32 nNumberOfBytesToRead, Pointer<Uint32> lpNumberOfBytesRead, Pointer<OVERLAPPED> lpOverlapped), int Function( int hFile, Pointer lpBuffer, int nNumberOfBytesToRead, Pointer<Uint32> lpNumberOfBytesRead, Pointer<OVERLAPPED> lpOverlapped)>('ReadFile'); /// ReadProcessMemory copies the data in the specified address range from /// the address space of the specified process into the specified buffer of /// the current process. Any process that has a handle with PROCESS_VM_READ /// access can call the function. /// /// ```c /// BOOL ReadProcessMemory( /// HANDLE hProcess, /// LPCVOID lpBaseAddress, /// LPVOID lpBuffer, /// SIZE_T nSize, /// SIZE_T *lpNumberOfBytesRead /// ); /// ``` /// {@category kernel32} int ReadProcessMemory(int hProcess, Pointer lpBaseAddress, Pointer lpBuffer, int nSize, Pointer<IntPtr> lpNumberOfBytesRead) => _ReadProcessMemory( hProcess, lpBaseAddress, lpBuffer, nSize, lpNumberOfBytesRead); late final _ReadProcessMemory = _kernel32.lookupFunction< Int32 Function(IntPtr hProcess, Pointer lpBaseAddress, Pointer lpBuffer, IntPtr nSize, Pointer<IntPtr> lpNumberOfBytesRead), int Function(int hProcess, Pointer lpBaseAddress, Pointer lpBuffer, int nSize, Pointer<IntPtr> lpNumberOfBytesRead)>('ReadProcessMemory'); /// The ReleaseActCtx function decrements the reference count of the /// specified activation context. /// /// ```c /// void ReleaseActCtx( /// HANDLE hActCtx /// ); /// ``` /// {@category kernel32} void ReleaseActCtx(int hActCtx) => _ReleaseActCtx(hActCtx); late final _ReleaseActCtx = _kernel32.lookupFunction< Void Function(IntPtr hActCtx), void Function(int hActCtx)>('ReleaseActCtx'); /// Deletes an existing empty directory. /// /// ```c /// BOOL RemoveDirectoryW( /// LPCWSTR lpPathName /// ); /// ``` /// {@category kernel32} int RemoveDirectory(Pointer<Utf16> lpPathName) => _RemoveDirectory(lpPathName); late final _RemoveDirectory = _kernel32.lookupFunction< Int32 Function(Pointer<Utf16> lpPathName), int Function(Pointer<Utf16> lpPathName)>('RemoveDirectoryW'); /// Reopens the specified file system object with different access rights, /// sharing mode, and flags. /// /// ```c /// HANDLE ReOpenFile( /// HANDLE hOriginalFile, /// DWORD dwDesiredAccess, /// DWORD dwShareMode, /// DWORD dwFlagsAndAttributes); /// ``` /// {@category kernel32} int ReOpenFile(int hOriginalFile, int dwDesiredAccess, int dwShareMode, int dwFlagsAndAttributes) => _ReOpenFile( hOriginalFile, dwDesiredAccess, dwShareMode, dwFlagsAndAttributes); late final _ReOpenFile = _kernel32.lookupFunction< IntPtr Function(IntPtr hOriginalFile, Uint32 dwDesiredAccess, Uint32 dwShareMode, Uint32 dwFlagsAndAttributes), int Function(int hOriginalFile, int dwDesiredAccess, int dwShareMode, int dwFlagsAndAttributes)>('ReOpenFile'); /// Sets the specified event object to the nonsignaled state. /// /// ```c /// BOOL ResetEvent( /// HANDLE hEvent /// ); /// ``` /// {@category kernel32} int ResetEvent(int hEvent) => _ResetEvent(hEvent); late final _ResetEvent = _kernel32.lookupFunction<Int32 Function(IntPtr hEvent), int Function(int hEvent)>('ResetEvent'); /// Resizes the internal buffers for a pseudoconsole to the given size. /// /// ```c /// HRESULT WINAPI ResizePseudoConsole( /// _In_ HPCON hPC , /// _In_ COORD size /// ); /// ``` /// {@category kernel32} int ResizePseudoConsole(int hPC, COORD size) => _ResizePseudoConsole(hPC, size); late final _ResizePseudoConsole = _kernel32.lookupFunction< Int32 Function(IntPtr hPC, COORD size), int Function(int hPC, COORD size)>('ResizePseudoConsole'); /// Moves a block of data in a screen buffer. The effects of the move can /// be limited by specifying a clipping rectangle, so the contents of the /// console screen buffer outside the clipping rectangle are unchanged. /// /// ```c /// BOOL WINAPI ScrollConsoleScreenBufferW( /// _In_           HANDLE     hConsoleOutput, /// _In_     const SMALL_RECT *lpScrollRectangle, /// _In_opt_ const SMALL_RECT *lpClipRectangle, /// _In_           COORD      dwDestinationOrigin, /// _In_     const CHAR_INFO  *lpFill /// ); /// ``` /// {@category kernel32} int ScrollConsoleScreenBuffer( int hConsoleOutput, Pointer<SMALL_RECT> lpScrollRectangle, Pointer<SMALL_RECT> lpClipRectangle, COORD dwDestinationOrigin, Pointer<CHAR_INFO> lpFill) => _ScrollConsoleScreenBuffer(hConsoleOutput, lpScrollRectangle, lpClipRectangle, dwDestinationOrigin, lpFill); late final _ScrollConsoleScreenBuffer = _kernel32.lookupFunction< Int32 Function( IntPtr hConsoleOutput, Pointer<SMALL_RECT> lpScrollRectangle, Pointer<SMALL_RECT> lpClipRectangle, COORD dwDestinationOrigin, Pointer<CHAR_INFO> lpFill), int Function( int hConsoleOutput, Pointer<SMALL_RECT> lpScrollRectangle, Pointer<SMALL_RECT> lpClipRectangle, COORD dwDestinationOrigin, Pointer<CHAR_INFO> lpFill)>('ScrollConsoleScreenBufferW'); /// Suspends character transmission for a specified communications device /// and places the transmission line in a break state until the /// ClearCommBreak function is called. /// /// ```c /// BOOL SetCommBreak( /// HANDLE hFile /// ); /// ``` /// {@category kernel32} int SetCommBreak(int hFile) => _SetCommBreak(hFile); late final _SetCommBreak = _kernel32.lookupFunction< Int32 Function(IntPtr hFile), int Function(int hFile)>('SetCommBreak'); /// Sets the current configuration of a communications device. /// /// ```c /// BOOL SetCommConfig( /// HANDLE hCommDev, /// LPCOMMCONFIG lpCC, /// DWORD dwSize /// ); /// ``` /// {@category kernel32} int SetCommConfig(int hCommDev, Pointer<COMMCONFIG> lpCC, int dwSize) => _SetCommConfig(hCommDev, lpCC, dwSize); late final _SetCommConfig = _kernel32.lookupFunction< Int32 Function(IntPtr hCommDev, Pointer<COMMCONFIG> lpCC, Uint32 dwSize), int Function( int hCommDev, Pointer<COMMCONFIG> lpCC, int dwSize)>('SetCommConfig'); /// Specifies a set of events to be monitored for a communications device. /// /// ```c /// BOOL SetCommMask( /// HANDLE hFile, /// DWORD dwEvtMask /// ); /// ``` /// {@category kernel32} int SetCommMask(int hFile, int dwEvtMask) => _SetCommMask(hFile, dwEvtMask); late final _SetCommMask = _kernel32.lookupFunction< Int32 Function(IntPtr hFile, Uint32 dwEvtMask), int Function(int hFile, int dwEvtMask)>('SetCommMask'); /// Configures a communications device according to the specifications in a /// device-control block (a DCB structure). The function reinitializes all /// hardware and control settings, but it does not empty output or input /// queues. /// /// ```c /// BOOL SetCommState( /// HANDLE hFile, /// LPDCB lpDCB /// ); /// ``` /// {@category kernel32} int SetCommState(int hFile, Pointer<DCB> lpDCB) => _SetCommState(hFile, lpDCB); late final _SetCommState = _kernel32.lookupFunction< Int32 Function(IntPtr hFile, Pointer<DCB> lpDCB), int Function(int hFile, Pointer<DCB> lpDCB)>('SetCommState'); /// Sets the time-out parameters for all read and write operations on a /// specified communications device. /// /// ```c /// BOOL SetCommTimeouts( /// HANDLE hFile, /// LPCOMMTIMEOUTS lpCommTimeouts /// ); /// ``` /// {@category kernel32} int SetCommTimeouts(int hFile, Pointer<COMMTIMEOUTS> lpCommTimeouts) => _SetCommTimeouts(hFile, lpCommTimeouts); late final _SetCommTimeouts = _kernel32.lookupFunction< Int32 Function(IntPtr hFile, Pointer<COMMTIMEOUTS> lpCommTimeouts), int Function( int hFile, Pointer<COMMTIMEOUTS> lpCommTimeouts)>('SetCommTimeouts'); /// Adds or removes an application-defined HandlerRoutine function from the /// list of handler functions for the calling process. /// /// ```c /// BOOL WINAPI SetConsoleCtrlHandler( /// _In_opt_ PHANDLER_ROUTINE HandlerRoutine, /// _In_     BOOL             Add /// ); /// ``` /// {@category kernel32} int SetConsoleCtrlHandler( Pointer<NativeFunction<HandlerRoutine>> HandlerRoutine, int Add) => _SetConsoleCtrlHandler(HandlerRoutine, Add); late final _SetConsoleCtrlHandler = _kernel32.lookupFunction< Int32 Function( Pointer<NativeFunction<HandlerRoutine>> HandlerRoutine, Int32 Add), int Function(Pointer<NativeFunction<HandlerRoutine>> HandlerRoutine, int Add)>('SetConsoleCtrlHandler'); /// Sets the size and visibility of the cursor for the specified console /// screen buffer. /// /// ```c /// BOOL WINAPI SetConsoleCursorInfo( /// _In_ HANDLE hConsoleOutput, /// _In_ const CONSOLE_CURSOR_INFO *lpConsoleCursorInfo /// ); /// ``` /// {@category kernel32} int SetConsoleCursorInfo( int hConsoleOutput, Pointer<CONSOLE_CURSOR_INFO> lpConsoleCursorInfo) => _SetConsoleCursorInfo(hConsoleOutput, lpConsoleCursorInfo); late final _SetConsoleCursorInfo = _kernel32.lookupFunction< Int32 Function(IntPtr hConsoleOutput, Pointer<CONSOLE_CURSOR_INFO> lpConsoleCursorInfo), int Function(int hConsoleOutput, Pointer<CONSOLE_CURSOR_INFO> lpConsoleCursorInfo)>( 'SetConsoleCursorInfo'); /// Sets the cursor position in the specified console screen buffer. /// /// ```c /// BOOL WINAPI SetConsoleCursorPosition( /// _In_ HANDLE hConsoleOutput, /// _In_ COORD dwCursorPosition /// ); /// ``` /// {@category kernel32} int SetConsoleCursorPosition(int hConsoleOutput, COORD dwCursorPosition) => _SetConsoleCursorPosition(hConsoleOutput, dwCursorPosition); late final _SetConsoleCursorPosition = _kernel32.lookupFunction< Int32 Function(IntPtr hConsoleOutput, COORD dwCursorPosition), int Function(int hConsoleOutput, COORD dwCursorPosition)>('SetConsoleCursorPosition'); /// Sets the display mode of the specified console screen buffer. /// /// ```c /// BOOL WINAPI SetConsoleDisplayMode( /// _In_      HANDLE hConsoleOutput, /// _In_      DWORD  dwFlags, /// _Out_opt_ PCOORD lpNewScreenBufferDimensions /// ); /// ``` /// {@category kernel32} int SetConsoleDisplayMode(int hConsoleOutput, int dwFlags, Pointer<COORD> lpNewScreenBufferDimensions) => _SetConsoleDisplayMode( hConsoleOutput, dwFlags, lpNewScreenBufferDimensions); late final _SetConsoleDisplayMode = _kernel32.lookupFunction< Int32 Function(IntPtr hConsoleOutput, Uint32 dwFlags, Pointer<COORD> lpNewScreenBufferDimensions), int Function(int hConsoleOutput, int dwFlags, Pointer<COORD> lpNewScreenBufferDimensions)>('SetConsoleDisplayMode'); /// Sets the input mode of a console's input buffer or the output mode of a /// console screen buffer. /// /// ```c /// BOOL WINAPI SetConsoleMode( /// _In_ HANDLE hConsoleHandle, /// _In_ DWORD dwMode /// ); /// ``` /// {@category kernel32} int SetConsoleMode(int hConsoleHandle, int dwMode) => _SetConsoleMode(hConsoleHandle, dwMode); late final _SetConsoleMode = _kernel32.lookupFunction< Int32 Function(IntPtr hConsoleHandle, Uint32 dwMode), int Function(int hConsoleHandle, int dwMode)>('SetConsoleMode'); /// Sets the attributes of characters written to the console screen buffer /// by the WriteFile or WriteConsole function, or echoed by the ReadFile or /// ReadConsole function. This function affects text written after the /// function call. /// /// ```c /// BOOL WINAPI SetConsoleTextAttribute( /// _In_ HANDLE hConsoleOutput, /// _In_ WORD wAttributes /// ); /// ``` /// {@category kernel32} int SetConsoleTextAttribute(int hConsoleOutput, int wAttributes) => _SetConsoleTextAttribute(hConsoleOutput, wAttributes); late final _SetConsoleTextAttribute = _kernel32.lookupFunction< Int32 Function(IntPtr hConsoleOutput, Uint16 wAttributes), int Function( int hConsoleOutput, int wAttributes)>('SetConsoleTextAttribute'); /// Sets the current size and position of a console screen buffer's window. /// /// ```c /// BOOL WINAPI SetConsoleWindowInfo( /// _In_       HANDLE     hConsoleOutput, /// _In_       BOOL       bAbsolute, /// _In_ const SMALL_RECT *lpConsoleWindow /// ); /// ``` /// {@category kernel32} int SetConsoleWindowInfo(int hConsoleOutput, int bAbsolute, Pointer<SMALL_RECT> lpConsoleWindow) => _SetConsoleWindowInfo(hConsoleOutput, bAbsolute, lpConsoleWindow); late final _SetConsoleWindowInfo = _kernel32.lookupFunction< Int32 Function(IntPtr hConsoleOutput, Int32 bAbsolute, Pointer<SMALL_RECT> lpConsoleWindow), int Function(int hConsoleOutput, int bAbsolute, Pointer<SMALL_RECT> lpConsoleWindow)>('SetConsoleWindowInfo'); /// Changes the current directory for the current process. /// /// ```c /// BOOL SetCurrentDirectoryW( /// LPCTSTR lpPathName /// ); /// ``` /// {@category kernel32} int SetCurrentDirectory(Pointer<Utf16> lpPathName) => _SetCurrentDirectory(lpPathName); late final _SetCurrentDirectory = _kernel32.lookupFunction< Int32 Function(Pointer<Utf16> lpPathName), int Function(Pointer<Utf16> lpPathName)>('SetCurrentDirectoryW'); /// Sets the default configuration for a communications device. /// /// ```c /// BOOL SetDefaultCommConfigW( /// LPCWSTR lpszName, /// LPCOMMCONFIG lpCC, /// DWORD dwSize /// ); /// ``` /// {@category kernel32} int SetDefaultCommConfig( Pointer<Utf16> lpszName, Pointer<COMMCONFIG> lpCC, int dwSize) => _SetDefaultCommConfig(lpszName, lpCC, dwSize); late final _SetDefaultCommConfig = _kernel32.lookupFunction< Int32 Function( Pointer<Utf16> lpszName, Pointer<COMMCONFIG> lpCC, Uint32 dwSize), int Function(Pointer<Utf16> lpszName, Pointer<COMMCONFIG> lpCC, int dwSize)>('SetDefaultCommConfigW'); /// Moves the file pointer of the specified file. /// /// ```c /// DWORD SetFilePointer( /// HANDLE hFile, /// LONG lDistanceToMove, /// PLONG lpDistanceToMoveHigh, /// DWORD dwMoveMethod /// ); /// ``` /// {@category kernel32} int SetFilePointer(int hFile, int lDistanceToMove, Pointer<Int32> lpDistanceToMoveHigh, int dwMoveMethod) => _SetFilePointer(hFile, lDistanceToMove, lpDistanceToMoveHigh, dwMoveMethod); late final _SetFilePointer = _kernel32.lookupFunction< Uint32 Function(IntPtr hFile, Int32 lDistanceToMove, Pointer<Int32> lpDistanceToMoveHigh, Uint32 dwMoveMethod), int Function( int hFile, int lDistanceToMove, Pointer<Int32> lpDistanceToMoveHigh, int dwMoveMethod)>('SetFilePointer'); /// Moves the file pointer of the specified file. /// /// ```c /// BOOL SetFilePointerEx( /// HANDLE hFile, /// LARGE_INTEGER liDistanceToMove, /// PLARGE_INTEGER lpNewFilePointer, /// DWORD dwMoveMethod /// ); /// ``` /// {@category kernel32} int SetFilePointerEx(int hFile, int liDistanceToMove, Pointer<Int64> lpNewFilePointer, int dwMoveMethod) => _SetFilePointerEx(hFile, liDistanceToMove, lpNewFilePointer, dwMoveMethod); late final _SetFilePointerEx = _kernel32.lookupFunction< Int32 Function(IntPtr hFile, Int64 liDistanceToMove, Pointer<Int64> lpNewFilePointer, Uint32 dwMoveMethod), int Function(int hFile, int liDistanceToMove, Pointer<Int64> lpNewFilePointer, int dwMoveMethod)>('SetFilePointerEx'); /// Sets the short name for the specified file. The file must be on an NTFS /// file system volume. /// /// ```c /// BOOL SetFileShortNameW( /// HANDLE hFile, /// LPCWSTR lpShortName); /// ``` /// {@category kernel32} int SetFileShortName(int hFile, Pointer<Utf16> lpShortName) => _SetFileShortName(hFile, lpShortName); late final _SetFileShortName = _kernel32.lookupFunction< Int32 Function(IntPtr hFile, Pointer<Utf16> lpShortName), int Function(int hFile, Pointer<Utf16> lpShortName)>('SetFileShortNameW'); /// Sets the value of the specified firmware environment variable. /// /// ```c /// BOOL SetFirmwareEnvironmentVariableW( /// LPCWSTR lpName, /// LPCWSTR lpGuid, /// PVOID pValue, /// DWORD nSize /// ); /// ``` /// {@category kernel32} int SetFirmwareEnvironmentVariable(Pointer<Utf16> lpName, Pointer<Utf16> lpGuid, Pointer pValue, int nSize) => _SetFirmwareEnvironmentVariable(lpName, lpGuid, pValue, nSize); late final _SetFirmwareEnvironmentVariable = _kernel32.lookupFunction< Int32 Function(Pointer<Utf16> lpName, Pointer<Utf16> lpGuid, Pointer pValue, Uint32 nSize), int Function(Pointer<Utf16> lpName, Pointer<Utf16> lpGuid, Pointer pValue, int nSize)>('SetFirmwareEnvironmentVariableW'); /// Sets the value of the specified firmware environment variable and the /// attributes that indicate how this variable is stored and maintained. /// /// ```c /// BOOL SetFirmwareEnvironmentVariableExW( /// LPCWSTR lpName, /// LPCWSTR lpGuid, /// PVOID pValue, /// DWORD nSize, /// DWORD dwAttributes /// ); /// ``` /// {@category kernel32} int SetFirmwareEnvironmentVariableEx(Pointer<Utf16> lpName, Pointer<Utf16> lpGuid, Pointer pValue, int nSize, int dwAttributes) => _SetFirmwareEnvironmentVariableEx( lpName, lpGuid, pValue, nSize, dwAttributes); late final _SetFirmwareEnvironmentVariableEx = _kernel32.lookupFunction< Int32 Function(Pointer<Utf16> lpName, Pointer<Utf16> lpGuid, Pointer pValue, Uint32 nSize, Uint32 dwAttributes), int Function(Pointer<Utf16> lpName, Pointer<Utf16> lpGuid, Pointer pValue, int nSize, int dwAttributes)>('SetFirmwareEnvironmentVariableExW'); /// Sets certain properties of an object handle. /// /// ```c /// BOOL SetHandleInformation( /// HANDLE hObject, /// DWORD dwMask, /// DWORD dwFlags /// ); /// ``` /// {@category kernel32} int SetHandleInformation(int hObject, int dwMask, int dwFlags) => _SetHandleInformation(hObject, dwMask, dwFlags); late final _SetHandleInformation = _kernel32.lookupFunction< Int32 Function(IntPtr hObject, Uint32 dwMask, Uint32 dwFlags), int Function(int hObject, int dwMask, int dwFlags)>('SetHandleInformation'); /// Sets the read mode and the blocking mode of the specified named pipe. /// If the specified handle is to the client end of a named pipe and if the /// named pipe server process is on a remote computer, the function can /// also be used to control local buffering. /// /// ```c /// BOOL SetNamedPipeHandleState( /// HANDLE hNamedPipe, /// LPDWORD lpMode, /// LPDWORD lpMaxCollectionCount, /// LPDWORD lpCollectDataTimeout); /// ``` /// {@category kernel32} int SetNamedPipeHandleState( int hNamedPipe, Pointer<Uint32> lpMode, Pointer<Uint32> lpMaxCollectionCount, Pointer<Uint32> lpCollectDataTimeout) => _SetNamedPipeHandleState( hNamedPipe, lpMode, lpMaxCollectionCount, lpCollectDataTimeout); late final _SetNamedPipeHandleState = _kernel32.lookupFunction< Int32 Function( IntPtr hNamedPipe, Pointer<Uint32> lpMode, Pointer<Uint32> lpMaxCollectionCount, Pointer<Uint32> lpCollectDataTimeout), int Function( int hNamedPipe, Pointer<Uint32> lpMode, Pointer<Uint32> lpMaxCollectionCount, Pointer<Uint32> lpCollectDataTimeout)>('SetNamedPipeHandleState'); /// Sets a processor affinity mask for the threads of the specified /// process. /// /// ```c /// BOOL SetProcessAffinityMask( /// HANDLE hProcess, /// DWORD_PTR dwProcessAffinityMask /// ); /// ``` /// {@category kernel32} int SetProcessAffinityMask(int hProcess, int dwProcessAffinityMask) => _SetProcessAffinityMask(hProcess, dwProcessAffinityMask); late final _SetProcessAffinityMask = _kernel32.lookupFunction< Int32 Function(IntPtr hProcess, IntPtr dwProcessAffinityMask), int Function( int hProcess, int dwProcessAffinityMask)>('SetProcessAffinityMask'); /// Disables or enables the ability of the system to temporarily boost the /// priority of the threads of the specified process. /// /// ```c /// BOOL SetProcessPriorityBoost( /// HANDLE hProcess, /// BOOL bDisablePriorityBoost /// ); /// ``` /// {@category kernel32} int SetProcessPriorityBoost(int hProcess, int bDisablePriorityBoost) => _SetProcessPriorityBoost(hProcess, bDisablePriorityBoost); late final _SetProcessPriorityBoost = _kernel32.lookupFunction< Int32 Function(IntPtr hProcess, Int32 bDisablePriorityBoost), int Function( int hProcess, int bDisablePriorityBoost)>('SetProcessPriorityBoost'); /// Sets the minimum and maximum working set sizes for the specified /// process. /// /// ```c /// BOOL SetProcessWorkingSetSize( /// HANDLE hProcess, /// SIZE_T dwMinimumWorkingSetSize, /// SIZE_T dwMaximumWorkingSetSize /// ); /// ``` /// {@category kernel32} int SetProcessWorkingSetSize(int hProcess, int dwMinimumWorkingSetSize, int dwMaximumWorkingSetSize) => _SetProcessWorkingSetSize( hProcess, dwMinimumWorkingSetSize, dwMaximumWorkingSetSize); late final _SetProcessWorkingSetSize = _kernel32.lookupFunction< Int32 Function(IntPtr hProcess, IntPtr dwMinimumWorkingSetSize, IntPtr dwMaximumWorkingSetSize), int Function(int hProcess, int dwMinimumWorkingSetSize, int dwMaximumWorkingSetSize)>('SetProcessWorkingSetSize'); /// Sets the handle for the specified standard device (standard input, /// standard output, or standard error). /// /// ```c /// BOOL WINAPI SetStdHandle( /// _In_ DWORD  nStdHandle, /// _In_ HANDLE hHandle /// ); /// ``` /// {@category kernel32} int SetStdHandle(int nStdHandle, int hHandle) => _SetStdHandle(nStdHandle, hHandle); late final _SetStdHandle = _kernel32.lookupFunction< Int32 Function(Uint32 nStdHandle, IntPtr hHandle), int Function(int nStdHandle, int hHandle)>('SetStdHandle'); /// Sets a processor affinity mask for the specified thread. /// /// ```c /// DWORD_PTR SetThreadAffinityMask( /// HANDLE hThread, /// DWORD_PTR dwThreadAffinityMask /// ); /// ``` /// {@category kernel32} int SetThreadAffinityMask(int hThread, int dwThreadAffinityMask) => _SetThreadAffinityMask(hThread, dwThreadAffinityMask); late final _SetThreadAffinityMask = _kernel32.lookupFunction< IntPtr Function(IntPtr hThread, IntPtr dwThreadAffinityMask), int Function( int hThread, int dwThreadAffinityMask)>('SetThreadAffinityMask'); /// Enables an application to inform the system that it is in use, thereby /// preventing the system from entering sleep or turning off the display /// while the application is running. /// /// ```c /// EXECUTION_STATE SetThreadExecutionState( /// EXECUTION_STATE esFlags /// ); /// ``` /// {@category kernel32} int SetThreadExecutionState(int esFlags) => _SetThreadExecutionState(esFlags); late final _SetThreadExecutionState = _kernel32.lookupFunction< Uint32 Function(Uint32 esFlags), int Function(int esFlags)>('SetThreadExecutionState'); /// Sets the user interface language for the current thread. /// /// ```c /// LANGID SetThreadUILanguage( /// LANGID LangId /// ); /// ``` /// {@category kernel32} int SetThreadUILanguage(int LangId) => _SetThreadUILanguage(LangId); late final _SetThreadUILanguage = _kernel32.lookupFunction< Uint16 Function(Uint16 LangId), int Function(int LangId)>('SetThreadUILanguage'); /// Initializes the communications parameters for a specified /// communications device. /// /// ```c /// BOOL SetupComm( /// HANDLE hFile, /// DWORD dwInQueue, /// DWORD dwOutQueue /// ); /// ``` /// {@category kernel32} int SetupComm(int hFile, int dwInQueue, int dwOutQueue) => _SetupComm(hFile, dwInQueue, dwOutQueue); late final _SetupComm = _kernel32.lookupFunction< Int32 Function(IntPtr hFile, Uint32 dwInQueue, Uint32 dwOutQueue), int Function(int hFile, int dwInQueue, int dwOutQueue)>('SetupComm'); /// Sets the label of a file system volume. /// /// ```c /// BOOL SetVolumeLabelW( /// LPCWSTR lpRootPathName, /// LPCWSTR lpVolumeName); /// ``` /// {@category kernel32} int SetVolumeLabel( Pointer<Utf16> lpRootPathName, Pointer<Utf16> lpVolumeName) => _SetVolumeLabel(lpRootPathName, lpVolumeName); late final _SetVolumeLabel = _kernel32.lookupFunction< Int32 Function(Pointer<Utf16> lpRootPathName, Pointer<Utf16> lpVolumeName), int Function(Pointer<Utf16> lpRootPathName, Pointer<Utf16> lpVolumeName)>('SetVolumeLabelW'); /// Suspends the execution of the current thread until the time-out /// interval elapses. /// /// ```c /// void Sleep( /// DWORD dwMilliseconds /// ); /// ``` /// {@category kernel32} void Sleep(int dwMilliseconds) => _Sleep(dwMilliseconds); late final _Sleep = _kernel32.lookupFunction< Void Function(Uint32 dwMilliseconds), void Function(int dwMilliseconds)>('Sleep'); /// Suspends the current thread until the specified condition is met. /// Execution resumes when one of the following occurs: (i) an I/O /// completion callback function is called; (ii) an asynchronous procedure /// call (APC) is queued to the thread; (iii) the time-out interval /// elapses. /// /// ```c /// DWORD SleepEx( /// DWORD dwMilliseconds, /// BOOL bAlertable /// ); /// ``` /// {@category kernel32} int SleepEx(int dwMilliseconds, int bAlertable) => _SleepEx(dwMilliseconds, bAlertable); late final _SleepEx = _kernel32.lookupFunction< Uint32 Function(Uint32 dwMilliseconds, Int32 bAlertable), int Function(int dwMilliseconds, int bAlertable)>('SleepEx'); /// Terminates the specified process and all of its threads. /// /// ```c /// BOOL TerminateProcess( /// HANDLE hProcess, /// UINT uExitCode); /// ``` /// {@category kernel32} int TerminateProcess(int hProcess, int uExitCode) => _TerminateProcess(hProcess, uExitCode); late final _TerminateProcess = _kernel32.lookupFunction< Int32 Function(IntPtr hProcess, Uint32 uExitCode), int Function(int hProcess, int uExitCode)>('TerminateProcess'); /// Terminates a thread. /// /// ```c /// BOOL TerminateThread( /// HANDLE hThread, /// DWORD dwExitCode /// ); /// ``` /// {@category kernel32} int TerminateThread(int hThread, int dwExitCode) => _TerminateThread(hThread, dwExitCode); late final _TerminateThread = _kernel32.lookupFunction< Int32 Function(IntPtr hThread, Uint32 dwExitCode), int Function(int hThread, int dwExitCode)>('TerminateThread'); /// Combines the functions that write a message to and read a message from /// the specified named pipe into a single network operation. /// /// ```c /// BOOL TransactNamedPipe( /// HANDLE hNamedPipe, /// LPVOID lpInBuffer, /// DWORD nInBufferSize, /// LPVOID lpOutBuffer, /// DWORD nOutBufferSize, /// LPDWORD lpBytesRead, /// LPOVERLAPPED lpOverlapped); /// ``` /// {@category kernel32} int TransactNamedPipe( int hNamedPipe, Pointer lpInBuffer, int nInBufferSize, Pointer lpOutBuffer, int nOutBufferSize, Pointer<Uint32> lpBytesRead, Pointer<OVERLAPPED> lpOverlapped) => _TransactNamedPipe(hNamedPipe, lpInBuffer, nInBufferSize, lpOutBuffer, nOutBufferSize, lpBytesRead, lpOverlapped); late final _TransactNamedPipe = _kernel32.lookupFunction< Int32 Function( IntPtr hNamedPipe, Pointer lpInBuffer, Uint32 nInBufferSize, Pointer lpOutBuffer, Uint32 nOutBufferSize, Pointer<Uint32> lpBytesRead, Pointer<OVERLAPPED> lpOverlapped), int Function( int hNamedPipe, Pointer lpInBuffer, int nInBufferSize, Pointer lpOutBuffer, int nOutBufferSize, Pointer<Uint32> lpBytesRead, Pointer<OVERLAPPED> lpOverlapped)>('TransactNamedPipe'); /// Transmits a specified character ahead of any pending data in the output /// buffer of the specified communications device. /// /// ```c /// BOOL TransmitCommChar( /// HANDLE hFile, /// char cChar /// ); /// ``` /// {@category kernel32} int TransmitCommChar(int hFile, int cChar) => _TransmitCommChar(hFile, cChar); late final _TransmitCommChar = _kernel32.lookupFunction< Int32 Function(IntPtr hFile, Uint8 cChar), int Function(int hFile, int cChar)>('TransmitCommChar'); /// Updates the specified attribute in a list of attributes for process and /// thread creation. /// /// ```c /// BOOL UpdateProcThreadAttribute( /// LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList, /// DWORD dwFlags, /// DWORD_PTR Attribute, /// PVOID lpValue, /// SIZE_T cbSize, /// PVOID lpPreviousValue, /// PSIZE_T lpReturnSize /// ); /// ``` /// {@category kernel32} int UpdateProcThreadAttribute( Pointer lpAttributeList, int dwFlags, int Attribute, Pointer lpValue, int cbSize, Pointer lpPreviousValue, Pointer<IntPtr> lpReturnSize) => _UpdateProcThreadAttribute(lpAttributeList, dwFlags, Attribute, lpValue, cbSize, lpPreviousValue, lpReturnSize); late final _UpdateProcThreadAttribute = _kernel32.lookupFunction< Int32 Function( Pointer lpAttributeList, Uint32 dwFlags, IntPtr Attribute, Pointer lpValue, IntPtr cbSize, Pointer lpPreviousValue, Pointer<IntPtr> lpReturnSize), int Function( Pointer lpAttributeList, int dwFlags, int Attribute, Pointer lpValue, int cbSize, Pointer lpPreviousValue, Pointer<IntPtr> lpReturnSize)>('UpdateProcThreadAttribute'); /// Adds, deletes, or replaces a resource in a portable executable (PE) /// file. /// /// ```c /// BOOL UpdateResourceW( /// HANDLE hUpdate, /// LPCWSTR lpType, /// LPCWSTR lpName, /// WORD wLanguage, /// LPVOID lpData, /// DWORD cb /// ); /// ``` /// {@category kernel32} int UpdateResource(int hUpdate, Pointer<Utf16> lpType, Pointer<Utf16> lpName, int wLanguage, Pointer lpData, int cb) => _UpdateResource(hUpdate, lpType, lpName, wLanguage, lpData, cb); late final _UpdateResource = _kernel32.lookupFunction< Int32 Function(IntPtr hUpdate, Pointer<Utf16> lpType, Pointer<Utf16> lpName, Uint16 wLanguage, Pointer lpData, Uint32 cb), int Function(int hUpdate, Pointer<Utf16> lpType, Pointer<Utf16> lpName, int wLanguage, Pointer lpData, int cb)>('UpdateResourceW'); /// Retrieves a description string for the language associated with a /// specified binary Microsoft language identifier. /// /// ```c /// DWORD VerLanguageNameW( /// DWORD wLang, /// LPWSTR szLang, /// DWORD cchLang /// ); /// ``` /// {@category kernel32} int VerLanguageName(int wLang, Pointer<Utf16> szLang, int cchLang) => _VerLanguageName(wLang, szLang, cchLang); late final _VerLanguageName = _kernel32.lookupFunction< Uint32 Function(Uint32 wLang, Pointer<Utf16> szLang, Uint32 cchLang), int Function( int wLang, Pointer<Utf16> szLang, int cchLang)>('VerLanguageNameW'); /// Reserves, commits, or changes the state of a region of pages in the /// virtual address space of the calling process. Memory allocated by this /// function is automatically initialized to zero. /// /// ```c /// LPVOID VirtualAlloc( /// LPVOID lpAddress, /// SIZE_T dwSize, /// DWORD flAllocationType, /// DWORD flProtect /// ); /// ``` /// {@category kernel32} Pointer VirtualAlloc( Pointer lpAddress, int dwSize, int flAllocationType, int flProtect) => _VirtualAlloc(lpAddress, dwSize, flAllocationType, flProtect); late final _VirtualAlloc = _kernel32.lookupFunction< Pointer Function(Pointer lpAddress, IntPtr dwSize, Uint32 flAllocationType, Uint32 flProtect), Pointer Function(Pointer lpAddress, int dwSize, int flAllocationType, int flProtect)>('VirtualAlloc'); /// Reserves, commits, or changes the state of a region of memory within /// the virtual address space of a specified process. The function /// initializes the memory it allocates to zero. /// /// ```c /// LPVOID VirtualAllocEx( /// HANDLE hProcess, /// LPVOID lpAddress, /// SIZE_T dwSize, /// DWORD flAllocationType, /// DWORD flProtect /// ); /// ``` /// {@category kernel32} Pointer VirtualAllocEx(int hProcess, Pointer lpAddress, int dwSize, int flAllocationType, int flProtect) => _VirtualAllocEx(hProcess, lpAddress, dwSize, flAllocationType, flProtect); late final _VirtualAllocEx = _kernel32.lookupFunction< Pointer Function(IntPtr hProcess, Pointer lpAddress, IntPtr dwSize, Uint32 flAllocationType, Uint32 flProtect), Pointer Function(int hProcess, Pointer lpAddress, int dwSize, int flAllocationType, int flProtect)>('VirtualAllocEx'); /// Releases, decommits, or releases and decommits a region of pages within /// the virtual address space of the calling process. /// /// ```c /// BOOL VirtualFree( /// LPVOID lpAddress, /// SIZE_T dwSize, /// DWORD dwFreeType /// ); /// ``` /// {@category kernel32} int VirtualFree(Pointer lpAddress, int dwSize, int dwFreeType) => _VirtualFree(lpAddress, dwSize, dwFreeType); late final _VirtualFree = _kernel32.lookupFunction< Int32 Function(Pointer lpAddress, IntPtr dwSize, Uint32 dwFreeType), int Function(Pointer lpAddress, int dwSize, int dwFreeType)>('VirtualFree'); /// Releases, decommits, or releases and decommits a region of memory /// within the virtual address space of a specified process. /// /// ```c /// BOOL VirtualFreeEx( /// HANDLE hProcess, /// LPVOID lpAddress, /// SIZE_T dwSize, /// DWORD dwFreeType /// ); /// ``` /// {@category kernel32} int VirtualFreeEx( int hProcess, Pointer lpAddress, int dwSize, int dwFreeType) => _VirtualFreeEx(hProcess, lpAddress, dwSize, dwFreeType); late final _VirtualFreeEx = _kernel32.lookupFunction< Int32 Function( IntPtr hProcess, Pointer lpAddress, IntPtr dwSize, Uint32 dwFreeType), int Function(int hProcess, Pointer lpAddress, int dwSize, int dwFreeType)>('VirtualFreeEx'); /// Locks the specified region of the process's virtual address space into /// physical memory, ensuring that subsequent access to the region will not /// incur a page fault. /// /// ```c /// BOOL VirtualLock( /// LPVOID lpAddress, /// SIZE_T dwSize /// ); /// ``` /// {@category kernel32} int VirtualLock(Pointer lpAddress, int dwSize) => _VirtualLock(lpAddress, dwSize); late final _VirtualLock = _kernel32.lookupFunction< Int32 Function(Pointer lpAddress, IntPtr dwSize), int Function(Pointer lpAddress, int dwSize)>('VirtualLock'); /// Unlocks a specified range of pages in the virtual address space of a /// process, enabling the system to swap the pages out to the paging file /// if necessary. /// /// ```c /// BOOL VirtualUnlock( /// LPVOID lpAddress, /// SIZE_T dwSize /// ); /// ``` /// {@category kernel32} int VirtualUnlock(Pointer lpAddress, int dwSize) => _VirtualUnlock(lpAddress, dwSize); late final _VirtualUnlock = _kernel32.lookupFunction< Int32 Function(Pointer lpAddress, IntPtr dwSize), int Function(Pointer lpAddress, int dwSize)>('VirtualUnlock'); /// Waits for an event to occur for a specified communications device. The /// set of events that are monitored by this function is contained in the /// event mask associated with the device handle. /// /// ```c /// BOOL WaitCommEvent( /// HANDLE hFile, /// LPDWORD lpEvtMask, /// LPOVERLAPPED lpOverlapped /// ); /// ``` /// {@category kernel32} int WaitCommEvent(int hFile, Pointer<Uint32> lpEvtMask, Pointer<OVERLAPPED> lpOverlapped) => _WaitCommEvent(hFile, lpEvtMask, lpOverlapped); late final _WaitCommEvent = _kernel32.lookupFunction< Int32 Function(IntPtr hFile, Pointer<Uint32> lpEvtMask, Pointer<OVERLAPPED> lpOverlapped), int Function(int hFile, Pointer<Uint32> lpEvtMask, Pointer<OVERLAPPED> lpOverlapped)>('WaitCommEvent'); /// Waits until the specified object is in the signaled state or the /// time-out interval elapses. /// /// ```c /// DWORD WaitForSingleObject( /// HANDLE hHandle, /// DWORD dwMilliseconds /// ); /// ``` /// {@category kernel32} int WaitForSingleObject(int hHandle, int dwMilliseconds) => _WaitForSingleObject(hHandle, dwMilliseconds); late final _WaitForSingleObject = _kernel32.lookupFunction< Uint32 Function(IntPtr hHandle, Uint32 dwMilliseconds), int Function(int hHandle, int dwMilliseconds)>('WaitForSingleObject'); /// Maps a UTF-16 (wide character) string to a new character string. The /// new character string is not necessarily from a multibyte character set. /// /// ```c /// int WideCharToMultiByte( /// UINT CodePage, /// DWORD dwFlags, /// LPCWCH lpWideCharStr, /// int cchWideChar, /// LPSTR lpMultiByteStr, /// int cbMultiByte, /// LPCCH lpDefaultChar, /// LPBOOL lpUsedDefaultChar /// ); /// ``` /// {@category kernel32} int WideCharToMultiByte( int CodePage, int dwFlags, Pointer<Utf16> lpWideCharStr, int cchWideChar, Pointer<Utf8> lpMultiByteStr, int cbMultiByte, Pointer<Utf8> lpDefaultChar, Pointer<Int32> lpUsedDefaultChar) => _WideCharToMultiByte(CodePage, dwFlags, lpWideCharStr, cchWideChar, lpMultiByteStr, cbMultiByte, lpDefaultChar, lpUsedDefaultChar); late final _WideCharToMultiByte = _kernel32.lookupFunction< Int32 Function( Uint32 CodePage, Uint32 dwFlags, Pointer<Utf16> lpWideCharStr, Int32 cchWideChar, Pointer<Utf8> lpMultiByteStr, Int32 cbMultiByte, Pointer<Utf8> lpDefaultChar, Pointer<Int32> lpUsedDefaultChar), int Function( int CodePage, int dwFlags, Pointer<Utf16> lpWideCharStr, int cchWideChar, Pointer<Utf8> lpMultiByteStr, int cbMultiByte, Pointer<Utf8> lpDefaultChar, Pointer<Int32> lpUsedDefaultChar)>('WideCharToMultiByte'); /// Suspends the specified WOW64 thread. /// /// ```c /// DWORD Wow64SuspendThread( /// HANDLE hThread /// ); /// ``` /// {@category kernel32} int Wow64SuspendThread(int hThread) => _Wow64SuspendThread(hThread); late final _Wow64SuspendThread = _kernel32.lookupFunction< Uint32 Function(IntPtr hThread), int Function(int hThread)>('Wow64SuspendThread'); /// Writes a character string to a console screen buffer beginning at the /// current cursor location. /// /// ```c /// BOOL WINAPI WriteConsoleW( /// _In_             HANDLE  hConsoleOutput, /// _In_       const VOID    *lpBuffer, /// _In_             DWORD   nNumberOfCharsToWrite, /// _Out_opt_        LPDWORD lpNumberOfCharsWritten, /// _Reserved_       LPVOID  lpReserved /// ); /// ``` /// {@category kernel32} int WriteConsole( int hConsoleOutput, Pointer lpBuffer, int nNumberOfCharsToWrite, Pointer<Uint32> lpNumberOfCharsWritten, Pointer lpReserved) => _WriteConsole(hConsoleOutput, lpBuffer, nNumberOfCharsToWrite, lpNumberOfCharsWritten, lpReserved); late final _WriteConsole = _kernel32.lookupFunction< Int32 Function( IntPtr hConsoleOutput, Pointer lpBuffer, Uint32 nNumberOfCharsToWrite, Pointer<Uint32> lpNumberOfCharsWritten, Pointer lpReserved), int Function( int hConsoleOutput, Pointer lpBuffer, int nNumberOfCharsToWrite, Pointer<Uint32> lpNumberOfCharsWritten, Pointer lpReserved)>('WriteConsoleW'); /// Writes data to the specified file or input/output (I/O) device. /// /// ```c /// BOOL WriteFile( /// HANDLE hFile, /// LPCVOID lpBuffer, /// DWORD nNumberOfBytesToWrite, /// LPDWORD lpNumberOfBytesWritten, /// LPOVERLAPPED lpOverlapped /// ); /// ``` /// {@category kernel32} int WriteFile( int hFile, Pointer lpBuffer, int nNumberOfBytesToWrite, Pointer<Uint32> lpNumberOfBytesWritten, Pointer<OVERLAPPED> lpOverlapped) => _WriteFile(hFile, lpBuffer, nNumberOfBytesToWrite, lpNumberOfBytesWritten, lpOverlapped); late final _WriteFile = _kernel32.lookupFunction< Int32 Function( IntPtr hFile, Pointer lpBuffer, Uint32 nNumberOfBytesToWrite, Pointer<Uint32> lpNumberOfBytesWritten, Pointer<OVERLAPPED> lpOverlapped), int Function( int hFile, Pointer lpBuffer, int nNumberOfBytesToWrite, Pointer<Uint32> lpNumberOfBytesWritten, Pointer<OVERLAPPED> lpOverlapped)>('WriteFile'); /// Writes data to an area of memory in a specified process. The entire /// area to be written to must be accessible or the operation fails. /// /// ```c /// BOOL WriteProcessMemory( /// HANDLE hProcess, /// LPVOID lpBaseAddress, /// LPCVOID lpBuffer, /// SIZE_T nSize, /// SIZE_T *lpNumberOfBytesWritten /// ); /// ``` /// {@category kernel32} int WriteProcessMemory(int hProcess, Pointer lpBaseAddress, Pointer lpBuffer, int nSize, Pointer<IntPtr> lpNumberOfBytesWritten) => _WriteProcessMemory( hProcess, lpBaseAddress, lpBuffer, nSize, lpNumberOfBytesWritten); late final _WriteProcessMemory = _kernel32.lookupFunction< Int32 Function(IntPtr hProcess, Pointer lpBaseAddress, Pointer lpBuffer, IntPtr nSize, Pointer<IntPtr> lpNumberOfBytesWritten), int Function( int hProcess, Pointer lpBaseAddress, Pointer lpBuffer, int nSize, Pointer<IntPtr> lpNumberOfBytesWritten)>('WriteProcessMemory');
timsneath/win32
<|start_filename|>src/Skybrud.Social.Twitter/Properties/AssemblyInfoVersion.cs<|end_filename|> using System.Reflection; [assembly: AssemblyMetadata("StartDate", "2012-07-30")]
ohunecker/Skybrud.Social.Twitter
<|start_filename|>beater/decoder_test.go<|end_filename|> // +build !integration package beater import ( "testing" "time" "github.com/Shopify/sarama" "github.com/elastic/beats/libbeat/common" ) var ( testNowValue = time.Date(1981, time.May, 5, 10, 15, 35, 9583543, time.UTC) ) func newTestJSONDecoder() decoder { return &jsonDecoder{ timestampKey: "@timestamp", timestampLayout: common.TsLayout, timeNowFn: func() time.Time { return testNowValue }, } } func newTestPlainDecoder() decoder { return &plainDecoder{ timeNowFn: func() time.Time { return testNowValue }, } } func TestJSONDecoderWithoutTimestamp(t *testing.T) { d := newTestJSONDecoder() msg := &sarama.ConsumerMessage{ Value: []byte(`{ "field": "value" }`), } e := d.Decode(msg) if e == nil { t.Fatal("Event must be generated") } if e.Fields["field"] != "value" { t.Error("Expected field=value keypair, but not found on event") } if e.Timestamp != testNowValue { t.Errorf("Expected %v", testNowValue) t.Errorf(" found %v", e.Timestamp) } } func TestJSONDecoderWithMessageTimestamp(t *testing.T) { ts := time.Date(2019, time.April, 26, 17, 16, 10, 945958000, time.UTC) d := newTestJSONDecoder() msg := &sarama.ConsumerMessage{ Value: []byte(`{ "field": "value" }`), Timestamp: ts, } e := d.Decode(msg) if e == nil { t.Fatal("Event must be generated") } if e.Fields["field"] != "value" { t.Error("Expected field=value keypair, but not found on event") } if e.Timestamp != ts { t.Errorf("Expected %v", ts) t.Errorf(" found %v", e.Timestamp) } } func TestJSONDecoderWithValidJSONTimestamp(t *testing.T) { ts := time.Date(2019, time.April, 26, 17, 16, 10, 945000000, time.UTC) d := newTestJSONDecoder() msg := &sarama.ConsumerMessage{ Value: []byte(`{ "@timestamp": "2019-04-26T17:16:10.945Z", "field": "value" }`), } e := d.Decode(msg) if e == nil { t.Fatal("Event must be generated") } if e.Fields["field"] != "value" { t.Error("Expected field=value keypair, but not found on event") } if e.Timestamp != ts { t.Errorf("Expected %v", ts) t.Errorf(" found %v", e.Timestamp) } } func TestJSONDecoderWithInvalidJSONTimestamp(t *testing.T) { d := newTestJSONDecoder() msg := &sarama.ConsumerMessage{ Value: []byte(`{ "@timestamp": "2019-04-26T17:16:10.945759Z", "field": "value" }`), } e := d.Decode(msg) if e == nil { t.Fatal("Event must be generated") } if e.Fields["field"] != "value" { t.Error("Expected field=value keypair, but not found on event") } if e.Timestamp != testNowValue { t.Errorf("Expected %v", testNowValue) t.Errorf(" found %v", e.Timestamp) } } func TestPlainDecoderWithoutTimestamp(t *testing.T) { d := newTestPlainDecoder() msg := &sarama.ConsumerMessage{ Value: []byte(`mymessage`), } e := d.Decode(msg) if e == nil { t.Fatal("Event must be generated") } if e.Fields["message"] != "mymessage" { t.Error("Expected message=mymessage keypair, but not found on event") } if e.Timestamp != testNowValue { t.Errorf("Expected %v", testNowValue) t.Errorf(" found %v", e.Timestamp) } } func TestPlainDecoderWithMessageTimestamp(t *testing.T) { ts := time.Date(2019, time.April, 26, 17, 16, 10, 945958000, time.UTC) d := newTestPlainDecoder() msg := &sarama.ConsumerMessage{ Value: []byte(`mymessage`), Timestamp: ts, } e := d.Decode(msg) if e == nil { t.Fatal("Event must be generated") } if e.Fields["message"] != "mymessage" { t.Error("Expected message=mymessage keypair, but not found on event") } if e.Timestamp != ts { t.Errorf("Expected %v", ts) t.Errorf(" found %v", e.Timestamp) } } <|start_filename|>vendor/github.com/elastic/go-txfile/internal/cleanup/cleanup_test.go<|end_filename|> package cleanup_test import ( "testing" "github.com/stretchr/testify/assert" "github.com/elastic/go-txfile/internal/cleanup" ) func TestIfBool(t *testing.T) { testcases := []struct { title string fn func(*bool, func()) value bool cleanup bool }{ { "IfNot runs cleanup", cleanup.IfNot, false, true, }, { "IfNot does not run cleanup", cleanup.IfNot, true, false, }, { "If runs cleanup", cleanup.If, true, true, }, { "If does not run cleanup", cleanup.If, false, false, }, } for _, test := range testcases { test := test t.Run(test.title, func(t *testing.T) { executed := false func() { v := test.value defer test.fn(&v, func() { executed = true }) }() assert.Equal(t, test.cleanup, executed) }) } } <|start_filename|>vendor/github.com/elastic/go-txfile/internal/iter/iter_test.go<|end_filename|> package iter_test import ( "testing" "github.com/stretchr/testify/assert" "github.com/elastic/go-txfile/internal/iter" ) func TestIterForward(t *testing.T) { L := 10 var is []int for i, end, next := iter.Forward(L); i != end; i = next(i) { is = append(is, i) } for i, value := range is { assert.Equal(t, i, value) } } func TestIterReversed(t *testing.T) { L := 10 var is []int for i, end, next := iter.Reversed(L); i != end; i = next(i) { is = append(is, i) } for i, value := range is { assert.Equal(t, L-i-1, value) } } <|start_filename|>vendor/github.com/elastic/go-structform/sftest/sftest_test.go<|end_filename|> package sftest import ( "testing" structform "github.com/elastic/go-structform" ) func TestRecordingConsistent(t *testing.T) { TestEncodeParseConsistent(t, Samples, func() (structform.Visitor, func(structform.Visitor) error) { buf := &Recording{} return buf, buf.Replay }) } <|start_filename|>vendor/github.com/elastic/go-txfile/file_test.go<|end_filename|> package txfile import ( "fmt" "os" "testing" "github.com/elastic/go-txfile/internal/cleanup" ) type testFile struct { *File path string assert *assertions opts Options } func TestTxFile(t *testing.T) { assert := newAssertions(t) sampleContents := []string{ "Hello World", "The quick brown fox jumps over the lazy dog", "Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua.", } assert.Run("mmap sizing", func(assert *assertions) { const ( _ = 1 << (10 * iota) KB MB GB ) testcases := []struct { min, max, expected uint64 }{ {64, 0, 64 * KB}, {4 * KB, 0, 64 * KB}, {100 * KB, 0, 128 * KB}, {5 * MB, 0, 8 * MB}, {300 * MB, 0, 512 * MB}, {1200 * MB, 0, 2 * GB}, {2100 * MB, 0, 3 * GB}, } for _, test := range testcases { min, max, expected := test.min, test.max, test.expected title := fmt.Sprintf("min=%v,max=%v,expected=%v", min, max, expected) assert.Run(title, func(assert *assertions) { if expected > uint64(maxUint) { assert.Skip("unsatisfyable tests on 32bit system") } sz, err := computeMmapSize(uint(min), uint(max), 4096) assert.NoError(err) assert.Equal(int(expected), int(sz)) }) } }) assert.Run("open/close", func(assert *assertions) { path, teardown := setupPath(assert, "") defer teardown() f, err := Open(path, os.ModePerm, Options{ MaxSize: 10 * 1 << 20, // 10MB PageSize: 4096, }) assert.FatalOnError(err) assert.NoError(f.Close()) // check if we can re-open the file: f, err = Open(path, os.ModePerm, Options{}) assert.FatalOnError(err) assert.NoError(f.Close()) }) if assert.Failed() { // if we find a file can not even be created correctly, no need to run more // tests, that rely on file creation during test setup return } assert.Run("start and close readonly transaction without reads", func(assert *assertions) { f, teardown := setupTestFile(assert, Options{}) defer teardown() tx := f.BeginReadonly() assert.NotNil(tx) assert.True(tx.Readonly()) assert.False(tx.Writable()) assert.True(tx.Active()) assert.NoError(tx.Close()) assert.False(tx.Active()) }) assert.Run("start and close read-write transaction without reads/writes", func(assert *assertions) { f, teardown := setupTestFile(assert, Options{}) defer teardown() tx := f.Begin() assert.NotNil(tx) assert.False(tx.Readonly()) assert.True(tx.Writable()) assert.True(tx.Active()) assert.NoError(tx.Close()) assert.False(tx.Active()) }) assert.Run("readonly transaction can not allocate pages", func(assert *assertions) { f, teardown := setupTestFile(assert, Options{}) defer teardown() tx := f.BeginReadonly() defer tx.Close() page, err := tx.Alloc() assert.Nil(page) assert.Error(err) }) assert.Run("write transaction with modifications on new file with rollback", func(assert *assertions) { f, teardown := setupTestFile(assert, Options{}) defer teardown() tx := f.Begin() defer tx.Close() ids := pageSet{} page, err := tx.Alloc() assert.FatalOnError(err) if assert.NotNil(page) { ids.Add(page.ID()) assert.NotEqual(PageID(0), page.ID()) } pages, err := tx.AllocN(5) assert.FatalOnError(err) assert.Len(pages, 5) for _, page := range pages { if assert.NotNil(page) { assert.NotEqual(PageID(0), page.ID()) ids.Add(page.ID()) } } // check we didn't get the same ID twice: assert.Len(ids, 6) f.Rollback(tx) }) assert.Run("comitting write transaction without modifications", func(assert *assertions) { f, teardown := setupTestFile(assert, Options{}) defer teardown() tx := f.Begin() defer tx.Close() f.Commit(tx) }) assert.Run("committing write transaction on new file with page writes", func(assert *assertions) { contents := sampleContents f, teardown := setupTestFile(assert, Options{}) defer teardown() var ids idList func() { tx := f.Begin() defer tx.Close() ids = f.txAppend(tx, contents) tx.SetRoot(ids[0]) f.Commit(tx, "failed to commit the initial transaction") }() traceln("transaction page ids: ", ids) f.Reopen() tx := f.BeginReadonly() defer tx.Close() assert.Equal(ids[0], tx.Root()) assert.Equal(contents, f.readIDs(ids)) }) assert.Run("read contents after reopen and page contents has been overwritten", func(assert *assertions) { f, teardown := setupTestFile(assert, Options{}) defer teardown() writeSample := func(msg string, id PageID) (to PageID) { f.withTx(true, func(tx *Tx) { to = id if to == 0 { page, err := tx.Alloc() assert.FatalOnError(err) to = page.ID() } f.txWriteAt(tx, to, msg) f.Commit(tx) }) return } msgs := sampleContents[:2] id := writeSample(msgs[0], 0) writeSample(msgs[1], id) // reopen and check new contents is really available f.Reopen() assert.Equal(msgs[1], f.read(id)) }) assert.Run("check allocates smallest page possible", func(assert *assertions) { bools := [2]bool{false, true} for _, reopen := range bools { for _, withFragmentation := range bools { reopen := reopen withFragmentation := withFragmentation title := fmt.Sprintf("reopen=%v, fragmentation=%v", reopen, withFragmentation) assert.Run(title, func(assert *assertions) { f, teardown := setupTestFile(assert, Options{}) defer teardown() // allocate 2 pages var id PageID f.withTx(true, func(tx *Tx) { page, err := tx.Alloc() assert.FatalOnError(err) // allocate dummy page, so to ensure some fragmentation on free if withFragmentation { _, err = tx.Alloc() assert.FatalOnError(err) } id = page.ID() f.Commit(tx) }) if reopen { f.Reopen() } // free first allocated page f.withTx(true, func(tx *Tx) { page, err := tx.Page(id) assert.FatalOnError(err) assert.FatalOnError(page.Free()) f.Commit(tx) }) if reopen { f.Reopen() } // expect just freed page can be allocated again var newID PageID f.withTx(true, func(tx *Tx) { page, err := tx.Alloc() assert.FatalOnError(err) newID = page.ID() f.Commit(tx) }) // verify assert.Equal(id, newID) }) } } }) assert.Run("file open old transaction if verification fails", func(assert *assertions) { msgs := sampleContents[:2] f, teardown := setupTestFile(assert, Options{}) defer teardown() // start first transaction with first message writeSample := func(msg string, id PageID) PageID { tx := f.Begin() defer tx.Close() if id == 0 { page, err := tx.Alloc() assert.FatalOnError(err) id = page.ID() } f.txWriteAt(tx, id, msg) tx.SetRoot(id) f.Commit(tx) return id } id := writeSample(msgs[0], 0) writeSample(msgs[1], id) // overwrite contents // get active meta page id metaID := PageID(f.File.metaActive) metaOff := int64(metaID) * int64(f.allocator.pageSize) // close file and write invalid contents into last tx meta page f.Close() func() { tmp, err := os.OpenFile(f.path, os.O_RDWR, 0777) assert.FatalOnError(err) defer tmp.Close() _, err = tmp.WriteAt([]byte{1, 2, 3, 4, 5}, metaOff) assert.FatalOnError(err) }() // Open db file again and check recent transaction contents is still // available. f.Open() assert.Equal(msgs[0], f.read(id)) }) assert.Run("concurrent read transaction can not access not comitted contents", func(assert *assertions) { orig, modified := sampleContents[0], sampleContents[1:] f, teardown := setupTestFile(assert, Options{}) defer teardown() // commit original contents first id := f.append([]string{orig})[0] current := orig for _, newmsg := range modified { func() { // create write transaction, used to update the contents writer := f.Begin() defer writer.Close() f.txWriteAt(writer, id, newmsg) // check concurrent read will not have access to new contents reader := f.BeginReadonly() defer reader.Close() assert.Equal(current, f.txRead(reader, id)) f.Commit(reader) // close reader transaction // check new reader will read modified contents reader = f.BeginReadonly() defer reader.Close() assert.Equal(current, f.txRead(reader, id), "read unexpected message") f.Commit(reader) // finish transaction f.Commit(writer) current = newmsg }() } }) assert.Run("execute wal checkpoint", func(assert *assertions) { f, teardown := setupTestFile(assert, Options{}) defer teardown() // first tx with original contents ids := f.append(sampleContents) // overwrite original contents overwrites := append(sampleContents[1:], sampleContents[0]) f.writeAllAt(ids, overwrites) assert.Len(f.wal.mapping, 3, "expected wal mapping entries") // run wal checkpoint f.withTx(true, func(tx *Tx) { assert.FatalOnError(tx.CheckpointWAL()) f.Commit(tx) }) assert.Len(f.wal.mapping, 0, "mapping must be empty after checkpointing") }) assert.Run("force remap", func(assert *assertions) { N, i := 64/3+1, 0 contents := make([]string, 0, N) for len(contents) < N { contents = append(contents, sampleContents[i]) if i++; i == len(sampleContents) { i = 0 } } f, teardown := setupTestFile(assert, Options{}) defer teardown() ids := f.append(contents) // write enough contents to enforce an munmap/mmap assert.Equal(len(contents), len(ids)) // check we can still read all contents assert.Equal(contents, f.readIDs(ids)) }) assert.Run("inplace update", func(assert *assertions) { f, teardown := setupTestFile(assert, Options{}) defer teardown() id := f.append(sampleContents[:1])[0] func() { tx := f.Begin() defer tx.Close() page, err := tx.Page(id) assert.FatalOnError(err) assert.FatalOnError(page.Load()) buf, err := page.Bytes() assert.FatalOnError(err) // validate contents buffer assert.Len(buf, 4096) L := int(castU32(buf).Get()) assert.Equal(len(sampleContents[0]), L) assert.Equal(sampleContents[0], string(buf[4:4+L])) // overwrite buffer castU32(buf).Set(uint32(len(sampleContents[1]))) copy(buf[4:], sampleContents[1]) assert.FatalOnError(page.MarkDirty()) // commit f.Commit(tx) }() // read/validate new contents assert.Equal(sampleContents[1], f.read(id)) }) assert.Run("multiple inplace updates", func(assert *assertions) { f, teardown := setupTestFile(assert, Options{}) defer teardown() id := f.append(sampleContents[:1])[0] assert.Equal(sampleContents[0], f.read(id)) f.writeAt(id, sampleContents[1]) assert.Equal(sampleContents[1], f.read(id)) f.writeAt(id, sampleContents[2]) assert.Equal(sampleContents[2], f.read(id)) }) } func setupTestFile(assert *assertions, opts Options) (*testFile, func()) { // if opts.MaxSize == 0 { // opts.MaxSize = 10 * 1 << 20 // 10 MB // } if opts.PageSize == 0 { opts.PageSize = 4096 } ok := false path, teardown := setupPath(assert, "") defer cleanup.IfNot(&ok, teardown) tf := &testFile{path: path, assert: assert, opts: opts} tf.Open() ok = true return tf, func() { tf.Close() teardown() } } func (f *testFile) Reopen() { f.Close() f.Open() } func (f *testFile) Close() { if f.File != nil { f.assert.NoError(f.File.Close(), "close failed on reopen") f.File = nil } } func (f *testFile) Open() { tmp, err := Open(f.path, os.ModePerm, f.opts) f.assert.FatalOnError(err, "reopen failed") f.File = tmp f.checkConsistency() } func (f *testFile) Commit(tx *Tx, msgAndArgs ...interface{}) { needsCheck := tx.Writable() f.assert.FatalOnError(tx.Commit(), msgAndArgs...) if needsCheck { if !f.checkConsistency() { f.assert.Fatal("inconsistent file state") } } } func (f *testFile) Rollback(tx *Tx, msgAndArgs ...interface{}) { needsCheck := tx.Writable() f.assert.FatalOnError(tx.Rollback(), msgAndArgs...) if needsCheck { if !f.checkConsistency() { f.assert.Fatal("inconsistent file state") } } } // checkConsistency checks on disk file state is correct and consistent with in // memory state. func (f *testFile) checkConsistency() bool { if err := f.getMetaPage().Validate(); err != nil { f.assert.Error(err, "meta page validation") return false } meta := f.getMetaPage() ok := true // check wal: walMapping, walPages, err := readWAL(f.mmapedPage, meta.wal.Get()) f.assert.FatalOnError(err, "reading wal state") ok = ok && f.assert.Equal(walMapping, f.wal.mapping, "wal mapping") ok = ok && f.assert.Equal(walPages.Regions(), f.wal.metaPages, "wal meta pages") // validate meta end markers state maxSize := meta.maxSize.Get() / uint64(meta.pageSize.Get()) dataEnd := meta.dataEndMarker.Get() metaEnd := meta.metaEndMarker.Get() ok = ok && f.assert.True(maxSize == 0 || uint64(dataEnd) <= maxSize, "data end marker in bounds") // compare alloc markers and counters with allocator state ok = ok && f.assert.Equal(dataEnd, f.allocator.data.endMarker, "data end marker mismatch") ok = ok && f.assert.Equal(metaEnd, f.allocator.meta.endMarker, "meta end marker mismatch") ok = ok && f.assert.Equal(uint(meta.metaTotal.Get()), f.allocator.metaTotal, "meta area size mismatch") // compare free lists var metaList, dataList regionList flPages, err := readFreeList(f.mmapedPage, meta.freelist.Get(), func(isMeta bool, r region) { if isMeta { metaList.Add(r) } else { dataList.Add(r) } }) optimizeRegionList(&metaList) optimizeRegionList(&dataList) f.assert.FatalOnError(err, "reading freelist") ok = ok && f.assert.Equal(metaList, f.allocator.meta.freelist.regions, "meta area freelist mismatch") ok = ok && f.assert.Equal(dataList, f.allocator.data.freelist.regions, "data area freelist mismatch") ok = ok && f.assert.Equal(flPages.Regions(), f.allocator.freelistPages, "freelist meta pages") return ok } func (f *testFile) withTx(write bool, fn func(tx *Tx)) { tx := f.BeginWith(TxOptions{Readonly: !write}) defer func() { f.assert.FatalOnError(tx.Close()) }() fn(tx) } func (f *testFile) append(contents []string) (ids idList) { f.withTx(true, func(tx *Tx) { ids = f.txAppend(tx, contents) f.assert.FatalOnError(tx.Commit()) }) return } func (f *testFile) txAppend(tx *Tx, contents []string) idList { ids := make(idList, len(contents)) pages, err := tx.AllocN(len(contents)) f.assert.FatalOnError(err) for i, page := range pages { buf := make([]byte, tx.PageSize()) data := contents[i] castU32(buf).Set(uint32(len(data))) copy(buf[4:], data) f.assert.NoError(page.SetBytes(buf)) ids[i] = page.ID() } return ids } func (f *testFile) read(id PageID) (s string) { f.withTx(false, func(tx *Tx) { s = f.txRead(tx, id) }) return } func (f *testFile) txRead(tx *Tx, id PageID) string { page, err := tx.Page(id) f.assert.FatalOnError(err) buf, err := page.Bytes() f.assert.FatalOnError(err) count := castU32(buf).Get() return string(buf[4 : 4+count]) } func (f *testFile) readIDs(ids idList) (contents []string) { f.withTx(false, func(tx *Tx) { contents = f.txReadIDs(tx, ids) }) return } func (f *testFile) txReadIDs(tx *Tx, ids idList) []string { contents := make([]string, len(ids)) for i, id := range ids { contents[i] = f.txRead(tx, id) } return contents } func (f *testFile) writeAt(id PageID, msg string) { f.withTx(true, func(tx *Tx) { f.txWriteAt(tx, id, msg) f.assert.FatalOnError(tx.Commit()) }) } func (f *testFile) txWriteAt(tx *Tx, id PageID, msg string) { page, err := tx.Page(id) f.assert.FatalOnError(err) buf := make([]byte, tx.PageSize()) castU32(buf).Set(uint32(len(msg))) copy(buf[4:], msg) f.assert.NoError(page.SetBytes(buf)) } func (f *testFile) writeAllAt(ids idList, msgs []string) { f.withTx(true, func(tx *Tx) { f.txWriteAllAt(tx, ids, msgs) f.assert.FatalOnError(tx.Commit()) }) } func (f *testFile) txWriteAllAt(tx *Tx, ids idList, msgs []string) { for i, id := range ids { f.txWriteAt(tx, id, msgs[i]) } } <|start_filename|>vendor/github.com/elastic/go-sysinfo/providers/darwin/process_darwin_amd64.go<|end_filename|> // Licensed to Elasticsearch B.V. under one or more contributor // license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright // ownership. Elasticsearch B.V. licenses this file to you under // the Apache License, Version 2.0 (the "License"); you may // not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // +build darwin,amd64,cgo package darwin // #cgo LDFLAGS:-lproc // #include <sys/sysctl.h> // #include <libproc.h> import "C" import ( "bytes" "encoding/binary" "os" "time" "unsafe" "github.com/pkg/errors" "github.com/elastic/go-sysinfo/types" ) //go:generate sh -c "go tool cgo -godefs defs_darwin.go > ztypes_darwin_amd64.go" func (s darwinSystem) Processes() ([]types.Process, error) { return nil, nil } func (s darwinSystem) Process(pid int) (types.Process, error) { p := process{pid: pid} return &p, nil } func (s darwinSystem) Self() (types.Process, error) { return s.Process(os.Getpid()) } type process struct { pid int cwd string exe string args []string env map[string]string task procTaskAllInfo vnode procVnodePathInfo } func (p *process) Info() (types.ProcessInfo, error) { if err := getProcTaskAllInfo(p.pid, &p.task); err != nil { return types.ProcessInfo{}, err } if err := getProcVnodePathInfo(p.pid, &p.vnode); err != nil { return types.ProcessInfo{}, err } if err := kern_procargs(p.pid, p); err != nil { return types.ProcessInfo{}, err } return types.ProcessInfo{ Name: int8SliceToString(p.task.Pbsd.Pbi_name[:]), PID: p.pid, PPID: int(p.task.Pbsd.Pbi_ppid), CWD: int8SliceToString(p.vnode.Cdir.Path[:]), Exe: p.exe, Args: p.args, StartTime: time.Unix(int64(p.task.Pbsd.Pbi_start_tvsec), int64(p.task.Pbsd.Pbi_start_tvusec)*int64(time.Microsecond)), }, nil } func (p *process) Environment() (map[string]string, error) { return p.env, nil } func (p *process) CPUTime() types.CPUTimes { return types.CPUTimes{ User: time.Duration(p.task.Ptinfo.Total_user), System: time.Duration(p.task.Ptinfo.Total_system), } } func (p *process) Memory() types.MemoryInfo { return types.MemoryInfo{ Virtual: p.task.Ptinfo.Virtual_size, Resident: p.task.Ptinfo.Resident_size, Metrics: map[string]uint64{ "page_ins": uint64(p.task.Ptinfo.Pageins), "page_faults": uint64(p.task.Ptinfo.Faults), }, } } func getProcTaskAllInfo(pid int, info *procTaskAllInfo) error { size := C.int(unsafe.Sizeof(*info)) ptr := unsafe.Pointer(info) n := C.proc_pidinfo(C.int(pid), C.PROC_PIDTASKALLINFO, 0, ptr, size) if n != size { return errors.New("failed to read process info with proc_pidinfo") } return nil } func getProcVnodePathInfo(pid int, info *procVnodePathInfo) error { size := C.int(unsafe.Sizeof(*info)) ptr := unsafe.Pointer(info) n := C.proc_pidinfo(C.int(pid), C.PROC_PIDVNODEPATHINFO, 0, ptr, size) if n != size { return errors.New("failed to read vnode info with proc_pidinfo") } return nil } var nullTerminator = []byte{0} // wrapper around sysctl KERN_PROCARGS2 // callbacks params are optional, // up to the caller as to which pieces of data they want func kern_procargs(pid int, p *process) error { mib := []C.int{C.CTL_KERN, C.KERN_PROCARGS2, C.int(pid)} var data []byte if err := sysctl(mib, &data); err != nil { return nil } buf := bytes.NewBuffer(data) // argc var argc int32 if err := binary.Read(buf, binary.LittleEndian, &argc); err != nil { return err } // exe lines := bytes.Split(buf.Bytes(), nullTerminator) p.exe = string(lines[0]) lines = lines[1:] // skip nulls for len(lines) > 0 { if len(lines[0]) == 0 { lines = lines[1:] continue } break } // args for i := 0; i < int(argc); i++ { p.args = append(p.args, string(lines[0])) lines = lines[1:] } // env vars env := make(map[string]string, len(lines)) for _, l := range lines { if len(l) == 0 { break } parts := bytes.SplitN(l, []byte{'='}, 2) if len(parts) != 2 { return errors.New("failed to parse") } key := string(parts[0]) value := string(parts[1]) env[key] = value } p.env = env return nil } func int8SliceToString(s []int8) string { buf := bytes.NewBuffer(make([]byte, len(s))) buf.Reset() for _, b := range s { if b == 0 { break } buf.WriteByte(byte(b)) } return buf.String() } <|start_filename|>vendor/github.com/elastic/go-txfile/pageset_test.go<|end_filename|> package txfile import "testing" func TestPageSet(t *testing.T) { assert := newAssertions(t) assert.Run("query nil pageSet", func(assert *assertions) { var s pageSet assert.False(s.Has(1)) assert.True(s.Empty()) assert.Equal(0, s.Count()) assert.Nil(s.IDs()) assert.Nil(s.Regions()) }) assert.Run("query empty pageSet", func(assert *assertions) { s := pageSet{} assert.False(s.Has(1)) assert.True(s.Empty()) assert.Equal(0, s.Count()) assert.Nil(s.IDs()) assert.Nil(s.Regions()) }) assert.Run("pageSet modifications", func(assert *assertions) { var s pageSet s.Add(1) s.Add(2) s.Add(10) assert.False(s.Empty()) assert.Equal(3, s.Count()) assert.True(s.Has(1)) assert.True(s.Has(2)) assert.False(s.Has(3)) assert.False(s.Has(4)) assert.True(s.Has(10)) ids := s.IDs() ids.Sort() // ids might be unsorted assert.Equal(idList{1, 2, 10}, ids) regions := s.Regions() assert.Equal(regionList{{1, 2}, {10, 1}}, regions) }) } <|start_filename|>vendor/github.com/elastic/go-txfile/util_test.go<|end_filename|> package txfile import ( "testing" ) // TestHelpers tests some critical internal utilities for being somewhat correct func TestInternalHelpers(t *testing.T) { assert := newAssertions(t) assert.Run("is power of 2", func(assert *assertions) { for bit := uint64(0); bit < 64; bit++ { value := uint64(1) << bit assert.True(isPowerOf2(value)) // Check masking with another arbitrary bit pattern, the result does not // satisfy the isPowerOf2 predicate. assert.QuickCheck(func(mask uint64) bool { // mask must modify the value, otherwise continue testing return (mask == 0 || mask == value) || !isPowerOf2(mask|value) }) bit++ } }) assert.Run("check nextPowerOf2 consistent", makeQuickCheck(func(u uint64) bool { if u >= (1 << 63) { // if highest bit is already set, we can not compute next power of 2 // (which would be 0) return true } v := nextPowerOf2(u) if !isPowerOf2(v) { return false // v must be power of 2 } else if !(v/2 <= u && u < v) { return false // u must be in range [v/2, v[ } else if isPowerOf2(u) && v != 2*u { return false // if u is power of 2, v = 2*u } return true })) } func TestPagingWriter(t *testing.T) { assert := newAssertions(t) recordPages := func(ids *idList, pages *[][]byte) func(PageID, []byte) error { return func(id PageID, buf []byte) error { *ids, *pages = append(*ids, id), append(*pages, buf) return nil } } assert.Run("requires pages", func(assert *assertions) { w := newPagingWriter(make(idList, 0), 4096, 0, nil) assert.Nil(w) }) assert.Run("errors on write, if not enough pages", func(assert *assertions) { w := newPagingWriter(idList{2}, 64, 0, nil) var err error for i := 0; i < 60; i++ { var tmp [10]byte if err = w.Write(tmp[:]); err != nil { break } } assert.Error(err) }) assert.Run("write 1 page", func(assert *assertions) { var ids idList var pages [][]byte w := newPagingWriter(idList{2}, 64, 0, recordPages(&ids, &pages)) tmp := "abcdefghijklmn" assert.NoError(w.Write([]byte(tmp))) assert.NoError(w.Flush()) assert.Equal(idList{2}, ids) if assert.Len(pages, 1) { assert.Len(pages[0], 64) hdr, payload := castListPage(pages[0]) assert.Equal(PageID(0), hdr.next.Get()) assert.Equal(1, int(hdr.count.Get())) assert.Equal(tmp, string(payload[:len(tmp)])) } }) assert.Run("pages with multiple ids will be linked", func(assert *assertions) { var ids idList var pages [][]byte w := newPagingWriter(idList{0, 1, 2}, 64, 0, recordPages(&ids, &pages)) assert.NoError(w.Flush()) // flush all pages assert.Equal(idList{0, 1, 2}, ids) if assert.Len(pages, 3) { expectedNext := idList{1, 2, 0} for i, page := range pages { assert.Len(page, 64) hdr, _ := castListPage(page) assert.Equal(expectedNext[i], hdr.next.Get()) assert.Equal(0, int(hdr.count.Get())) } } }) assert.Run("write 3 pages", func(assert *assertions) { var ids idList var pages [][]byte w := newPagingWriter(idList{0, 1, 2}, 64, 0, recordPages(&ids, &pages)) for i := 0; i < 11; i++ { var buf [10]byte if !assert.NoError(w.Write(buf[:])) { assert.FailNow("all writes must be ok") } } assert.NoError(w.Flush()) if assert.Len(pages, 3) { expectedCounts := []uint32{5, 5, 1} for i, page := range pages { hdr, _ := castListPage(page) assert.Equal(expectedCounts[i], hdr.count.Get()) } } }) } <|start_filename|>vendor/github.com/elastic/go-txfile/layout_test.go<|end_filename|> package txfile import ( "testing" "unsafe" ) func TestMetaPage(t *testing.T) { assert := newAssertions(t) assert.Run("fail to validate", func(assert *assertions) { // var buf metaBuf buf := make([]byte, unsafe.Sizeof(metaPage{})) hdr := castMetaPage(buf[:]) assert.Error(hdr.Validate()) hdr.magic.Set(magic) assert.Error(hdr.Validate()) hdr.version.Set(version) assert.Error(hdr.Validate()) }) assert.Run("fail if checksum not set", func(assert *assertions) { // var buf metabuf buf := make([]byte, unsafe.Sizeof(metaPage{})) hdr := castMetaPage(buf[:]) hdr.Init(0, 4096, 1<<30) assert.Error(hdr.Validate()) }) assert.Run("with checksum", func(assert *assertions) { // var buf metabuf buf := make([]byte, unsafe.Sizeof(metaPage{})) hdr := castMetaPage(buf[:]) hdr.Init(0, 4096, 1<<30) hdr.Finalize() assert.NoError(hdr.Validate()) }) assert.Run("check if contents changed", func(assert *assertions) { // var buf metabuf buf := make([]byte, unsafe.Sizeof(metaPage{})) hdr := castMetaPage(buf[:]) hdr.Init(0, 4096, 1<<30) hdr.Finalize() buf[4] = 0xff assert.Error(hdr.Validate()) }) } <|start_filename|>beater/kafkabeat.go<|end_filename|> package beater import ( "fmt" "time" "github.com/arkady-emelyanov/kafkabeat/config" "github.com/Shopify/sarama" cluster "github.com/bsm/sarama-cluster" "github.com/elastic/beats/libbeat/beat" "github.com/elastic/beats/libbeat/common" "github.com/elastic/beats/libbeat/logp" ) type Kafkabeat struct { done chan struct{} logger *logp.Logger mode beat.PublishMode bConfig config.Config // beats config kConfig *cluster.Config // kafka config pipeline beat.Client consumer *cluster.Consumer codec decoder } // Creates beater func New(b *beat.Beat, cfg *common.Config) (beat.Beater, error) { bConfig := config.DefaultConfig if err := cfg.Unpack(&bConfig); err != nil { return nil, fmt.Errorf("error reading config file: %v", err) } kConfig := cluster.NewConfig() kConfig.ClientID = bConfig.ClientID kConfig.ChannelBufferSize = bConfig.ChannelBufferSize kConfig.Consumer.MaxWaitTime = time.Millisecond * 500 kConfig.Consumer.Return.Errors = true // initial offset handling switch bConfig.Offset { case "newest": kConfig.Consumer.Offsets.Initial = sarama.OffsetNewest case "oldest": kConfig.Consumer.Offsets.Initial = sarama.OffsetOldest default: return nil, fmt.Errorf("error in configuration, unknown offset: '%s'", bConfig.Offset) } // codec to use var codec decoder switch bConfig.Codec { case "json": codec = newJSONDecoder(bConfig.TimestampKey, bConfig.TimestampLayout) case "plain": codec = newPlainDecoder() default: return nil, fmt.Errorf("error in configuration, unknown codec: '%s'", bConfig.Codec) } // publish_mode var mode beat.PublishMode switch bConfig.PublishMode { case "default": mode = beat.DefaultGuarantees case "send": mode = beat.GuaranteedSend case "drop_if_full": mode = beat.DropIfFull default: return nil, fmt.Errorf("error in configuration, unknown publish_mode: '%s'", bConfig.PublishMode) } if bConfig.ChannelWorkers < 1 { bConfig.ChannelWorkers = 1 } // return beat bt := &Kafkabeat{ done: make(chan struct{}), logger: logp.NewLogger("kafkabeat"), mode: mode, bConfig: bConfig, kConfig: kConfig, codec: codec, } return bt, nil } func (bt *Kafkabeat) Run(b *beat.Beat) error { var err error // start kafka consumer bt.consumer, err = cluster.NewConsumer( bt.bConfig.Brokers, bt.bConfig.Group, bt.bConfig.Topics, bt.kConfig, ) if err != nil { return err } // start beats pipeline bt.pipeline, err = b.Publisher.ConnectWith( beat.ClientConfig{ PublishMode: bt.mode, }, ) if err != nil { return err } // run workers bt.logger.Info("spawning channel workers: ", bt.bConfig.ChannelWorkers) for i := 0; i < bt.bConfig.ChannelWorkers; i++ { go bt.workerFn() } // run loop bt.logger.Info("kafkabeat is running! Hit CTRL-C to stop it.") for { select { case <-bt.done: bt.consumer.Close() return nil case err := <-bt.consumer.Errors(): bt.logger.Error(err.Error()) } } } func (bt *Kafkabeat) workerFn() { for { msg := <-bt.consumer.Messages() if msg == nil { break } if event := bt.codec.Decode(msg); event != nil { bt.pipeline.Publish(*event) } bt.consumer.MarkOffset(msg, "") } } func (bt *Kafkabeat) Stop() { bt.pipeline.Close() close(bt.done) } <|start_filename|>config/config.go<|end_filename|> // Config is put into a different package to prevent cyclic imports in case // it is needed in several locations package config import ( "runtime" "github.com/elastic/beats/libbeat/common" ) type Config struct { Brokers []string `config:"brokers"` Topics []string `config:"topics"` ClientID string `config:"client_id"` Group string `config:"group"` Offset string `config:"offset"` Codec string `config:"codec"` PublishMode string `config:"publish_mode"` ChannelBufferSize int `config:"channel_buffer_size"` ChannelWorkers int `config:"channel_workers"` TimestampKey string `config:"timestamp_key"` TimestampLayout string `config:"timestamp_layout"` } var DefaultConfig = Config{ Brokers: []string{"localhost:9092"}, Topics: []string{"watch"}, ClientID: "beat", Group: "kafkabeat", Offset: "newest", Codec: "json", PublishMode: "default", ChannelBufferSize: 256, ChannelWorkers: runtime.NumCPU(), TimestampKey: "@timestamp", TimestampLayout: common.TsLayout, } <|start_filename|>vendor/github.com/elastic/go-structform/gotype/gotypes_test.go<|end_filename|> package gotype import ( "runtime" "testing" structform "github.com/elastic/go-structform" "github.com/elastic/go-structform/sftest" ) type mapstr map[string]interface{} // special visitor enforcing a gc before and after every // every operators, checking the folder/unfolder to not hold on // invalid pointers. type gcCheckVisitor struct { u structform.ExtVisitor } func TestFoldUnfoldToIfcConsistent(t *testing.T) { sftest.TestEncodeParseConsistent(t, sftest.Samples, func() (structform.Visitor, func(structform.Visitor) error) { var v interface{} unfolder, err := NewUnfolder(&v) if err != nil { panic(err) } return newGCCheckVisitor(unfolder), func(to structform.Visitor) error { return Fold(v, to) } }) } func newGCCheckVisitor(v structform.Visitor) *gcCheckVisitor { return &gcCheckVisitor{structform.EnsureExtVisitor(v)} } func (g *gcCheckVisitor) OnObjectStart(len int, baseType structform.BaseType) error { runtime.GC() err := g.u.OnObjectStart(len, baseType) runtime.GC() return err } func (g *gcCheckVisitor) OnObjectFinished() error { runtime.GC() err := g.u.OnObjectFinished() runtime.GC() return err } func (g *gcCheckVisitor) OnKey(s string) error { runtime.GC() err := g.u.OnKey(s) runtime.GC() return err } func (g *gcCheckVisitor) OnArrayStart(len int, baseType structform.BaseType) error { runtime.GC() err := g.u.OnArrayStart(len, baseType) runtime.GC() return err } func (g *gcCheckVisitor) OnArrayFinished() error { runtime.GC() err := g.u.OnArrayFinished() runtime.GC() return err } func (g *gcCheckVisitor) OnNil() error { runtime.GC() err := g.u.OnNil() runtime.GC() return err } func (g *gcCheckVisitor) OnBool(b bool) error { runtime.GC() err := g.u.OnBool(b) runtime.GC() return err } func (g *gcCheckVisitor) OnString(s string) error { runtime.GC() err := g.u.OnString(s) runtime.GC() return err } func (g *gcCheckVisitor) OnInt8(i int8) error { runtime.GC() err := g.u.OnInt8(i) runtime.GC() return err } func (g *gcCheckVisitor) OnInt16(i int16) error { runtime.GC() err := g.u.OnInt16(i) runtime.GC() return err } func (g *gcCheckVisitor) OnInt32(i int32) error { runtime.GC() err := g.u.OnInt32(i) runtime.GC() return err } func (g *gcCheckVisitor) OnInt64(i int64) error { runtime.GC() err := g.u.OnInt64(i) runtime.GC() return err } func (g *gcCheckVisitor) OnInt(i int) error { runtime.GC() err := g.u.OnInt(i) runtime.GC() return err } func (g *gcCheckVisitor) OnByte(b byte) error { runtime.GC() err := g.u.OnByte(b) runtime.GC() return err } func (g *gcCheckVisitor) OnUint8(u uint8) error { runtime.GC() err := g.u.OnUint8(u) runtime.GC() return err } func (g *gcCheckVisitor) OnUint16(u uint16) error { runtime.GC() err := g.u.OnUint16(u) runtime.GC() return err } func (g *gcCheckVisitor) OnUint32(u uint32) error { runtime.GC() err := g.u.OnUint32(u) runtime.GC() return err } func (g *gcCheckVisitor) OnUint64(u uint64) error { runtime.GC() err := g.u.OnUint64(u) runtime.GC() return err } func (g *gcCheckVisitor) OnUint(u uint) error { runtime.GC() err := g.u.OnUint(u) runtime.GC() return err } func (g *gcCheckVisitor) OnFloat32(f float32) error { runtime.GC() err := g.u.OnFloat32(f) runtime.GC() return err } func (g *gcCheckVisitor) OnFloat64(f float64) error { runtime.GC() err := g.u.OnFloat64(f) runtime.GC() return err } func (g *gcCheckVisitor) OnBoolArray(a []bool) error { runtime.GC() err := g.u.OnBoolArray(a) runtime.GC() return err } func (g *gcCheckVisitor) OnStringArray(a []string) error { runtime.GC() err := g.u.OnStringArray(a) runtime.GC() return err } func (g *gcCheckVisitor) OnInt8Array(a []int8) error { runtime.GC() err := g.u.OnInt8Array(a) runtime.GC() return err } func (g *gcCheckVisitor) OnInt16Array(a []int16) error { runtime.GC() err := g.u.OnInt16Array(a) runtime.GC() return err } func (g *gcCheckVisitor) OnInt32Array(a []int32) error { runtime.GC() err := g.u.OnInt32Array(a) runtime.GC() return err } func (g *gcCheckVisitor) OnInt64Array(a []int64) error { runtime.GC() err := g.u.OnInt64Array(a) runtime.GC() return err } func (g *gcCheckVisitor) OnIntArray(a []int) error { runtime.GC() err := g.u.OnIntArray(a) runtime.GC() return err } func (g *gcCheckVisitor) OnBytes(a []byte) error { runtime.GC() err := g.u.OnBytes(a) runtime.GC() return err } func (g *gcCheckVisitor) OnUint8Array(a []uint8) error { runtime.GC() err := g.u.OnUint8Array(a) runtime.GC() return err } func (g *gcCheckVisitor) OnUint16Array(a []uint16) error { runtime.GC() err := g.u.OnUint16Array(a) runtime.GC() return err } func (g *gcCheckVisitor) OnUint32Array(a []uint32) error { runtime.GC() err := g.u.OnUint32Array(a) runtime.GC() return err } func (g *gcCheckVisitor) OnUint64Array(a []uint64) error { runtime.GC() err := g.u.OnUint64Array(a) runtime.GC() return err } func (g *gcCheckVisitor) OnUintArray(a []uint) error { runtime.GC() err := g.u.OnUintArray(a) runtime.GC() return err } func (g *gcCheckVisitor) OnFloat32Array(a []float32) error { runtime.GC() err := g.u.OnFloat32Array(a) runtime.GC() return err } func (g *gcCheckVisitor) OnFloat64Array(a []float64) error { runtime.GC() err := g.u.OnFloat64Array(a) runtime.GC() return err } func (g *gcCheckVisitor) OnBoolObject(o map[string]bool) error { runtime.GC() err := g.u.OnBoolObject(o) runtime.GC() return err } func (g *gcCheckVisitor) OnStringObject(o map[string]string) error { runtime.GC() err := g.u.OnStringObject(o) runtime.GC() return err } func (g *gcCheckVisitor) OnInt8Object(o map[string]int8) error { runtime.GC() err := g.u.OnInt8Object(o) runtime.GC() return err } func (g *gcCheckVisitor) OnInt16Object(o map[string]int16) error { runtime.GC() err := g.u.OnInt16Object(o) runtime.GC() return err } func (g *gcCheckVisitor) OnInt32Object(o map[string]int32) error { runtime.GC() err := g.u.OnInt32Object(o) runtime.GC() return err } func (g *gcCheckVisitor) OnInt64Object(o map[string]int64) error { runtime.GC() err := g.u.OnInt64Object(o) runtime.GC() return err } func (g *gcCheckVisitor) OnIntObject(o map[string]int) error { runtime.GC() err := g.u.OnIntObject(o) runtime.GC() return err } func (g *gcCheckVisitor) OnUint8Object(o map[string]uint8) error { runtime.GC() err := g.u.OnUint8Object(o) runtime.GC() return err } func (g *gcCheckVisitor) OnUint16Object(o map[string]uint16) error { runtime.GC() err := g.u.OnUint16Object(o) runtime.GC() return err } func (g *gcCheckVisitor) OnUint32Object(o map[string]uint32) error { runtime.GC() err := g.u.OnUint32Object(o) runtime.GC() return err } func (g *gcCheckVisitor) OnUint64Object(o map[string]uint64) error { runtime.GC() err := g.u.OnUint64Object(o) runtime.GC() return err } func (g *gcCheckVisitor) OnUintObject(o map[string]uint) error { runtime.GC() err := g.u.OnUintObject(o) runtime.GC() return err } func (g *gcCheckVisitor) OnFloat32Object(o map[string]float32) error { runtime.GC() err := g.u.OnFloat32Object(o) runtime.GC() return err } func (g *gcCheckVisitor) OnFloat64Object(o map[string]float64) error { runtime.GC() err := g.u.OnFloat64Object(o) runtime.GC() return err } func (g *gcCheckVisitor) OnStringRef(s []byte) error { runtime.GC() err := g.u.OnStringRef(s) runtime.GC() return err } func (g *gcCheckVisitor) OnKeyRef(s []byte) error { runtime.GC() err := g.u.OnKeyRef(s) runtime.GC() return err } <|start_filename|>vendor/github.com/elastic/go-txfile/freelist_test.go<|end_filename|> package txfile import ( "math" "testing" ) func TestFreelist(t *testing.T) { assert := newAssertions(t) mkList := func(r regionList) freelist { var l freelist l.AddRegions(r) return l } assert.Run("empty list", func(assert *assertions) { var l freelist assert.Nil(l.AllocAllRegions()) assert.Equal(region{}, l.AllocContinuousRegion(allocFromBeginning, 1)) var regions regionList l.AllocAllRegionsWith(regions.Add) assert.Nil(regions) regions = nil l.AllocRegionsWith(allocFromBeginning, 1, regions.Add) assert.Nil(regions) }) assert.Run("adding regions consistent", func(assert *assertions) { var l freelist l.AddRegions(regionList{{1, 5}, {10, 4}}) assert.Equal(9, int(l.Avail())) assert.Equal(regionList{{1, 5}, {10, 4}}, l.regions) }) assert.Run("alloc all regions", func(assert *assertions) { regions := regionList{{1, 5}, {10, 4}} l := mkList(regions) assert.Equal(regions, l.AllocAllRegions()) assert.Equal(0, int(l.Avail())) }) assert.Run("alloc continuous", func(assert *assertions) { testcases := []struct { title string init regionList n uint order *allocOrder allocates region after regionList }{ { title: "no continuous region available", init: regionList{{1, 3}, {8, 6}}, n: 8, order: allocFromBeginning, after: regionList{{1, 3}, {8, 6}}, }, { title: "allocate matching region from beginning", init: regionList{{1, 3}, {100, 10}, {200, 10}, {300, 3}}, n: 10, order: allocFromBeginning, allocates: region{100, 10}, after: regionList{{1, 3}, {200, 10}, {300, 3}}, }, { title: "allocate matching region from end", init: regionList{{1, 3}, {100, 10}, {200, 10}, {300, 3}}, n: 10, order: allocFromEnd, allocates: region{200, 10}, after: regionList{{1, 3}, {100, 10}, {300, 3}}, }, { title: "allocate best fit", init: regionList{{1, 3}, {100, 10}, {150, 5}, {200, 10}, {300, 3}}, n: 5, order: allocFromBeginning, allocates: region{150, 5}, after: regionList{{1, 3}, {100, 10}, {200, 10}, {300, 3}}, }, { title: "split first smallest fitting region", init: regionList{{1, 3}, {100, 10}, {150, 15}, {200, 10}, {300, 3}}, n: 8, order: allocFromBeginning, allocates: region{100, 8}, after: regionList{{1, 3}, {108, 2}, {150, 15}, {200, 10}, {300, 3}}, }, { title: "split last smallest fitting region", init: regionList{{1, 3}, {100, 10}, {150, 15}, {200, 10}, {300, 3}}, n: 8, order: allocFromEnd, allocates: region{202, 8}, after: regionList{{1, 3}, {100, 10}, {150, 15}, {200, 2}, {300, 3}}, }, } for _, test := range testcases { test := test assert.Run(test.title, func(assert *assertions) { l := mkList(test.init) assert.Equal(test.allocates, l.AllocContinuousRegion(test.order, test.n), "unexpected allocation result") assert.Equal(int(test.after.CountPages()), int(l.Avail()), "invalid number of available pages") assert.Equal(test.after, l.regions, "freelist regions not matching expected freelist") }) } }) assert.Run("alloc non-continuous", func(assert *assertions) { testcases := []struct { title string init regionList n uint order *allocOrder allocates regionList after regionList }{ { title: "not enough space available", init: regionList{{1, 3}, {8, 6}}, n: 20, order: allocFromBeginning, after: regionList{{1, 3}, {8, 6}}, }, { title: "allocate sub-region from first region only", init: regionList{{1, 10}, {20, 5}}, n: 5, order: allocFromBeginning, allocates: regionList{{1, 5}}, after: regionList{{6, 5}, {20, 5}}, }, { title: "allocate complete first region found", init: regionList{{1, 10}, {20, 5}}, n: 10, order: allocFromBeginning, allocates: regionList{{1, 10}}, after: regionList{{20, 5}}, }, { title: "allocate sub-region from last region only", init: regionList{{1, 10}, {20, 10}}, n: 5, order: allocFromEnd, allocates: regionList{{25, 5}}, after: regionList{{1, 10}, {20, 5}}, }, { title: "allocate complete last region found", init: regionList{{1, 10}, {20, 10}}, n: 10, order: allocFromEnd, allocates: regionList{{20, 10}}, after: regionList{{1, 10}}, }, { title: "allocate multiple regions from the beginning", init: regionList{{1, 3}, {5, 3}, {10, 5}, {20, 10}}, n: 9, order: allocFromBeginning, allocates: regionList{{1, 3}, {5, 3}, {10, 3}}, after: regionList{{13, 2}, {20, 10}}, }, { title: "allocate multiple regions from the end", init: regionList{{1, 3}, {5, 4}, {10, 3}, {20, 3}}, n: 9, order: allocFromEnd, allocates: regionList{{6, 3}, {10, 3}, {20, 3}}, after: regionList{{1, 3}, {5, 1}}, }, } for _, test := range testcases { test := test assert.Run(test.title, func(assert *assertions) { var allocated regionList l := mkList(test.init) l.AllocRegionsWith(test.order, test.n, allocated.Add) assert.Equal(test.allocates, allocated, "unexpected allocation result") assert.Equal(int(test.after.CountPages()), int(l.Avail()), "invalid number of available pages") assert.Equal(test.after, l.regions, "freelist regions not matching expected freelist") }) } }) assert.Run("remove region", func(assert *assertions) { testcases := []struct { title string init regionList remove region after regionList }{ { title: "remove region from end, not in freelist", init: regionList{{1, 10}, {30, 10}, {50, 10}}, remove: region{60, 10}, after: regionList{{1, 10}, {30, 10}, {50, 10}}, }, { title: "remove region from beginning, not in freelist", init: regionList{{10, 10}, {30, 10}, {50, 10}}, remove: region{1, 5}, after: regionList{{10, 10}, {30, 10}, {50, 10}}, }, { title: "remove region from middle, not in freelist", init: regionList{{10, 10}, {30, 10}, {50, 10}}, remove: region{20, 5}, after: regionList{{10, 10}, {30, 10}, {50, 10}}, }, { title: "remove first region from list", init: regionList{{1, 10}, {20, 10}, {50, 10}}, remove: region{1, 10}, after: regionList{{20, 10}, {50, 10}}, }, { title: "remove from beginning of first region", init: regionList{{1, 10}, {20, 10}, {50, 10}}, remove: region{1, 5}, after: regionList{{6, 5}, {20, 10}, {50, 10}}, }, { title: "remove from end of first region", init: regionList{{1, 10}, {20, 10}, {50, 10}}, remove: region{6, 5}, after: regionList{{1, 5}, {20, 10}, {50, 10}}, }, { title: "remove from middle of first region", init: regionList{{1, 10}, {20, 10}, {50, 10}}, remove: region{6, 2}, after: regionList{{1, 5}, {8, 3}, {20, 10}, {50, 10}}, }, { title: "remove multiple regions", init: regionList{{1, 10}, {20, 10}, {50, 10}}, remove: region{1, 30}, after: regionList{{50, 10}}, }, { title: "remove sub-regions from multiple regions", init: regionList{{1, 10}, {12, 5}, {20, 10}, {50, 10}}, remove: region{6, 20}, after: regionList{{1, 5}, {26, 4}, {50, 10}}, }, } for _, test := range testcases { test := test assert.Run(test.title, func(assert *assertions) { l := mkList(test.init) l.RemoveRegion(test.remove) assert.Equal(int(test.after.CountPages()), int(l.Avail()), "invalid number of available pages") assert.Equal(test.after, l.regions, "freelist regions not matching expected freelist") }) } }) assert.Run("add-merge new region", func(assert *assertions) { testcases := []struct { title string init, add, after regionList requires64 bool // mark a test requires 64bit arch to run }{ { title: "into empty list", add: regionList{{10, 2}}, after: regionList{{10, 2}}, }, { title: "add to end of list", init: regionList{{1, 10}}, add: regionList{{100, 10}}, after: regionList{{1, 10}, {100, 10}}, }, { title: "merge to end of list", init: regionList{{1, 10}}, add: regionList{{11, 10}}, after: regionList{{1, 20}}, }, { title: "add to beginning of list", init: regionList{{100, 10}}, add: regionList{{10, 10}}, after: regionList{{10, 10}, {100, 10}}, }, { title: "merge with beginning of list", init: regionList{{11, 10}}, add: regionList{{1, 10}}, after: regionList{{1, 20}}, }, { title: "add in middle of list", init: regionList{{1, 10}, {1000, 10}}, add: regionList{{100, 10}}, after: regionList{{1, 10}, {100, 10}, {1000, 10}}, }, { title: "merge end of entry in middle of list", init: regionList{{1, 10}, {100, 10}, {1001, 10}}, add: regionList{{110, 10}}, after: regionList{{1, 10}, {100, 20}, {1001, 10}}, }, { title: "merge start of entry in middle of list", init: regionList{{1, 10}, {110, 10}, {1001, 10}}, add: regionList{{100, 10}}, after: regionList{{1, 10}, {100, 20}, {1001, 10}}, }, { title: "combine regions on merge", init: regionList{{1, 10}, {100, 10}, {120, 10}, {1001, 10}}, add: regionList{{110, 10}}, after: regionList{{1, 10}, {100, 30}, {1001, 10}}, }, { title: "do not combine unmergable regions into full region", requires64: true, init: regionList{{0, 1<<32 - 10}, {1<<32 - 5, 100}}, add: regionList{{1<<32 - 10, 5}}, after: regionList{{0, 1<<32 - 5}, {1<<32 - 5, 100}}, }, } for _, test := range testcases { test := test assert.Run(test.title, func(assert *assertions) { if test.requires64 { if uint64(maxUint) != math.MaxUint64 { assert.Skip("test requires 64bit system to run") } } var l freelist l.AddRegions(test.init) for _, reg := range test.add { l.AddRegion(reg) } assert.Equal(int(test.after.CountPages()), int(l.Avail()), "invalid number of available pages") assert.Equal(test.after, l.regions, "freelist regions not matching expected freelist") }) } }) assert.Run("serialization", func(assert *assertions) { testcases := []struct { title string pages uint meta regionList data regionList }{ { title: "empty lists", pages: 0, }, { title: "empty lists with allocated write pages", pages: 3, }, { title: "small data list only, with estimate", data: regionList{{100, 10}, {200, 20}, {1000, 500}}, }, { title: "small meta list only, with estimate", meta: regionList{{100, 10}, {200, 20}, {1000, 500}}, }, { title: "small data and meta list, with estimate", meta: regionList{{100, 10}, {200, 20}, {1000, 500}, {1500, 300}}, data: regionList{{500, 10}, {2000, 20}, {10000, 500}, {40000, 200}}, }, { title: "data and meta list, with extra pages", pages: 10, meta: regionList{{100, 10}, {200, 20}, {1000, 500}, {1500, 300}}, data: regionList{{500, 10}, {2000, 20}, {10000, 500}, {40000, 200}}, }, } pageSize := uint(64) for _, test := range testcases { N := test.pages meta, data := test.meta, test.data assert.Run(test.title, func(assert *assertions) { store := newTestPageStore(pageSize) if N == 0 { predictor := prepareFreelistEncPagePrediction(listPageHeaderSize, pageSize) predictor.AddRegions(meta) predictor.AddRegions(data) N = predictor.Estimate() } root := PageID(2) writePages := regionList{{root, uint32(N)}} if N == 0 { // no pages -> set root to nil root = 0 writePages = nil } tracef("freelist test write regions: %v\n", writePages) err := writeFreeLists(writePages, pageSize, meta, data, store.Set) assert.FatalOnError(err, "write freelist failed") var actualMeta, actualData regionList ids, err := readFreeList(store.Get, root, func(isMeta bool, reg region) { if isMeta { actualMeta.Add(reg) } else { actualData.Add(reg) } }) assert.FatalOnError(err, "reading the list failed") assert.Equal(writePages, ids.Regions()) assert.Equal(meta, actualMeta, "meta regions mismatch") assert.Equal(data, actualData, "data regions mismatch") }) } }) } <|start_filename|>vendor/github.com/elastic/go-txfile/pq/pq_test.go<|end_filename|> package pq import ( "math/rand" "testing" "github.com/elastic/go-txfile" "github.com/elastic/go-txfile/internal/mint" ) func TestQueueOperations(testing *testing.T) { t := mint.NewWith(testing, func(sub *mint.T) func() { pushTracer(mint.NewTestLogTracer(sub, logTracer)) return popTracer }) defaultConfig := config{ File: txfile.Options{ MaxSize: 128 * 1024, // default file size of 128 pages PageSize: 1024, }, Queue: Settings{ WriteBuffer: 4096, // buffer up to 4 pages }, } t.Run("no events in new file", withQueue(defaultConfig, func(t *mint.T, qu *testQueue) { t.Equal(0, qu.len()) })) t.Run("no events without flush", withQueue(defaultConfig, func(t *mint.T, qu *testQueue) { qu.append("event1", "event2") t.Equal(0, qu.len()) })) t.Run("events available with flush", withQueue(defaultConfig, func(t *mint.T, qu *testQueue) { qu.append("event1", "event2") qu.flush() t.Equal(2, qu.len()) })) t.Run("no more events after ack", withQueue(defaultConfig, func(t *mint.T, qu *testQueue) { qu.append("event1", "event2") qu.flush() qu.ack(2) t.Equal(0, qu.len()) })) t.Run("read written events", withQueue(defaultConfig, func(t *mint.T, qu *testQueue) { events := []string{"event1", "event2"} qu.append(events...) qu.flush() actual := qu.read(-1) qu.ack(uint(len(actual))) t.Equal(events, actual) t.Equal(0, qu.len()) })) t.Run("scenarios", func(t *mint.T) { sz := int(defaultConfig.File.PageSize) qcCconfig := defaultConfig qcCconfig.File.MaxSize = 5000 * 500 testcases := []struct { ops scenario config config }{ // randomized event lengths { ops: scenario{ opRandEvents(1, sz, sz/2+sz, 0), }, config: defaultConfig, }, { ops: scenario{ opRandEvents(1, sz*2, sz*2+sz/2, 0), }, config: defaultConfig, }, { ops: scenario{ opRandEvents(1, sz*2, sz*3+sz/2, 0), }, config: defaultConfig, }, { ops: scenario{ opRandEvents(2, sz, sz/2+sz, 0), }, config: defaultConfig, }, { ops: scenario{ opRandEvents(2, sz*2, sz*2+sz/2, 0), }, config: defaultConfig, }, { ops: scenario{ opRandEvents(2, sz*2, sz*3+sz/2, 0), }, config: defaultConfig, }, { ops: scenario{ opRandEvents(10, sz/10, sz/2, 0), }, config: defaultConfig, }, { ops: scenario{ opRandEvents(10, sz/10, sz*3, 0), }, config: defaultConfig, }, // randomized events with known seed (former failing tests) { ops: scenario{ opRandEvents(2, sz*2, sz*2+sz/2, 1519332567522137000), }, config: defaultConfig, }, { ops: scenario{ opRandEvents(2, sz*2, sz*3+sz/2, 1519334194758363000), }, config: defaultConfig, }, { ops: scenario{ opRandEvents(2, 2048, 2560, 1519336773321643000), }, config: defaultConfig, }, { ops: scenario{ opRandEvents(10, sz/10, sz*3, 1519336716061915000), }, config: defaultConfig, }, { ops: scenario{ opRandEvents(10, 102, 2073, 1519398160271388000), }, config: defaultConfig, }, // failed scenarios from quick check { ops: scenario{ opWriteEvents(4344, 1293, 1164, 2154, 3104, 4282, 2241, 3944), }, config: qcCconfig, }, { ops: scenario{ opWriteEvents(2982, 2877, 317, 2319, 2098, 2752, 1445, 3653), }, config: qcCconfig, }, { ops: scenario{ opWriteEvents(983, 242, 166, 789, 2780, 2806, 3616, 4777, 3569), }, config: qcCconfig, }, { ops: scenario{ opWriteEvents(4770, 4139), opWriteEvents(3966, 231), }, config: qcCconfig, }, { ops: scenario{ opWriteEvents(4770, 4139), opReopen, opWriteEvents(3966, 231), opReopen, }, config: qcCconfig, }, { ops: scenario{ opWriteEvents(400, 400, 400, 400, 400), opReadAll, opACKEvents(1), opACKAll, }, config: qcCconfig, }, { ops: scenario{ opWriteEvents(400, 400, 400, 400, 400), opReadAll, opACKEvents(1), opACKEvents(2), opACKEvents(1), opACKEvents(1), }, config: qcCconfig, }, { ops: scenario{ opWriteEvents(1500, 1500, 1500, 1500, 1500), opReadAll, opACKEvents(1), opACKAll, }, config: qcCconfig, }, { ops: scenario{ opWriteEvents(1500, 1500, 1500, 1500, 1500), opReadAll, opACKEvents(1), opACKEvents(2), opACKEvents(1), opACKEvents(1), }, config: qcCconfig, }, // special failing scenarios: { ops: scenario{ // initial writes so to reconstruct queue state opWriteEvents(concatSizes( nOfSize(24, 49), nOfSize(256-24, 50), nOfSize(374-256, 51))...), opReadAll, opACKEvents(374), opWriteEvents(nOfSize(296, 51)...), opReadAll, opACKEvents(296), opWriteEvents(nOfSize(296, 51)...), opReadAll, opACKEvents(296), opWriteEvents(nOfSize(296, 51)...), opReadAll, opACKEvents(296), opWriteEvents(nOfSize(296, 51)...), opReadAll, opACKEvents(296), opWriteEvents(nOfSize(296, 51)...), opReadAll, opACKEvents(296), // write that requires additinal allocations opWriteEvents(nOfSize(296, 51)...), opReadAll, // <- missing ACK and next push // write with delayed ACK opWriteEvents(nOfSize(295, 51)...), opACKEvents(296), // <- delayed ACK opReadAll, // <- fails opACKEvents(295), }, config: config{ File: txfile.Options{ MaxSize: 128 * 1024, PageSize: 4 * 1024, Prealloc: true, }, Queue: Settings{ WriteBuffer: 16 * 1024, }, }, }, } for _, test := range testcases { test := test t.Run(test.ops.String(), func(t *mint.T) { runScenario(t, test.config, append(test.ops, opFinalize)) }) } }) t.Run("quick check queue operations", func(t *mint.T) { config := defaultConfig config.File.MaxSize = 5000 * 500 // rounds := between(1, 3) rounds := between(1, 4) // rounds := exactly(1) events := between(5, 50) // events := between(1, 10) sizes := between(10, 5000) t.Run("randomized writes", func(t *mint.T) { t.QuickCheck(qcGenRandWrites(rounds, events, sizes), func(ops scenario) bool { return runScenario(t, config, append(ops, opReadAll)) }) }) t.Run("randomized acks", func(t *mint.T) { t.QuickCheck(qcGenRandACKs(events, sizes), func(ops scenario) bool { return runScenario(t, config, append(ops, opReadAll)) }) }) }) } func withQueue(cfg config, fn func(*mint.T, *testQueue)) func(*mint.T) { return func(t *mint.T) { qu, teardown := setupQueue(t, cfg) defer teardown() fn(t, qu) } } func qcGenRandWrites(rounds, N, Len testRange) func(*rand.Rand) scenario { return func(rng *rand.Rand) scenario { var ops scenario W := rounds.rand(rng) reopen := W > 1 for i := 0; i < W; i++ { ops = append(ops, qcGenWriteOp(N.rand(rng), Len)(rng)) if reopen { ops = append(ops, opReopen) } } return ops } } func qcGenWriteOp(N int, Len testRange) func(*rand.Rand) testOp { return func(rng *rand.Rand) testOp { events := make([]int, N) for i := range events { events[i] = Len.rand(rng) } return opWriteEvents(events...) } } func qcGenRandACKs(events, Len testRange) func(*rand.Rand) scenario { return func(rng *rand.Rand) scenario { var ops scenario N := events.rand(rng) ops = append(ops, qcGenWriteOp(N, Len)(rng), opReadAll) for N > 0 { acks := testRange{min: 1, max: N}.rand(rng) ops = append(ops, opACKEvents(acks)) N -= acks } return ops } } func genQcRandString(L testRange) func(*rand.Rand) string { return func(rng *rand.Rand) string { codePoints := make([]byte, L.rand(rng)) for i := range codePoints { codePoints[i] = byte(rng.Intn(int('Z'-'0'))) + '0' } return string(codePoints) } } <|start_filename|>vendor/github.com/elastic/go-txfile/lock_test.go<|end_filename|> package txfile import ( "testing" ) func TestLock(t *testing.T) { assert := newAssertions(t) makeTestLock := func() (*sharedLock, *reservedLock, *pendingLock, *exclusiveLock) { l := newLock() return l.Shared(), l.Reserved(), l.Pending(), l.Exclusive() } assert.Run("multiple shared locks", func(assert *assertions) { shared, _, _, _ := makeTestLock() shared.Lock() defer shared.Unlock() assert.True(shared.check(), "shared lock can not be acquired") }) assert.Run("shared lock if reserved lock is set", func(assert *assertions) { shared, reserved, _, _ := makeTestLock() reserved.Lock() defer reserved.Unlock() assert.True(shared.check(), "shared lock can not be acquired") }) assert.Run("can not acquire shared lock if pending lock is set", func(assert *assertions) { shared, reserved, pending, _ := makeTestLock() reserved.Lock() defer reserved.Unlock() pending.Lock() defer pending.Unlock() assert.False(shared.check(), "shared lock can be acquired") }) assert.Run("shared lock can be acquired once pending is unlocked", func(assert *assertions) { shared, reserved, pending, _ := makeTestLock() reserved.Lock() defer reserved.Unlock() pending.Lock() pending.Unlock() assert.True(shared.check(), "shared lock can not be acquired") }) assert.Run("reserved lock correctly unlocks", func(assert *assertions) { _, reserved, _, _ := makeTestLock() reserved.Lock() reserved.Unlock() // this will block/fail the tests if it blocks reserved.Lock() reserved.Unlock() }) assert.Run("exclusive lock can only be acquired if no shared lock is taken", func(assert *assertions) { _, reserved, pending, exclusive := makeTestLock() reserved.Lock() defer reserved.Unlock() pending.Lock() defer pending.Unlock() assert.True(exclusive.check(), "exclusive lock can not be acquired") }) assert.Run("exclusive lock can not be acquired if shared lock exists", func(assert *assertions) { shared, reserved, pending, exclusive := makeTestLock() reserved.Lock() defer reserved.Unlock() shared.Lock() defer shared.Unlock() pending.Lock() defer pending.Unlock() assert.False(exclusive.check(), "exclusive lock can be acquired") }) assert.Run("exclusive lock can be acquired after shared is unlocked", func(assert *assertions) { shared, reserved, pending, exclusive := makeTestLock() reserved.Lock() defer reserved.Unlock() shared.Lock() pending.Lock() defer pending.Unlock() shared.Unlock() assert.True(exclusive.check(), "exclusive lock can not be acquired") }) } <|start_filename|>vendor/github.com/elastic/go-txfile/write_test.go<|end_filename|> package txfile import ( "errors" "testing" "time" ) type ( testIOOperations []testIOOp testIOOp interface { Type() opType At() int64 Contents() []byte } testWriteAtOP struct { at int64 contents []byte } testSyncOP struct{} opType uint8 ) type testWriterTarget struct { writeAt func([]byte, int64) (int, error) sync func() error } const ( opUndefined opType = iota opWriteAt opSync ) func TestFileWriter(t *testing.T) { assert := newAssertions(t) assert.Run("start stop", func(assert *assertions) { var ops testIOOperations _, teardown := newTestWriter(recordWriteOps(&ops), 64) time.Sleep(10 * time.Millisecond) if assert.NoError(teardown()) { assert.Len(ops, 0) } }) assert.Run("write and sync", func(assert *assertions) { var ops testIOOperations w, teardown := newTestWriter(recordWriteOps(&ops), 10) defer mustSucceed(assert, teardown) var tmp [10]byte sync := newTxWriteSync() w.Schedule(sync, 0, tmp[:]) w.Sync(sync) if !assert.NoError(waitFn(1*time.Second, sync.Wait)) { assert.FailNow("invalid writer state") } if assert.Len(ops, 2) { assert.Equal(opWriteAt, ops[0].Type()) assert.Equal(int64(0), ops[0].At()) assert.Len(ops[0].Contents(), 10) assert.Equal(syncOp, ops[1]) } }) assert.Run("write after sync", func(assert *assertions) { var ops testIOOperations b, target := blockingTarget(recordWriteOps(&ops)) b.Block() w, teardown := newTestWriter(target, 10) defer mustSucceed(assert, teardown) var tmp [10]byte sync := newTxWriteSync() w.Schedule(sync, 0, tmp[:]) w.Schedule(sync, 1, tmp[:]) w.Sync(sync) w.Schedule(sync, 2, tmp[:]) w.Schedule(sync, 3, tmp[:]) w.Schedule(sync, 4, tmp[:]) w.Sync(sync) w.Schedule(sync, 5, tmp[:]) w.Sync(sync) // unblock writer, so scheduled write commands will be executed b.Unblock() if !assert.NoError(waitFn(1*time.Second, sync.Wait)) { assert.FailNow("invalid writer state") } expectedOps := []opType{opWriteAt, opWriteAt, opSync, opWriteAt, opWriteAt, opWriteAt, opSync, opWriteAt, opSync} expectedOffsets := []int64{0, 10, -1, 20, 30, 40, -1, 50, -1} offsets := make([]int64, len(ops)) actual := make([]opType, len(ops)) for i, op := range ops { t := op.Type() off := int64(-1) if t == opWriteAt { off = op.At() } actual[i] = t offsets[i] = off } assert.Equal(expectedOps, actual) assert.Equal(expectedOffsets, offsets) }) assert.Run("ordered writes", func(assert *assertions) { var ops testIOOperations b, target := blockingTarget(recordWriteOps(&ops)) b.Block() w, teardown := newTestWriter(target, 10) defer mustSucceed(assert, teardown) var tmp [10]byte sync := newTxWriteSync() w.Sync(sync) // start with sync, to guarantee writer is really blocked w.Schedule(sync, 3, tmp[:]) w.Schedule(sync, 2, tmp[:]) w.Schedule(sync, 1, tmp[:]) w.Sync(sync) // unblock writer, so scheduled write commands will be executed b.Unblock() if !assert.NoError(waitFn(1*time.Second, sync.Wait)) { assert.FailNow("invalid writer state") } expected := []int64{10, 20, 30} var actual []int64 for _, op := range ops { if op.Type() == opWriteAt { actual = append(actual, op.At()) assert.Equal(10, len(op.Contents())) } } assert.Equal(expected, actual) }) assert.Run("fail on sync", func(assert *assertions) { expectedErr := errors.New("ups") var ops testIOOperations target := recordWriteOps(&ops) recordSync := target.sync target.sync = func() error { recordSync() return expectedErr } w, teardown := newTestWriter(target, 10) defer mustSucceed(assert, teardown) var tmp [10]byte sync := newTxWriteSync() w.Schedule(sync, 1, tmp[:]) w.Sync(sync) w.Schedule(sync, 2, tmp[:]) w.Sync(sync) err := waitFn(1*time.Second, sync.Wait) if expectedErr != err { assert.FailNow("unexpected error") } // writer should stop on first error and ignore all following commands expectedOps := []opType{opWriteAt, opSync} actual := make([]opType, len(ops)) for i, op := range ops { actual[i] = op.Type() } assert.Equal(expectedOps, actual) }) assert.Run("fail on write", func(assert *assertions) { expectedErr := errors.New("ups") var ops testIOOperations target := recordWriteOps(&ops) recordWrites := target.writeAt target.writeAt = func(p []byte, off int64) (int, error) { recordWrites(p, off) return 0, expectedErr } w, teardown := newTestWriter(target, 10) defer mustSucceed(assert, teardown) var tmp [10]byte sync := newTxWriteSync() w.Schedule(sync, 1, tmp[:]) w.Schedule(sync, 2, tmp[:]) w.Sync(sync) w.Schedule(sync, 3, tmp[:]) w.Schedule(sync, 4, tmp[:]) w.Sync(sync) err := waitFn(5*time.Second, sync.Wait) assert.Error(err) assert.Equal(expectedErr, err) // writer should stop on first error and ignore all following commands expectedOps := []opType{opWriteAt} actual := make([]opType, len(ops)) for i, op := range ops { actual[i] = op.Type() } assert.Equal(expectedOps, actual) }) } func newTestWriter(to writable, pagesize uint) (*writer, func() error) { w := &writer{} w.Init(to, pagesize) cw := makeCloseWait(1 * time.Second) cw.Add(1) go func() { defer cw.Done() w.Run() }() return w, func() error { w.Stop() if !cw.Wait() { return errors.New("test writer shutdown timeout") } return nil } } func (w *testWriterTarget) Sync() error { return w.sync() } func (w *testWriterTarget) WriteAt(p []byte, off int64) (n int, err error) { return w.writeAt(p, off) } var ignoreOps = &testWriterTarget{ writeAt: func(p []byte, _ int64) (int, error) { return len(p), nil }, sync: func() error { return nil }, } func recordWriteOps(ops *testIOOperations) *testWriterTarget { return &testWriterTarget{ writeAt: func(p []byte, off int64) (n int, err error) { *ops = append(*ops, &testWriteAtOP{at: off, contents: p}) return len(p), nil }, sync: func() error { *ops = append(*ops, syncOp) return nil }, } } func blockingTarget(w *testWriterTarget) (*blocker, *testWriterTarget) { b := newBlocker() return b, &testWriterTarget{ writeAt: func(p []byte, off int64) (n int, err error) { b.Wait() return w.writeAt(p, off) }, sync: func() error { b.Wait() return w.sync() }, } } func (op *testWriteAtOP) Type() opType { return opWriteAt } func (op *testWriteAtOP) At() int64 { return op.at } func (op *testWriteAtOP) Contents() []byte { return op.contents } var syncOp = (*testSyncOP)(nil) func (op *testSyncOP) Type() opType { return opSync } func (op *testSyncOP) At() int64 { panic("sync op") } func (op *testSyncOP) Contents() []byte { panic("sync op") } func mustSucceed(assert *assertions, fn func() error) { assert.NoError(fn()) } <|start_filename|>vendor/github.com/elastic/go-txfile/wal_test.go<|end_filename|> package txfile import ( "math/rand" "testing" "github.com/urso/qcgen" ) func TestWAL(t *testing.T) { assert := newAssertions(t) assert.Run("tx updates", func(assert *assertions) { assert.Run("add entries to empty wal", func(assert *assertions) { wal := makeWALog() tx := wal.makeTxWALState(0) tx.Set(1, 10) tx.Set(2, 100) upd := createMappingUpdate(wal.mapping, &tx) assert.Equal(walMapping{1: 10, 2: 100}, upd) }) assert.Run("remove entries from empty wal", func(assert *assertions) { wal := makeWALog() tx := wal.makeTxWALState(0) tx.Release(10) assert.Equal(walMapping{}, createMappingUpdate(wal.mapping, &tx)) }) assert.Run("add to non empty wal", func(assert *assertions) { wal := makeWALog() wal.mapping = walMapping{10: 100} tx := wal.makeTxWALState(0) tx.Set(10, 1000) tx.Set(11, 101) upd := createMappingUpdate(wal.mapping, &tx) assert.Equal(walMapping{10: 1000, 11: 101}, upd, "new mapping mismatch") assert.Equal(walMapping{10: 100}, wal.mapping, "original mapping has been updated") }) assert.Run("remove from non empty wal", func(assert *assertions) { wal := makeWALog() wal.mapping = walMapping{10: 100, 20: 2000} tx := wal.makeTxWALState(0) tx.Release(10) upd := createMappingUpdate(wal.mapping, &tx) assert.Equal(walMapping{20: 2000}, upd, "new mapping mismatch") assert.Equal(walMapping{10: 100, 20: 2000}, wal.mapping, "original mapping has been updated") }) assert.Run("add and remove same mapping from non empty wal", func(assert *assertions) { wal := makeWALog() wal.mapping = walMapping{10: 100} tx := wal.makeTxWALState(0) tx.Set(10, 1000) tx.Set(11, 101) tx.Release(10) upd := createMappingUpdate(wal.mapping, &tx) assert.Equal(walMapping{11: 101}, upd, "new mapping mismatch") assert.Equal(walMapping{10: 100}, wal.mapping, "original mapping has been updated") }) }) assert.Run("serialization", func(assert *assertions) { assert.Run("empty mapping", func(assert *assertions) { store := newTestPageStore(64) mapping, ids, err := readWAL(store.Get, PageID(0)) assert.NoError(err) assert.Nil(ids) assert.Equal(walMapping{}, mapping) }) // uses fatal on error, so we don't have to see the complete input on failure assert.Run("randomized", makeQuickCheck(makeGenMapping(0, 1500), func(mapping walMapping) bool { pageSize := uint(64) store := newTestPageStore(pageSize) updateWAL := len(mapping) != 0 root := PageID(0) pageCount := uint32(predictWALMappingPages(mapping, pageSize)) var regions regionList tracef("mapping size=%v, page size=%v, page count=%v", len(mapping), pageSize, pageCount) if updateWAL { root = 3 regions = regionList{{root, pageCount}} err := writeWAL(regions, pageSize, mapping, store.Set) assert.FatalOnError(err, "writing wal mapping failed") } newMapping, ids, err := readWAL(store.Get, root) assert.FatalOnError(err, "reading wal mapping failed") ok := assert.Equal(regions, ids.Regions(), "meta pages use doesn't match up") ok = ok && assert.Equal(mapping, newMapping, "mappings not equal after read") return ok })) }) } func makeGenMapping(min, max uint64) func(*rand.Rand) walMapping { return func(rng *rand.Rand) walMapping { mapping := walMapping{} count := qcgen.GenUint64Range(rng, min, max) for i := count; i > 0; i-- { mapping[qcMakePageID(rng)] = qcMakePageID(rng) } return mapping } } <|start_filename|>Makefile<|end_filename|> BEAT_NAME=kafkabeat BEAT_PATH=github.com/arkady-emelyanov/kafkabeat BEAT_GOPATH=$(firstword $(subst :, ,${GOPATH})) BEAT_URL=https://${BEAT_PATH} SYSTEM_TESTS=false TEST_ENVIRONMENT=false ES_BEATS?=./vendor/github.com/elastic/beats GOPACKAGES=$(shell govendor list -no-status +local) GOX_OS= GOX_OSARCH=darwin/amd64 linux/amd64 windows/amd64 PREFIX?=. NOTICE_FILE=NOTICE GOBUILD_FLAGS=-i -ldflags "-X $(BEAT_PATH)/vendor/github.com/elastic/beats/libbeat/version.buildTime=$(NOW) -X $(BEAT_PATH)/vendor/github.com/elastic/beats/libbeat/version.commit=$(COMMIT_ID)" # Path to the libbeat Makefile -include $(ES_BEATS)/libbeat/scripts/Makefile # This is called by the beats packer before building starts .PHONY: before-build before-build: # Collects all dependencies and then calls update .PHONY: collect collect: .PHONY: test-beat test-beat: go test ./... <|start_filename|>vendor/github.com/elastic/go-txfile/pq/pq_rand_test.go<|end_filename|> package pq import ( "fmt" "math/rand" "strings" "github.com/elastic/go-txfile/internal/mint" ) type testCtx struct { t *mint.T rng *rand.Rand written []string read []string acked int } type ( scenario []testOp testOp struct { describe string validate validator exec execer } execer func(*testCtx, *testQueue) validator func(*testCtx, *testQueue) ) func (s scenario) String() string { ops := make([]string, len(s)) for i, op := range s { ops[i] = op.describe } return strings.Join(ops, "\n") } var opReopen = testOp{ describe: "opReopen", validate: checkAvail, exec: func(_ *testCtx, qu *testQueue) { qu.Reopen() }, } var opReadAll = testOp{ describe: "opReadAll", validate: checkAll(checkNoAvail, checkAllEvents), exec: func(ctx *testCtx, qu *testQueue) { ctx.read = append(ctx.read, qu.read(-1)...) }, } var opFinalize = testOp{ describe: "opFinalize", validate: checkAll(checkNoAvail, checkAllEvents), exec: func(ctx *testCtx, qu *testQueue) { ctx.read = append(ctx.read, qu.read(-1)...) }, } func opWriteEvents(lens ...int) testOp { return testOp{ describe: fmt.Sprintf("opWriteEvents %v: %v", len(lens), lens), validate: checkAvail, exec: func(ctx *testCtx, qu *testQueue) { for _, l := range lens { event := genQcRandString(exactly(l))(ctx.rng) qu.append(event) ctx.written = append(ctx.written, event) } qu.flush() }, } } func opRandEvents(N, minSz, maxSz int, seed int64) testOp { name := fmt.Sprintf("opRandEvents %v: min size=%v, max size=%v, seed=%v", N, minSz, maxSz, seed) if seed == 0 { seed = mint.RngSeed() name = fmt.Sprintf("%v, run seed=%v", name, seed) } return testOp{ describe: name, validate: checkAvail, exec: func(ctx *testCtx, qu *testQueue) { rng := mint.NewRng(seed) for i := 0; i < N; i++ { event := genQcRandString(testRange{minSz, maxSz})(rng) qu.append(event) ctx.written = append(ctx.written, event) } qu.flush() }, } } var opACKAll = testOp{ describe: "opACKAll", validate: checkNoPending, exec: func(ctx *testCtx, qu *testQueue) { delta := len(ctx.written) - ctx.acked qu.ack(uint(delta)) }, } func opACKEvents(n int) testOp { return testOp{ describe: fmt.Sprintf("opACKEvents %v", n), validate: checkPending, exec: func(ctx *testCtx, qu *testQueue) { ctx.acked += n qu.ack(uint(n)) }, } } func checkAll(checks ...validator) validator { return func(ctx *testCtx, qu *testQueue) { for _, check := range checks { check(ctx, qu) } } } func checkAllEvents(ctx *testCtx, _ *testQueue) { ctx.t.Equal(ctx.written, ctx.read, "comparing written with read events") } func checkNoAvail(ctx *testCtx, qu *testQueue) { ctx.t.Equal(0, qu.len(), "expected no events to be available") } func checkAvail(ctx *testCtx, qu *testQueue) { ctx.t.Equal(len(ctx.written), len(ctx.read)+qu.len(), "available events mismatch") } func checkNoPending(ctx *testCtx, qu *testQueue) { ctx.t.Equal(0, qu.Pending()) } func checkPending(ctx *testCtx, qu *testQueue) { ctx.t.Equal(len(ctx.written)-ctx.acked, qu.Pending()) } func runScenario(t *mint.T, cfg config, ops scenario) bool { qu, teardown := setupQueue(t, cfg) defer teardown() rng := mint.NewRng(-1) ctx := &testCtx{t: t, rng: rng} for _, op := range ops { traceln("run op:", op.describe) if op.exec != nil { op.exec(ctx, qu) if t.Failed() { return false } } if op.validate != nil { op.validate(ctx, qu) if t.Failed() { return false } } } return !t.Failed() } func nOfSize(n int, sz int) []int { ret := make([]int, n) for i := range ret { ret[i] = sz } return ret } func concatSizes(all ...[]int) []int { var ret []int for _, other := range all { ret = append(ret, other...) } return ret } <|start_filename|>vendor/github.com/elastic/go-txfile/testing_test.go<|end_filename|> package txfile import ( "errors" "math/rand" "sync" "testing" "time" "github.com/urso/qcgen" "github.com/elastic/go-txfile/internal/mint" ) // assertions wraps the testing, assert, and quick packages in order to provide // some unified functionality. // The Run method pushes a new tracer to the tracer stack, such that trace prints // will be captured by the current testing context. type assertions = mint.T type blocker struct { blocked bool mux sync.Mutex cond *sync.Cond } type closeWaiter struct { wg sync.WaitGroup duration time.Duration } type testPageStore struct { pageSize uint pages map[PageID][]byte } func newAssertions(t *testing.T) *assertions { a := mint.NewWith(t, func(sub *mint.T) func() { pushTracer(mint.NewTestLogTracer(sub, logTracer)) return popTracer }) a.SetDefaultGenerators(qcMakePageID) return a } func newBlocker() *blocker { b := &blocker{} b.cond = sync.NewCond(&b.mux) return b } func (b *blocker) Block() { b.mux.Lock() b.blocked = true b.mux.Unlock() } func (b *blocker) Unblock() { b.mux.Lock() b.blocked = false b.mux.Unlock() b.cond.Signal() } func (b *blocker) Wait() { b.mux.Lock() defer b.mux.Unlock() for b.blocked { b.cond.Wait() } } func makeQuickCheck(fns ...interface{}) func(*assertions) { return func(assert *assertions) { assert.QuickCheck(fns...) } } func makeCloseWait(timeout time.Duration) closeWaiter { return closeWaiter{duration: timeout} } func (w *closeWaiter) Add(n int) { w.wg.Add(n) } func (w *closeWaiter) Done() { w.wg.Done() } func (w *closeWaiter) Wait() bool { err := waitFn(w.duration, func() error { w.wg.Wait() return nil }) return err == nil } func newTestPageStore(pageSize uint) *testPageStore { return &testPageStore{ pages: map[PageID][]byte{}, pageSize: pageSize, } } func (p *testPageStore) Get(id PageID) []byte { if id < 2 { panic("must not access file meta region") } b := p.pages[id] if b == nil { b := make([]byte, p.pageSize) p.pages[id] = b } return b } func (p *testPageStore) Set(id PageID, b []byte) error { if id < 2 { panic("must not overwrite file meta region") } p.pages[id] = b return nil } func waitFn(timeout time.Duration, fn func() error) error { ch := make(chan error) go func() { ch <- fn() }() select { case err := <-ch: return err case <-time.After(timeout): return errors.New("wait timed out") } } // quick check generators func qcMakePageID(rng *rand.Rand) PageID { max := uint64(1 << (64 - entryBits)) if qcgen.GenBool(rng) { max = entryOverflow - 1 // generate 'small' id only } return PageID(qcgen.GenUint64Range(rng, 2, max)) } <|start_filename|>vendor/github.com/elastic/go-txfile/vfs_test.go<|end_filename|> package txfile import ( "io/ioutil" "os" "path" "testing" ) func TestOSFileSupport(t *testing.T) { assert := newAssertions(t) setupFile := func(assert *assertions, file string) (vfsFile, func()) { path, teardown := setupPath(assert, file) f, err := openOSFile(path, os.ModePerm) if err != nil { teardown() assert.Fatal(err) } return f, func() { f.Close() teardown() } } assert.Run("file size", func(assert *assertions) { file, teardown := setupFile(assert, "") defer teardown() _, err := file.WriteAt([]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 0) assert.FatalOnError(err) sz, err := file.Size() assert.NoError(err) assert.Equal(10, int(sz)) }) assert.Run("lock/unlock succeed", func(assert *assertions) { file, teardown := setupFile(assert, "") defer teardown() err := file.Lock(true, false) assert.NoError(err) err = file.Unlock() assert.NoError(err) }) assert.Run("locking locked file fails", func(assert *assertions) { f1, teardown := setupFile(assert, "") defer teardown() f2, err := openOSFile(f1.Name(), os.ModePerm) assert.FatalOnError(err) defer f2.Close() err = f1.Lock(true, false) assert.NoError(err) err = f2.Lock(true, false) assert.Error(err) err = f1.Unlock() assert.NoError(err) }) assert.Run("mmap file", func(assert *assertions) { f, teardown := setupFile(assert, "") defer teardown() var buf = [10]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} n, err := f.WriteAt(buf[:], 0) assert.Equal(len(buf), n) assert.NoError(err) mem, err := f.MMap(len(buf)) assert.FatalOnError(err) defer func() { assert.NoError(f.MUnmap(mem)) }() assert.Equal(buf[:], mem[:len(buf)]) }) } func setupPath(assert *assertions, file string) (string, func()) { dir, err := ioutil.TempDir("", "") assert.FatalOnError(err) if file == "" { file = "test.dat" } return path.Join(dir, file), func() { os.RemoveAll(dir) } } <|start_filename|>vendor/github.com/elastic/go-seccomp-bpf/cmd/sandbox/main.go<|end_filename|> // Licensed to Elasticsearch B.V. under one or more contributor // license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright // ownership. Elasticsearch B.V. licenses this file to you under // the Apache License, Version 2.0 (the "License"); you may // not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. package main import ( "flag" "fmt" "os" "os/exec" "github.com/elastic/go-ucfg/yaml" "github.com/elastic/go-seccomp-bpf" ) var ( policyFile string noNewPrivs bool ) func main() { flag.StringVar(&policyFile, "policy", "seccomp.yml", "seccomp policy file") flag.BoolVar(&noNewPrivs, "no-new-privs", true, "set no new privs bit") flag.Parse() args := flag.Args() if len(args) == 0 { fmt.Fprintf(os.Stderr, "You must specify a command and args to execute.\n") os.Exit(1) } // Load policy from file. policy, err := parsePolicy() if err != nil { fmt.Fprintf(os.Stderr, "error: %v\n", err) os.Exit(1) } // Create a filter based on config. filter := seccomp.Filter{ NoNewPrivs: noNewPrivs, Flag: seccomp.FilterFlagTSync, Policy: *policy, } // Load the BPF filter using the seccomp system call. if err = seccomp.LoadFilter(filter); err != nil { fmt.Fprintf(os.Stderr, "error loading filter: %v\n", err) os.Exit(1) } // Execute the specified command (requires execve). cmd := exec.Command(args[0], args[1:]...) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr cmd.Stdin = os.Stdin if err = cmd.Run(); err != nil { fmt.Fprintf(os.Stderr, "error: %v\n", err) os.Exit(1) } } func parsePolicy() (*seccomp.Policy, error) { conf, err := yaml.NewConfigWithFile(policyFile) if err != nil { return nil, err } type Config struct { Seccomp seccomp.Policy } var config Config if err = conf.Unpack(&config); err != nil { return nil, err } return &config.Seccomp, nil } <|start_filename|>beater/decoder.go<|end_filename|> package beater import ( "encoding/json" "time" "github.com/Shopify/sarama" "github.com/elastic/beats/libbeat/beat" ) // Decoder decoder interface type decoder interface { Decode(msg *sarama.ConsumerMessage) *beat.Event } type jsonDecoder struct { timestampKey string timestampLayout string timeNowFn func() time.Time } // JSON decoder func newJSONDecoder(timestampKey, timestampLayout string) *jsonDecoder { return &jsonDecoder{ timestampKey: timestampKey, timestampLayout: timestampLayout, timeNowFn: time.Now, } } func (d *jsonDecoder) Decode(msg *sarama.ConsumerMessage) *beat.Event { fields := map[string]interface{}{} if err := json.Unmarshal(msg.Value, &fields); err != nil { return nil } // special @timestamp field handling var ts time.Time if val, exists := fields[d.timestampKey]; exists { delete(fields, d.timestampKey) // drop timestamp key if s, ok := val.(string); ok { if p, err := time.Parse(d.timestampLayout, s); err == nil { ts = time.Time(p) } } } if ts.IsZero() { if msg.Timestamp.IsZero() { ts = d.timeNowFn() } else { ts = msg.Timestamp } } return &beat.Event{ Timestamp: ts, Fields: fields, } } // Plain decoder type plainDecoder struct { timeNowFn func() time.Time } func newPlainDecoder() *plainDecoder { return &plainDecoder{ timeNowFn: time.Now, } } func (d *plainDecoder) Decode(msg *sarama.ConsumerMessage) *beat.Event { fields := map[string]interface{}{ "message": string(msg.Value), } ts := msg.Timestamp if ts.IsZero() { ts = d.timeNowFn() } return &beat.Event{ Timestamp: ts, Fields: fields, } } <|start_filename|>vendor/github.com/elastic/go-txfile/alloc_test.go<|end_filename|> package txfile import ( "math" "math/rand" "testing" "github.com/urso/qcgen" ) type allocatorTest func(*allocator) bool type allocatorTestRunner func(assert *assertions, cfg allocatorConfig, tst allocatorTest) type allocatorConfig struct { // Minimum continuous pages that must be available in new allocation area. At // least one region will be >= MinContPages. MinContPages uint // Minium number of free pages that must be available. MinFreePages uint // propability of a freespace region to be assigned to the meta area. PropMetaPage float64 // EndMarker and MaxPages. One must be set. EndMarker uint MaxPages uint } func TestDataAllocator(t *testing.T) { assert := newAssertions(t) assert.Run("fresh allocator", func(assert *assertions) { prepareAlloc := func(pages uint) (*allocator, *dataAllocator, txAllocState) { state := makeFreshAllocator(allocatorConfig{MinFreePages: pages}) allocator := state.DataAllocator() tx := state.makeTxAllocState(false, 0) return state, allocator, tx } assert.Run("available space", func(assert *assertions) { assert.Run("bound allocator", func(assert *assertions) { _, allocator, tx := prepareAlloc(100) assert.Equal(100, int(allocator.Avail(&tx))) }) assert.Run("unbound allocator", func(assert *assertions) { _, allocator, tx := prepareAlloc(0) assert.Equal(noLimit, allocator.Avail(&tx)) }) }) // common data allocator tests testDataAllocator(assert, func(assert *assertions, cfg allocatorConfig, tst allocatorTest) { tst(makeFreshAllocator(cfg)) }) }) // QuickCheck based allocator tests, with randomized initial allocation state assert.Run("with freelist entries", func(assert *assertions) { // Run randomized data allocator tests. The allocator state is randomized // on each run. testDataAllocator(assert, func(assert *assertions, cfg allocatorConfig, tst allocatorTest) { assert.QuickCheck(makeAllocatorState(cfg), tst) }) }) } func testDataAllocator(assert *assertions, runner allocatorTestRunner) { prepareAlloc := func(st *allocator) (*dataAllocator, txAllocState) { return st.DataAllocator(), st.makeTxAllocState(false, 0) } run := func(title string, cfg allocatorConfig, fn func(*assertions, *allocator) bool) { assert.Run(title, func(assert *assertions) { runner(assert, cfg, func(st *allocator) bool { return fn(assert, st) }) }) } run("alloc regions", allocatorConfig{ MaxPages: 500, MinFreePages: 20, }, func(assert *assertions, state *allocator) bool { var regions regionList allocator, tx := prepareAlloc(state) n := allocator.AllocRegionsWith(&tx, 20, regions.Add) return assert.Equal(20, int(n)) && assert.Equal(20, int(regions.CountPages())) }) run("alloc continuous", allocatorConfig{ MinContPages: 100, MaxPages: 1 << 20, }, func(assert *assertions, state *allocator) bool { allocator, tx := prepareAlloc(state) avail := allocator.Avail(&tx) r := allocator.AllocContinuousRegion(&tx, 100) return assert.Equal(100, int(r.count)) && assert.Equal(avail-100, allocator.Avail(&tx)) }) run("impossible alloc regions", allocatorConfig{ MaxPages: 100, }, func(assert *assertions, state *allocator) bool { allocator, tx := prepareAlloc(state) var regions regionList n := allocator.AllocRegionsWith(&tx, 200, regions.Add) return assert.Equal(0, int(n)) && assert.Nil(regions) }) run("impossible alloc continuous", allocatorConfig{ MaxPages: 100, }, func(assert *assertions, state *allocator) bool { allocator, tx := prepareAlloc(state) r := allocator.AllocContinuousRegion(&tx, 200) return assert.Equal(PageID(0), r.id) }) run("allocate and free regions", allocatorConfig{ MaxPages: 10000, MinFreePages: 100, MinContPages: 100, }, func(assert *assertions, state *allocator) bool { allocator, tx := prepareAlloc(state) r := allocator.AllocContinuousRegion(&tx, 100) if !assert.Equal(100, int(r.count), "alloc mismatch") { return false } // free region r.EachPage(func(id PageID) { allocator.Free(&tx, id) }) // try to allocate same freed region again expected := r r = allocator.AllocContinuousRegion(&tx, 100) return assert.Equal(expected, r) }) run("rollback restores original data region after allocations", allocatorConfig{ MinFreePages: 50, MaxPages: 500, }, func(assert *assertions, state *allocator) bool { allocator, tx := prepareAlloc(state) orig := copyAllocArea(state.data) var regions regionList allocator.AllocRegionsWith(&tx, 50, regions.Add) if !assert.Equal(50, int(regions.CountPages())) { return false } // check state has been changed assert.NotEqual(orig, state.data) // undo allocations state.Rollback(&tx) return assert.Equal(orig, state.data) }) run("free pages after commit", allocatorConfig{ MinFreePages: 50, MaxPages: 500, }, func(assert *assertions, state *allocator) bool { allocator, tx := prepareAlloc(state) origAvail := allocator.Avail(&tx) // allocate regions in first transaction var regions regionList allocator.AllocRegionsWith(&tx, 50, regions.Add) if !assert.Equal(origAvail-50, allocator.Avail(&tx), "invalid allocator state") { return false } // simulate commit by creating a new tx allocation state: tx = state.makeTxAllocState(false, 0) // return all pages in new transaction regions.EachPage(func(id PageID) { allocator.Free(&tx, id) }) // commit transaction state: state.data.commit(mergeRegionLists(state.data.freelist.regions, tx.data.freed.Regions())) // validate tx = state.makeTxAllocState(false, 0) return assert.Equal(int(origAvail), int(allocator.Avail(&tx))) }) } func TestMetaAllocator(t *testing.T) { assert := newAssertions(t) assert.Run("fresh allocator", func(assert *assertions) { prepareAlloc := func(pages uint) (*allocator, *metaAllocator, txAllocState) { state := makeFreshAllocator(allocatorConfig{MinFreePages: pages}) allocator := state.MetaAllocator() tx := state.makeTxAllocState(false, 0) return state, allocator, tx } assert.Run("available space", func(assert *assertions) { assert.Run("bound allocator", func(assert *assertions) { _, allocator, tx := prepareAlloc(100) assert.Equal(100, int(allocator.Avail(&tx))) }) assert.Run("unbound allocator", func(assert *assertions) { _, allocator, tx := prepareAlloc(0) assert.Equal(noLimit, allocator.Avail(&tx)) }) }) // common data allocator tests testMetaAllocator(assert, func(assert *assertions, cfg allocatorConfig, tst allocatorTest) { tst(makeFreshAllocator(cfg)) }) }) // QuickCheck based allocator tests, with randomized initial allocation state assert.Run("with freelist entries", func(assert *assertions) { // Run randomized data allocator tests. The allocator state is randomized // on each run. testMetaAllocator(assert, func(assert *assertions, cfg allocatorConfig, tst allocatorTest) { assert.QuickCheck(makeAllocatorState(cfg), tst) }) }) assert.Run("overflow release", func(assert *assertions) { type input struct { regions regionList maxPages, endMarker uint64 } type expected struct { regions regionList freed uint64 } testcases := []struct { title string input input expected expected }{ { "do not free anything if no file limit", input{ regions: regionList{{1, 1000}, {2000, 5000}}, maxPages: 0, endMarker: 7000, }, expected{ regions: regionList{{1, 1000}, {2000, 5000}}, }, }, { "do not free if end marker < max pages, freelist ends at end marker", input{ regions: regionList{{1, 1000}, {2000, 5000}}, maxPages: 10000, endMarker: 7000, }, expected{ regions: regionList{{1, 1000}, {2000, 5000}}, }, }, { "do not free if end marker < max pages, freelist ends before end marker", input{ regions: regionList{{1, 1000}, {2000, 1000}}, maxPages: 10000, endMarker: 7000, }, expected{ regions: regionList{{1, 1000}, {2000, 1000}}, }, }, { "do not free if end marker > max pages, but last region not adjacent to end marker", input{ regions: regionList{{1, 1000}, {2000, 1000}, {4200, 500}}, maxPages: 4000, endMarker: 5000, }, expected{ regions: regionList{{1, 1000}, {2000, 1000}, {4200, 500}}, }, }, { "free, remove complete region", input{ regions: regionList{{1, 1000}, {2000, 1000}, {4500, 500}}, maxPages: 4000, endMarker: 5000, }, expected{ regions: regionList{{1, 1000}, {2000, 1000}}, freed: 500, }, }, { "free, remove complete region, region adjacent to max pages", input{ regions: regionList{{1, 1000}, {2000, 1000}, {4000, 1000}}, maxPages: 4000, endMarker: 5000, }, expected{ regions: regionList{{1, 1000}, {2000, 1000}}, freed: 1000, }, }, { "free, remove adjacent complete regions", input{ regions: regionList{{1, 1000}, {2000, 1000}, {4000, 500}, {4500, 500}}, maxPages: 4000, endMarker: 5000, }, expected{ regions: regionList{{1, 1000}, {2000, 1000}}, freed: 1000, }, }, { "free, split region", input{ regions: regionList{{1, 1000}, {2000, 1000}, {3000, 2000}}, maxPages: 4000, endMarker: 5000, }, expected{ regions: regionList{{1, 1000}, {2000, 1000}, {3000, 1000}}, freed: 1000, }, }, { "free, split region with adjacent/unmerged regions", input{ regions: regionList{{1, 1000}, {2000, 1000}, {3000, 1500}, {4500, 500}}, maxPages: 4000, endMarker: 5000, }, expected{ regions: regionList{{1, 1000}, {2000, 1000}, {3000, 1000}}, freed: 1000, }, }, } for _, test := range testcases { input, expected := test.input, test.expected assert.Run(test.title, func(assert *assertions) { list := make(regionList, len(input.regions)) copy(list, test.input.regions) actual, freed := releaseOverflowPages(list, uint(input.maxPages), PageID(input.endMarker)) assert.Equal(expected.freed, uint64(freed)) assert.Equal(expected.regions, actual) }) } }) } func testMetaAllocator(assert *assertions, runner allocatorTestRunner) { prepareAlloc := func(st *allocator) (*metaAllocator, txAllocState) { return st.MetaAllocator(), st.makeTxAllocState(false, 0) } run := func(title string, cfg allocatorConfig, fn func(*assertions, *allocator) bool) { assert.Run(title, func(assert *assertions) { runner(assert, cfg, func(st *allocator) bool { return fn(assert, st) }) }) } run("alloc regions", allocatorConfig{ MaxPages: 100, MinFreePages: 20, PropMetaPage: 0.3, }, func(assert *assertions, state *allocator) bool { allocator, tx := prepareAlloc(state) avail := allocator.Avail(&tx) regions := allocator.AllocRegions(&tx, 20) ok := assert.Equal(20, int(regions.CountPages())) ok = ok && assert.Equal(avail-20, allocator.Avail(&tx)) return ok }) run("impossible alloc regions", allocatorConfig{ MaxPages: 100, PropMetaPage: 0.3, }, func(assert *assertions, state *allocator) bool { allocator, tx := prepareAlloc(state) regions := allocator.AllocRegions(&tx, 200) return assert.Nil(regions) }) run("alloc regions with overflow area", allocatorConfig{ MaxPages: 100, PropMetaPage: 0.3, }, func(assert *assertions, state *allocator) bool { allocator, tx := prepareAlloc(state) tx.options.overflowAreaEnabled = true regions := allocator.AllocRegions(&tx, 150) return assert.Equal(150, int(regions.CountPages())) }) run("rollback returns pages into meta area", allocatorConfig{ MinFreePages: 50, MaxPages: 500, PropMetaPage: 0.3, }, func(assert *assertions, state *allocator) bool { allocator, tx := prepareAlloc(state) origData := copyAllocArea(state.data) origMeta := copyAllocArea(state.meta) regions := allocator.AllocRegions(&tx, 50) if !assert.Equal(50, int(regions.CountPages())) { return false } state.Rollback(&tx) ok := true ok = assert.Equal(origData, state.data, "data area mismatch") && ok if len(origMeta.freelist.regions) > 0 { ok = assert.Equal(origMeta, state.meta, "meta area mismatch") && ok } else { ok = assert.Equal(0, len(state.meta.freelist.regions), "meta area mismatch") && ok } return ok }) run("free pages after commit", allocatorConfig{ MinFreePages: 50, MaxPages: 500, }, func(assert *assertions, state *allocator) bool { allocator, tx := prepareAlloc(state) origAvail := allocator.Avail(&tx) // allocate regions in first transaction regions := allocator.AllocRegions(&tx, 50) if !assert.Equal(origAvail-50, allocator.Avail(&tx), "invalid allocator state") { return false } // simulate commit by creating a new tx allocation state: tx = state.makeTxAllocState(false, 0) // return all pages in new transaction allocator.FreeRegions(&tx, regions) // commit transaction state: state.data.commit(mergeRegionLists(state.data.freelist.regions, tx.data.freed.Regions())) state.meta.commit(mergeRegionLists(state.meta.freelist.regions, tx.meta.freed.Regions())) // validate tx = state.makeTxAllocState(false, 0) return assert.Equal(int(origAvail), int(allocator.Avail(&tx))) }) } func makeFreshAllocator(cfg allocatorConfig) *allocator { pages := cfg.MaxPages if cfg.MaxPages == 0 { pages = cfg.EndMarker + cfg.MinContPages + cfg.MinFreePages } pageSize := uint(64) if pages > 0 { pages += 2 } a := &allocator{ maxSize: pages * pageSize, maxPages: pages, pageSize: pageSize, data: allocArea{ endMarker: 2, }, meta: allocArea{ endMarker: 2, }, } // ensure we never return nil lists, such that asserts on list contents will // not complain about nil vs list of length 0 a.data.freelist.regions = regionList{} a.meta.freelist.regions = regionList{} return a } func makeAllocatorState(config allocatorConfig) func(*rand.Rand) *allocator { if config.EndMarker == 0 && config.MaxPages == 0 { panic("either end marker or max size required") } if config.EndMarker > config.MaxPages { panic("end marker must be less then max size") } const pageSize = 64 return func(rng *rand.Rand) *allocator { maxPages := config.MaxPages endMarker := config.EndMarker minContPages := config.MinContPages // if max pages is set, compute randomized end marker. var freePages uint // number of pages available after end of freelist if endMarker == 0 { maxEndMarker := config.MaxPages if qcgen.GenBool(rng) { // continuous space from end of file? maxEndMarker -= config.MinContPages minContPages = 0 endMarker = qcgen.GenUintRange(rng, 2, maxEndMarker) } else { endMarker = maxEndMarker } freePages = maxPages - endMarker traceln("set endmarker to: ", endMarker) traceln("free pages at end of file: ", freePages) } // determine minimum number of pages required to be available in the freelist minFree := config.MinFreePages if minFree > 0 { if freePages >= minFree { minFree = 0 } else { minFree -= freePages } } // Split file into allocated and free regions. Free regions are inserted // into the free list. metaList, dataList := splitRegions(rng, 2, endMarker, minFree, minContPages, config.PropMetaPage) // create allocator state a := &allocator{ maxPages: maxPages, maxSize: maxPages * pageSize, data: allocArea{ endMarker: PageID(endMarker), }, meta: allocArea{ endMarker: PageID(endMarker), }, } a.data.freelist.AddRegions(dataList) a.meta.freelist.AddRegions(metaList) a.metaTotal = metaList.CountPages() return a } } func splitRegions( rng *rand.Rand, start, end uint, minFree, minContPages uint, propMeta float64, ) (meta regionList, data regionList) { traceln("split regions with propability", propMeta) // ensure we never return nil, such that asserts on list contents will // not complain about nil vs list of length 0 meta = regionList{} data = regionList{} addRegion := func(r region) { list := &data if propMeta > 0 && rng.Uint64() < uint64(math.MaxUint64*propMeta) { list = &meta } *list = append(*list, r) } count := end - start if count == minFree { addRegion(region{PageID(start), uint32(count)}) return } if minFree < minContPages { minFree = minContPages } allocMode := qcgen.GenBool(rng) for start <= end { avail := end - start if avail == 0 { break } if avail == minFree || avail == minContPages { addRegion(region{PageID(start), uint32(avail)}) break } if allocMode { // allocMode = true => select are being actively allocated/used if avail > 1 { // advance start pointer, such that at least minFree/minContPages is // still available after advancing the pointer required := minFree if required < minContPages { required = minContPages } // allocate from allocStart to allocEnd, guaranteeing enough we will // have enough space to fullfill MinFreePages and MinContPages // conditions. allocEnd := end - required allocStart := start + 1 if allocStart < allocEnd { start = qcgen.GenUintRange(rng, allocStart, allocEnd) } } } else { // allocMode = false => select area of available space to be put into the // freelist. // add freelist entry split := end if avail > 1 { split = qcgen.GenUintRange(rng, start+1, end) } count := split - start if count >= minContPages { minContPages = 0 } addRegion(region{PageID(start), uint32(count)}) start = split if minFree < count { minFree = 0 } else { minFree -= count } } // switch allocation mode allocMode = !allocMode } optimizeRegionList(&meta) optimizeRegionList(&data) traceln("new testing meta freelist: ", meta) traceln("new testing data freelist: ", data) return } func copyAllocArea(st allocArea) allocArea { new := st L := len(st.freelist.regions) if L > 0 { new.freelist.regions = make(regionList, L) copy(new.freelist.regions, st.freelist.regions) } return new } <|start_filename|>vendor/github.com/elastic/go-txfile/internal/mint/trace.go<|end_filename|> package mint type TestLogTracer struct { backends []backend } type backend struct { print func(...interface{}) printf func(string, ...interface{}) } func NewTestLogTracer(loggers ...interface{}) *TestLogTracer { type testLogger interface { Log(...interface{}) Logf(string, ...interface{}) } type tracer interface { Println(...interface{}) Printf(string, ...interface{}) } bs := make([]backend, 0, len(loggers)) for _, logger := range loggers { var to backend switch v := logger.(type) { case testLogger: to = backend{print: v.Log, printf: v.Logf} case tracer: to = backend{print: v.Println, printf: v.Printf} } if to.print != nil { bs = append(bs, to) } } return &TestLogTracer{bs} } func (t *TestLogTracer) Println(vs ...interface{}) { for _, b := range t.backends { b.print(vs...) } } func (t *TestLogTracer) Printf(fmt string, vs ...interface{}) { for _, b := range t.backends { b.printf(fmt, vs...) } }
arkady-emelyanov/kafkabeat
<|start_filename|>cypress/support/commands.js<|end_filename|> import '@percy/cypress' import 'cypress-file-upload' <|start_filename|>src/css/suggestions/index.css<|end_filename|> .suggestions { background: #f6f6f6; display: flex; height: 100%; margin-top: 8px; padding: 15px; width: 100%; } .suggestions__label { font-size: 0.8rem; font-weight: bold; margin-right: 10px; } .suggestions__option { margin: 0 5px; } <|start_filename|>cypress/integration/application.spec.js<|end_filename|> /// <reference types="cypress" /> const messages = { READY: 'Application is ready to use', PROCESS_STARTED: 'Processing your image.', PROCESS_FINISHED: 'Image has been processed.' } describe('BackgroundRemove Application', () => { it('As a User I should be able to visit application', function () { cy.visit(Cypress.env('CYPRESS_BASE_URL')) cy.percySnapshot() }) it('Should inform me when application is ready to use', function () { cy.contains(messages.READY) cy.percySnapshot() }) it('As a User I should be able to select an image from my machine to remove Background', function () { cy.get('#js-image-picker').attachFile('adult-1868750_1920.jpg') cy.contains(messages.PROCESS_STARTED) cy.contains(messages.PROCESS_FINISHED) cy.percySnapshot() }) it('Should be able to pick suggested image from provided options', function () { cy.get('.suggestions__option').eq(2).click() cy.contains(messages.PROCESS_FINISHED) cy.percySnapshot() }) it('Should be able to interact with advance options', function () { cy.get('#internalResolution').should('not.be.visible') cy.get('[aria-controls="advance-options"]').click() cy.get('#internalResolution').should('be.visible') cy.percySnapshot() cy.get('[aria-controls="advance-options"]').click() cy.get('#internalResolution').should('not.be.visible') cy.percySnapshot() }) it('Should be able to specify background colour for processed image', function () { cy.get('[aria-controls="advance-options"]').click() cy.get('#backgroundColour').invoke('val', '#ff0000').trigger('change') cy.contains(messages.PROCESS_FINISHED) cy.percySnapshot() }) it('Should be able to download processed image', function () { cy.get('#js-download-link').click() cy.percySnapshot() }) }) <|start_filename|>src/css/core-css/index.js<|end_filename|> import './vars.css' import './reset.css' import './screen-readers.css' import './base-styles.css' import './site.css' import './views.css' <|start_filename|>src/css/input-source/index.css<|end_filename|> .input-source { border-right: 1px solid var(--borderColor); display: flex; flex: 1; flex-direction: column; } .input-source__preview { border-bottom: 1px solid var(--borderColor); flex: 1; } .input-source__image { max-height: 426px; width: 100%; } <|start_filename|>src/css/core-css/vars.css<|end_filename|> :root { --main-bg-color: #fff; --main-color: #222; --font: -apple-system, blinkmacsystemfont, "Segoe UI", roboto, "Helvetica Neue", arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; --brand: #01189b; --brand-highlight: #011271; --brand-text: #fff; --borderColor: rgba(0, 0, 0, 0.15); } <|start_filename|>setup-tests.js<|end_filename|> import fs from 'fs'; import path from 'path'; const html = fs.readFileSync(path.resolve(path.join(__dirname, 'public', 'index.html')), { encoding: "utf8" }); global.beforeEach(() => { document.documentElement.innerHTML = html; }); global.afterEach(() => { jest.clearAllMocks(); }); <|start_filename|>src/css/settings/index.css<|end_filename|> .settings__item { border-bottom: 1px solid var(--borderColor); display: flex; flex-direction: column; padding: 8px 15px; } .settings__item--column { flex-direction: row; } .settings__column { display: flex; flex: 1; flex-direction: column; } .settings__advance { margin: 8px 0 8px 0; } <|start_filename|>src/lib/background-removal/__tests__/background-removal.js<|end_filename|> import * as bodyPix from '@tensorflow-models/body-pix' import BackgroundRemoval from '../background-removal' jest.mock('@tensorflow-models/body-pix', () => { return { load: jest.fn() } }) describe('BackgroundRemoval test', () => { let instance beforeEach(() => { instance = new BackgroundRemoval() }) describe('BackgroundRemoval.loadModel()', () => { beforeEach(() => { jest.spyOn(bodyPix, 'load').mockResolvedValue('body-pix-object') }) it('Should exists', () => { expect(instance.loadModel).toBeTruthy() }) it('Should load & return bodyPix model', () => { expect(instance.loadModel()).resolves.toEqual('body-pix-object') }) it('Should only call bodyPix once', async () => { await instance.loadModel() await instance.loadModel() await instance.loadModel() expect(bodyPix.load.mock.calls.length).toEqual(1) }) }) describe('BackgroundRemoval._predict()', () => { const mockBodyPix = { segmentPerson: jest.fn() } beforeEach(() => { jest.spyOn(bodyPix, 'load').mockResolvedValue(mockBodyPix) }) it('Should exists', () => { expect(instance._predict).toBeTruthy() }) it('Should pass arguments to bodyPix', async () => { const imgData = 'imgData' const config = 'config' await instance._predict(imgData, config) expect(mockBodyPix.segmentPerson).toBeCalled() expect(mockBodyPix.segmentPerson).toBeCalledWith(imgData, config) }) }) describe('BackgroundRemoval._intersectPixels()', () => { const backgroundColour = '#0000ff' // blue it('Given I have 1x1 image and segment identified pixel as a body then return image body pixel', async () => { const imgData = { width: 1, height: 1, data: [ 255, 255, 255, 255 // white ] } const predictedSegmentPixelData = { width: 1, height: 1, data: [ 1 // match ] } const expected = { width: 1, height: 1, data: Uint8ClampedArray.from([ 255, 255, 255, 255 ]) } const actual = await instance._intersectPixels(imgData, predictedSegmentPixelData, backgroundColour) expect(actual).toEqual(expected) }) it('Given I have 1x2 image then intersect the identified body with given image and replace other pixel by given background colour', async () => { const imgData = { width: 1, height: 2, data: [ 255, 255, 255, 255, // white 255, 0, 0, 255 // red ] } const predictedSegmentPixelData = { width: 1, height: 2, data: [ 0, // ignore 1 // match ] } const expected = { width: 1, height: 2, data: Uint8ClampedArray.from([ 0, 0, 255, 255, // blue 255, 0, 0, 255 // red ]) } const actual = await instance._intersectPixels(imgData, predictedSegmentPixelData, backgroundColour) expect(actual).toEqual(expected) }) it('Given I have 2x2 image then intersect the identified body with given image and replace other pixel by given background colour', async () => { const imgData = { width: 2, height: 2, data: [ 255, 255, 255, 255, // white 255, 0, 0, 255, // red 255, 0, 0, 255, // red 255, 255, 255, 255 // white ] } const predictedSegmentPixelData = { width: 2, height: 2, data: [ 0, // ignore 0, // ignore 1, // match 0 // ignore ] } const expected = { width: 2, height: 2, data: Uint8ClampedArray.from([ 0, 0, 255, 255, // ignore 0, 0, 255, 255, // ignore 255, 0, 0, 255, // red from imgData 0, 0, 255, 255 // ignore ]) } const actual = await instance._intersectPixels(imgData, predictedSegmentPixelData, backgroundColour) expect(actual).toEqual(expected) }) }) describe('BackgroundRemoval.remove(imgData, config)', () => { const imgData = { width: 1, height: 1, data: Uint8ClampedArray.from([ 255, 255, 255, 255 // white ]) } beforeEach(() => { jest.spyOn(instance, 'loadModel').mockResolvedValue('') jest.spyOn(instance, '_predict').mockResolvedValue('') jest.spyOn(instance, '_intersectPixels').mockResolvedValue(imgData) }) it('Should return data URI to be used by img element', async () => { const actual = await instance.remove(imgData, {}) expect(actual).toEqual(expect.stringContaining('data:image/png;')) }) }) }) <|start_filename|>src/css/core-css/views.css<|end_filename|> .views { display: flex; flex: 1 0 auto; } .views__child { display: flex; flex: 1; position: relative; } .views__frame { border: 0; height: 100%; left: 0; position: absolute; top: 0; width: 100%; }
n00r/tensorflowjs-remove-background
<|start_filename|>src/linux.cpp<|end_filename|> /* * Copyright 2013-2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ #include "linux.hpp" #include "errorlist.hpp" #include "watchdogd.hpp" #include "sub.hpp" #include "repair.hpp" #include "logutils.hpp" #include <zlib.h> static int ConfigureKernelOutOfMemoryKiller(void) { int fd = 0; int dfd = 0; dfd = open("/proc/self", O_DIRECTORY | O_RDONLY); if (dfd == -1) { Logmsg(LOG_ERR, "open failed: %s", MyStrerror(errno)); return -1; } fd = openat(dfd, "oom_score_adj", O_WRONLY); if (fd == -1) { Logmsg(LOG_ERR, "open failed: %s", MyStrerror(errno)); close(dfd); return -1; } if (write(fd, "-1000", strlen("-1000")) < 0) { Logmsg(LOG_ERR, "write failed: %s", MyStrerror(errno)); close(fd); close(dfd); return -1; } close(fd); close(dfd); return 0; } bool PlatformInit(void) { sd_notifyf(0, "READY=1\n" "MAINPID=%lu", (unsigned long)getppid()); if (ConfigureKernelOutOfMemoryKiller() < 0) { Logmsg(LOG_ERR, "unable to configure out of memory killer"); return false; } prctl(PR_SET_DUMPABLE, 0, 0, 0, 0); //prevent children from ptrace() ing main process and helpers return true; } int NativeShutdown(int errorcode, int kexec) { //http://cgit.freedesktop.org/systemd/systemd/tree/src/core/manager.c?id=f49fd1d57a429d4a05ac86352c017a845f8185b3 extern sig_atomic_t stopPing; stopPing = 1; if (kexec == 1) { kill(1, SIGRTMIN + 6); } else if (errorcode == WECMDREBOOT) { kill(1, SIGRTMIN + 5); } else if (errorcode == WETEMP) { kill(1, SIGRTMIN + 4); } else if (errorcode == WECMDRESET) { kill(1, SIGRTMIN + 15); } else { kill(1, SIGRTMIN + 5); } return 0; } int GetConsoleColumns(void) { struct winsize w = { 0 }; if (ioctl(0, TIOCGWINSZ, &w) < 0) { return 80; } return w.ws_col; } int SystemdWatchdogEnabled(pid_t * pid, long long int *const interval) { char *spid = getenv("WATCHDOG_PID"); char *sinv = getenv("WATCHDOG_USEC"); if (spid == NULL || sinv == NULL) return -1; *interval = atoll(sinv); *pid = atoll(spid); return 1; } bool OnParentDeathSend(uintptr_t sig) { if (prctl(PR_SET_PDEATHSIG, (uintptr_t *) sig) == -1) { return false; } return true; } int NoNewProvileges(void) { if (prctl(PR_SET_NO_NEW_PRIVS, 0, 0, 0, 0) < 0) { if (errno != 0) { return -errno; } else { return 1; } } return 0; } int GetCpuCount(void) { return std::thread::hardware_concurrency(); } bool LoadKernelModule(void) { pid_t pid = vfork(); if (pid == 0) { if (execl("/sbin/modprobe", "modprobe", "softdog", NULL) == -1) { _Exit(1); } } if (pid == -1) { abort(); } int ret = 0; waitpid(pid, &ret, 0); if (WEXITSTATUS(ret) == 0) { return true; } return false; } bool MakeDeviceFile(const char *file) { return true; } struct bestDevice { char *driverName; char *deviceName; short score; }; static short ScoreDriver(char *driver) { short score = 0; if (strcmp(driver, "mei_wdt") == 0) { --score; } return score; } char *FindBestWatchdogDevice(void) { DIR *devFolder = opendir("/dev"); struct dirent *device = NULL; struct bestDevice bestDevice = { 0 }; if (!devFolder) { return NULL; } while ((device = readdir(devFolder)) != NULL) { const char *devName = strstr(device->d_name, "watchdog"); if (devName == NULL || *(1 + strrchr(devName, 'g')) == '\0') { continue; } if (bestDevice.driverName == NULL) { char *path; asprintf(&path, "/sys/class/watchdog/%s/device/driver/module", device->d_name); bestDevice.deviceName = strdup(device->d_name); char *derefedPath = realpath(path, NULL); bestDevice.driverName = strdup(basename(derefedPath)); free(derefedPath); free(path); } else { struct bestDevice potentialDevice = { 0 }; char *path; asprintf(&path, "/sys/class/watchdog/%s/device/driver/module", device->d_name); char *derefedPath = realpath(path, NULL); potentialDevice.driverName = strdup(basename(derefedPath)); potentialDevice.deviceName = strdup(device->d_name); if (ScoreDriver(potentialDevice.driverName) > ScoreDriver(bestDevice.driverName)) { free(bestDevice.driverName); free(bestDevice.deviceName); bestDevice = potentialDevice; } free(derefedPath); free(path); } } closedir(devFolder); free(bestDevice.driverName); //will use detected driver name in the future static char * ret; asprintf(&ret, "/dev/%s", bestDevice.deviceName); return ret; } bool GetDeviceMajorMinor(struct dev * m, char *name) { if (name == NULL || m == NULL) { return false; } char *tmp = basename(name); size_t len = 0; char *buf = NULL; struct dev tmpdev = { 0 }; DIR *dir = opendir("/sys/dev/char"); if (dir == NULL) { return false; } for (struct dirent * node = readdir(dir); node != NULL; node = readdir(dir)) { if (node->d_name[0] == '.') { continue; } Wasnprintf(&len, &buf, "/sys/dev/char/%s/uevent", node->d_name); if (buf == NULL) { abort(); } FILE *fp = fopen(buf, "r"); if (fp == NULL) { abort(); } int x = 1; while (getline(&buf, &len, fp) != -1) { char *const name = strtok(buf, "="); char *const value = strtok(NULL, "="); if (Validate(name, value) == false) { continue; } if (x == 1) { tmpdev.major = strtoul(value, NULL, 0); x++; } else if (x == 2) { tmpdev.minor = strtoul(value, NULL, 0); x++; } else if (x == 3) { strcpy(tmpdev.name, value); x = 1; } } if (strcmp(tmpdev.name, tmp) == 0) { closedir(dir); free(buf); fclose(fp); strcpy(m->name, tmpdev.name); m->major = tmpdev.major; m->minor = tmpdev.minor; return true; } fclose(fp); } closedir(dir); free(buf); return false; } int ConfigWatchdogNowayoutIsSet(char *name) { bool found = false; char *buf = NULL; gzFile config = gzopen("/proc/config.gz", "r"); if (config == NULL) { return -1; } gzbuffer(config, 8192); while (true) { char buf[72] = { '\0' }; size_t bytesRead = gzread(config, buf, sizeof(buf) - 1); if (strstr(buf, "# CONFIG_WATCHDOG_NOWAYOUT is not set") != NULL) { found = true; break; } if (bytesRead < sizeof(buf) - 1) { if (gzeof(config)) { break; } else { break; } } } gzclose(config); struct dev ad = { 0 }; GetDeviceMajorMinor(&ad, name); char *devicePath = NULL; Wasprintf(&devicePath, "/sys/dev/char/%lu:%lu/device/driver", ad.major, ad.minor); buf = (char *)calloc(1, 4096); if (devicePath == NULL) { abort(); } readlink(devicePath, buf, 4096 - 1); Wasprintf(&buf, "/sys/module/%s/parameters/nowayout", basename(buf)); free(devicePath); FILE *fp = fopen(buf, "r"); if (fp != NULL) { if (fgetc(fp) == '1') { found = false; } fclose(fp); } free(buf); if (found) { return 0; } return 1; } bool IsClientAdmin(int sock) { struct ucred peercred; socklen_t len = sizeof(struct ucred); if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &peercred, &len) != 0) { return false; } if (peercred.uid == 0) { return true; } return false; } <|start_filename|>src/multicall.cpp<|end_filename|> /* * Copyright 2016-2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <string.h> #include <libgen.h> #include <stdio.h> #include <errno.h> #include <stdlib.h> char * GetExeName(void) { static char buf[1024] = {'\0'}; if (buf[0] != '\0') { return buf; } FILE* fp = fopen("/proc/self/cmdline", "r"); if (fp == NULL) { return buf; } errno = 0; fread(buf, sizeof(buf) - 1, 1, fp); fclose(fp); if (errno != 0) { return buf; } char * cpy = strdup(basename(buf)); if (cpy == NULL) { perror("watchdogd: "); abort(); } strncpy(buf, cpy, sizeof(buf)-1); free(cpy); return buf; } <|start_filename|>src/list.cpp<|end_filename|> /* * Copyright © 2010-2012 Intel Corporation * Copyright © 2010 <NAME> <<EMAIL>> * * 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 (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. * */ #include "watchdogd.hpp" /** * Initialize the list as an empty list. * * Example: * list_init(&bar->list_of_foos); * * @param The list to initialized. */ void list_init(struct list *list) { list->next = list->prev = list; } static void __list_add(struct list *const entry, struct list *const prev, struct list *const next) { next->prev = entry; entry->next = next; entry->prev = prev; prev->next = entry; } /** * Insert a new element after the given list head. The new element does not * need to be initialised as empty list. * The list changes from: * head → some element → ... * to * head → new element → older element → ... * * Example: * struct foo *newfoo = malloc(...); * list_add(&newfoo->entry, &bar->list_of_foos); * * @param entry The new element to prepend to the list. * @param head The existing list. */ void list_add(struct list *entry, struct list *head) { __list_add(entry, head, head->next); } void list_add_tail(struct list *entry, struct list *head) { __list_add(entry, head->prev, head); } void list_replace(struct list *old, struct list *_new) { _new->next = old->next; _new->next->prev = _new; _new->prev = old->prev; _new->prev->next = _new; } /** * Append a new element to the end of the list given with this list head. * * The list changes from: * head → some element → ... → lastelement * to * head → some element → ... → lastelement → new element * * Example: * struct foo *newfoo = malloc(...); * list_append(&newfoo->entry, &bar->list_of_foos); * * @param entry The new element to prepend to the list. * @param head The existing list. */ void list_append(struct list *entry, struct list *head) { __list_add(entry, head->prev, head); } static void __list_del(struct list *prev, struct list *next) { assert(next->prev == prev->next); next->prev = prev; prev->next = next; } static void _list_del(struct list *const entry) { assert(entry->prev->next == entry); assert(entry->next->prev == entry); __list_del(entry->prev, entry->next); } /** * Remove the element from the list it is in. Using this function will reset * the pointers to/from this element so it is removed from the list. It does * NOT free the element itself or manipulate it otherwise. * * Using list_del on a pure list head (like in the example at the top of * this file) will NOT remove the first element from * the list but rather reset the list as empty list. * * Example: * list_del(&foo->entry); * * @param entry The element to remove. */ void list_del(struct list *entry) { _list_del(entry); list_init(entry); } void list_move(struct list *list, struct list *head) { if (list->prev != head) { _list_del(list); list_add(list, head); } } void list_move_tail(struct list *list, struct list *head) { _list_del(list); list_add_tail(list, head); } /** * Check if the list is empty. * * Example: * list_is_empty(&bar->list_of_foos); * * @return True if the list contains one or more elements or False otherwise. */ bool list_is_empty(const struct list *head) { return head->next == head; } <|start_filename|>src/errorlist.hpp<|end_filename|> /* * Copyright 2013-2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ #ifndef ERRORLIST_H #define ERRORLIST_H #define WECMDREBOOT 255 #define WECMDRESET 254 #define WESYSOVERLOAD 253 #define WETEMP 252 #define WEZERO 0 #define WECHTIME 247 #define WECHKILL 248 #define WESYSCALL 249 #define WECUSTOM 246 #define WESCRIPT 251 #define WEPIDFILE 250 #define WEOTHER WEZERO #endif <|start_filename|>src/testdir.hpp<|end_filename|> #ifndef TESTDIR_H #define TESTDIR_H struct repairscriptTranctions { std::atomic_int sem; std::atomic_int ret; }; struct executeScriptsStruct { ProcessList *list; struct cfgoptions *config; }; struct container { volatile std::atomic_ullong workerThreadCount; struct cfgoptions *config; repaircmd_t *cmd; }; typedef struct container Container; #define TEST true #define REPAIR false int CreateLinkedListOfExes(char *repairScriptFolder, ProcessList * p, struct cfgoptions *const); int ExecuteRepairScripts(void); void FreeExeList(ProcessList * p); size_t DirentBufSize(DIR * dirp); bool ExecuteRepairScriptsPreFork(ProcessList *, struct cfgoptions *); #endif <|start_filename|>src/threadpool.hpp<|end_filename|> #ifndef THREADPOOL_H #define THREADPOOL_H extern unsigned long numberOfRepairScripts; bool ThreadPoolAddTask(void *(*)(void*), void *, bool); bool ThreadPoolNew(int threads = numberOfRepairScripts); bool ThreadPoolCancel(void); #endif <|start_filename|>src/main.cpp<|end_filename|> /* * Copyright 2016-2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ #include "watchdogd.hpp" #include "sub.hpp" #include "main.hpp" #include "init.hpp" #include "configfile.hpp" #include "threads.hpp" #include "identify.hpp" #include "bootstatus.hpp" #include "multicall.hpp" #include "daemon.hpp" #include "pidfile.hpp" #include "dbusapi.hpp" #include "logutils.hpp" #include "linux.hpp" #include <systemd/sd-event.h> const bool DISARM_WATCHDOG_BEFORE_REBOOT = true; static volatile sig_atomic_t quit = 0; volatile sig_atomic_t stop = 0; volatile sig_atomic_t stopPing = 0; ProcessList processes; static void PrintConfiguration(struct cfgoptions *const cfg) { Logmsg(LOG_INFO, "int=%lis realtime=%s sync=%s softboot=%s force=%s mla=%.2f mem=%li pid=%i", cfg->sleeptime, cfg->options & REALTIME ? "yes" : "no", cfg->options & SYNC ? "yes" : "no", cfg->options & SOFTBOOT ? "yes" : "no", cfg->options & FORCE ? "yes" : "no", cfg->maxLoadOne, cfg->minfreepages, getppid()); if (cfg->options & ENABLEPING) { for (int cnt = 0; cnt < config_setting_length(cfg->ipAddresses); cnt++) { const char *ipAddress = config_setting_get_string_elem(cfg->ipAddresses, cnt); assert(ipAddress != NULL); Logmsg(LOG_INFO, "ping: %s", ipAddress); } } else { Logmsg(LOG_INFO, "ping: no machine to check"); } if (cfg->options & ENABLEPIDCHECKER) { for (int cnt = 0; cnt < config_setting_length(cfg->pidFiles); cnt++) { const char *pidFilePathName = config_setting_get_string_elem(cfg->pidFiles, cnt); assert(pidFilePathName != NULL); Logmsg(LOG_DEBUG, "pidfile: %s", pidFilePathName); } } else { Logmsg(LOG_INFO, "pidfile: no server process to check"); } Logmsg(LOG_INFO, "test=%s(%i) repair=%s(%i) no_act=%s", cfg->testexepathname == NULL ? "no" : cfg->testexepathname, cfg->testBinTimeout, cfg->exepathname == NULL ? "no" : cfg->exepathname, cfg->repairBinTimeout, cfg->options & NOACTION ? "yes" : "no"); } static void BlockSignals() { sigset_t set; sigemptyset(&set); sigaddset(&set, SIGTERM); sigaddset(&set, SIGUSR2); sigaddset(&set, SIGINT); sigaddset(&set, SIGHUP); pthread_sigmask(SIG_BLOCK, &set, NULL); } static int SignalHandler(sd_event_source * s, const signalfd_siginfo * si, void *cxt) { switch (sd_event_source_get_signal(s)) { case SIGTERM: case SIGINT: quit = 1; sd_event_exit((sd_event *) cxt, 0); break; case SIGHUP: kill(getppid(), SIGHUP); break; } return 1; } static void InstallSignalHandlers(sd_event * event) { int r1 = sd_event_add_signal(event, NULL, SIGTERM, SignalHandler, event); int r2 = sd_event_add_signal(event, NULL, SIGHUP, SignalHandler, event); int r3 = sd_event_add_signal(event, NULL, SIGUSR2, SignalHandler, event); int r4 = sd_event_add_signal(event, NULL, SIGINT, SignalHandler, event); if (r1 < 0 || r2 < 0 || r3 < 0 || r4 < 0) { abort(); } } static int Pinger(sd_event_source * s, uint64_t usec, void *cxt) { Watchdog *watchdog = (Watchdog *) cxt; watchdog->Ping(); sd_event_now(sd_event_source_get_event(s), CLOCK_REALTIME, &usec); usec += watchdog->GetPingInterval() * 1000000; sd_event_add_time(sd_event_source_get_event(s), &s, CLOCK_REALTIME, usec, 1, Pinger, (void *)cxt); return 0; } static bool InstallPinger(sd_event * e, int time, Watchdog * w) { sd_event_source *s = NULL; uint64_t usec = 0; w->SetPingInterval(time); sd_event_now(e, CLOCK_REALTIME, &usec); sd_event_add_time(e, &s, CLOCK_REALTIME, usec, 1, Pinger, (void *)w); return true; } static int ServiceMain(int argc, char **argv, int fd, bool restarted) { cfgoptions options; Watchdog watchdog; cfgoptions *tmp = &options; Watchdog *tmp2 = &watchdog; Pidfile pidfile; struct dbusinfo temp = {.config = &tmp,.wdt = &tmp2}; temp.fd = fd; temp.miniMode = false; if (MyStrerrorInit() == false) { std::perror("Unable to create a new locale object"); return EXIT_FAILURE; } int ret = ParseCommandLine(&argc, argv, &options); if (ret < 0) { return EXIT_FAILURE; } else if (ret != 0) { return EXIT_SUCCESS; } if (strcasecmp(GetExeName(), "wd_identify") == 0 || strcasecmp(GetExeName(), "wd_identify.sh") == 0) { options.options |= IDENTIFY; } if (ReadConfigurationFile(&options) < 0) { return EXIT_FAILURE; } if (IsDaemon(&options) == true) { Daemonize(&options); pidfile.Open(options.pidfileName); pidfile.Write(getppid()); } if (options.options & IDENTIFY) { watchdog.Open(options.devicepath); ret = Identify(watchdog.GetRawTimeout(), (const char *)watchdog.GetIdentity(), options.devicepath, options.options & VERBOSE); watchdog.Close(); return ret; } if (PingInit(&options) < 0) { return EXIT_FAILURE; } if (restarted) { Logmsg(LOG_INFO,"restarting service (%s)", PACKAGE_VERSION); } else { Logmsg(LOG_INFO, "starting service (%s)", PACKAGE_VERSION); } PrintConfiguration(&options); if (ExecuteRepairScriptsPreFork(&processes, &options) == false) { Logmsg(LOG_ERR, "ExecuteRepairScriptsPreFork failed"); FatalError(&options); } sd_event *event = NULL; sd_event_default(&event); BlockSignals(); InstallSignalHandlers(event); if (StartHelperThreads(&options) != 0) { FatalError(&options); } pthread_t dbusThread = {0}; if (!(options.options & NOACTION)) { errno = 0; ret = watchdog.Open(options.devicepath); if (errno == EBUSY && ret < 0) { Logmsg(LOG_ERR, "Unable to open watchdog device"); return EXIT_FAILURE; } else if (ret <= -1) { LoadKernelModule(); Logmsg(LOG_INFO, "Trying to load software watchdog timer..."); ret = watchdog.Open(options.devicepath); if (ret == 0) { Logmsg(LOG_INFO, "Successfully loaded watchdog device"); } } if (ret <= -1) { FatalError(&options); } if (watchdog.ConfigureWatchdogTimeout(options.watchdogTimeout) < 0 && options.watchdogTimeout != -1) { Logmsg(LOG_ERR, "unable to set watchdog device timeout\n"); Logmsg(LOG_ERR, "program exiting\n"); EndDaemon(&options, false); watchdog.Close(); return EXIT_FAILURE; } watchdog.PrintWdtInfo(); if (options.sleeptime == -1) { options.sleeptime = watchdog.GetOptimalPingInterval(); Logmsg(LOG_INFO, "ping interval autodetect: %li", options.sleeptime); } if (options.watchdogTimeout != -1 && watchdog.CheckWatchdogTimeout(options.sleeptime) == true) { Logmsg(LOG_ERR, "WDT timeout is less than or equal watchdog daemon ping interval"); Logmsg(LOG_ERR, "Using this interval may result in spurious reboots"); if (!(options.options & FORCE)) { watchdog.Close(); Logmsg(LOG_WARNING, "use the -f option to force this configuration"); return EXIT_FAILURE; } } WriteBootStatus(watchdog.GetStatus(), "/run/watchdogd.status", options.sleeptime, watchdog.GetRawTimeout()); static struct identinfo i; strncpy(i.name, (char *)watchdog.GetIdentity(), sizeof(i.name) - 1); i.timeout = watchdog.GetRawTimeout(); strncpy(i.daemonVersion, PACKAGE_VERSION, sizeof(i.daemonVersion) - 1); strncpy(i.deviceName, options.devicepath, sizeof(i.deviceName) - 1); i.flags = watchdog.GetStatus(); i.firmwareVersion = watchdog.GetFirmwareVersion(); CreateDetachedThread(IdentityThread, &i); pthread_attr_t attr = {0}; pthread_attr_setstacksize(&attr, PTHREAD_STACK_MIN*2); pthread_attr_setguardsize(&attr, 0); pthread_create(&dbusThread, &attr, DbusHelper, &temp); InstallPinger(event, options.sleeptime, &watchdog); write(fd, "", sizeof(char)); } else { temp.miniMode = true; pthread_attr_t attr = {0}; pthread_attr_setstacksize(&attr, PTHREAD_STACK_MIN*2); pthread_attr_setguardsize(&attr, 0); pthread_create(&dbusThread, &attr, DbusHelper, &temp); write(fd, "", sizeof(char)); } if (SetupAuxManagerThread(&options) < 0) { FatalError(&options); } if (PlatformInit() != true) { FatalError(&options); } sd_event_loop(event); if (IsDaemon(&options) == true) { pidfile.Delete(); } if (stop == 1) { while (true) { if (stopPing == 1) { if (DISARM_WATCHDOG_BEFORE_REBOOT) { watchdog.Close(); } } else { watchdog.Ping(); } sleep(1); } } pthread_cancel(dbusThread); pthread_join(dbusThread, NULL); watchdog.Close(); unlink("/run/watchdogd.status"); if (EndDaemon(&options, false) < 0) { return EXIT_FAILURE; } return EXIT_SUCCESS; } static void ClosePipe(int *fd) { close(*fd); close(fd[1]); } int main(int argc, char **argv) { opterr = 0; ParseCommandLine(&argc, argv, NULL, true); opterr = 1; int com[2] = {-1}; pipe2(com, O_CLOEXEC); int com1[2] = {-1}; pipe2(com1, O_CLOEXEC); int sock[2] = {-1}; pid_t pid = fork(); pid_t dbusPid = 0; if (pid == 0) { setsid(); socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, sock); pid = fork(); if (pid != 0) { sigset_t set; sigemptyset(&set); sigaddset(&set, SIGHUP); pthread_sigmask(SIG_BLOCK, &set, nullptr); close(sock[1]); ClosePipe(com); ClosePipe(com1); CreateDetachedThread(DbusApiInit, &sock); close(0);close(1);close(2); waitpid(pid, NULL, 0); quick_exit(0); } dbusPid = getppid(); goto daemon; } else { sigset_t mask; sigemptyset(&mask); sigaddset(&mask, SIGTERM); sigaddset(&mask, SIGINT); sigaddset(&mask, SIGHUP); sigaddset(&mask, SIGUSR1); pthread_sigmask(SIG_BLOCK, &mask, NULL); pid_t x = getpid(); close(com1[0]); write(com1[1], &x, sizeof(pid_t)); close(com1[1]); close(com[1]); read(com[0], &pid, sizeof(pid_t)); int sfd = signalfd(-1, &mask, SFD_CLOEXEC); while (true) { struct signalfd_siginfo si = {0}; read (sfd, &si, sizeof(si)); switch (si.ssi_signo) { case SIGTERM: case SIGINT: kill(pid, SIGTERM); break; case SIGHUP: kill(pid, SIGHUP); break; case SIGUSR1: quick_exit(0); break; } } } daemon: pid_t shell = 0; close(com1[1]); close(com[0]); read(com1[0], &shell, sizeof(pid_t)); close(com1[0]); close(sock[0]); sigset_t mask; bool restarted = false; char name[64] = {0}; sd_bus *bus = NULL; sd_bus_message *m = NULL; sd_bus_error error = {0}; int fildes[2] = {0}; sigemptyset(&mask); sigaddset(&mask, SIGTERM); sigaddset(&mask, SIGINT); sigaddset(&mask, SIGHUP); sigaddset(&mask, SIGCHLD); sigaddset(&mask, SIGUSR1); sigprocmask(SIG_BLOCK, &mask, NULL); int sfd = signalfd (-1, &mask, SFD_CLOEXEC); pid = getpid(); write(com[1], &pid, sizeof(pid)); close(com[1]); init: kill(dbusPid, SIGHUP); waitpid(-1, NULL, WNOHANG); pipe(fildes); pid = fork(); if (pid == 0) { ClosePipe(com); close(sfd); ResetSignalHandlers(64); sigfillset(&mask); sigprocmask(SIG_UNBLOCK, &mask, NULL); close(fildes[1]); read(fildes[0], fildes+1, sizeof(int)); close(fildes[0]); _Exit(ServiceMain(argc, argv, sock[1], restarted)); } sd_bus_open_system(&bus); sprintf(name, "watchdogd.%i.scope", pid); sd_bus_message_new_method_call(bus, &m, "org.freedesktop.systemd1", "/org/freedesktop/systemd1", "org.freedesktop.systemd1.Manager", "StartTransientUnit"); sd_bus_message_append(m, "ss", name, "fail"); sd_bus_message_open_container(m, 'a', "(sv)"); sd_bus_message_append(m, "(sv)", "Description", "s", "This scope contains the main process and any repair scripts."); sd_bus_message_append(m, "(sv)", "KillSignal", "i", SIGTERM); sd_bus_message_append(m, "(sv)", "PIDs", "au", 1, (uint32_t) pid); sd_bus_message_close_container(m); sd_bus_message_append(m, "a(sa(sv))", 0); sd_bus_message * reply; sd_bus_call(bus, m, 0, &error, &reply); sd_bus_flush_close_unref(bus); close(fildes[0]); close(fildes[1]); sd_notifyf(0, "READY=1\n" "MAINPID=%lu", (unsigned long)getpid()); while (true) { struct signalfd_siginfo si = {0}; read (sfd, &si, sizeof(si)); switch (si.ssi_signo) { case SIGUSR1: if (getppid() != 1) { kill(shell, SIGUSR1); } si.ssi_signo = 0; break; case SIGHUP: sd_bus_open_system(&bus); sd_bus_call_method(bus, "org.freedesktop.systemd1", "/org/freedesktop/systemd1", "org.freedesktop.systemd1.Manager", "StopUnit", &error, NULL, "ss", name, "ignore-dependencies"); sd_bus_flush_close_unref(bus); restarted = true; read(sfd, &si, sizeof(si)); if (si.ssi_signo != SIGCHLD) { kill(shell, si.ssi_signo); } si.ssi_signo = 0; goto init; break; case SIGINT: case SIGTERM: case SIGCHLD: sd_bus_open_system(&bus); sd_bus_call_method(bus, "org.freedesktop.systemd1", "/org/freedesktop/systemd1", "org.freedesktop.systemd1.Manager", "StopUnit", &error, NULL, "ss", name, "ignore-dependencies"); sd_bus_flush_close_unref(bus); kill(shell, SIGUSR1); si.ssi_signo = 0; _Exit(si.ssi_status); break; } } } <|start_filename|>src/futex.cpp<|end_filename|> /* * Copyright 2016-2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <atomic> using namespace std; #include <linux/futex.h> #include <unistd.h> #include <sys/syscall.h> long FutexWait(atomic_int *addr, int val) { return syscall(SYS_futex, addr, FUTEX_WAIT, val, NULL, NULL, 0); } long FutexWake(atomic_int *addr) { return syscall(SYS_futex, addr, FUTEX_WAKE, 1, NULL, NULL, 0); } <|start_filename|>src/exe.hpp<|end_filename|> /* * Copyright 2013-2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ #ifndef EXE_H #define EXE_H int Spawn(int timeout, struct cfgoptions *const config, const char *file, const char *args, ...); int SpawnAttr(spawnattr_t *spawnattr, const char *file, const char *args, ...); #endif <|start_filename|>src/init.hpp<|end_filename|> /* * Copyright 2013-2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ #if !defined(INIT_H) #define INIT_H int MakeLogDir(struct cfgoptions *const s); int SetSchedulerPolicy(int priority); int CheckPriority(int priority); int InitializePosixMemlock(void); int Usage(void); int PrintVersionString(void); int ParseCommandLine(int *argc, char **argv, struct cfgoptions *s, bool earlyParse = false); bool SetDefaultConfig(struct cfgoptions *const options); int GetDefaultPriority(void); int PingInit(struct cfgoptions *const cfg); #endif <|start_filename|>src/pidfile.cpp<|end_filename|> /* * Copyright 2014-2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ #include "pidfile.hpp" #include "sub.hpp" #include "logutils.hpp" int Pidfile::Write(pid_t pid) { if (dprintf(ret, "%d\n", pid) < 0) { if (name != NULL) { fprintf(stderr, "watchdogd: unable to write pid to %s: %s\n", name, strerror(errno)); } else { fprintf(stderr, "watchdogd: unable to write pid to %i: %s\n", ret, strerror(errno)); } return -1; } fsync(ret); return 0; } int Pidfile::Open(const char *const path) { name = path; mode_t oumask = umask(0027); ret = open(path, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0644); if (ret < 0) { fprintf(stderr, "watchdogd: open failed: %s\n", strerror(errno)); if (errno == EEXIST) { ret = open(path, O_RDONLY | O_CLOEXEC); if (ret < 0) { umask(oumask); return ret; } char buf[64] = { 0 }; if (pread(ret, buf, sizeof(buf), 0) == -1) { close(ret); umask(oumask); return -1; } errno = 0; pid_t pid = (pid_t) strtol(buf, (char **)NULL, 10); if (errno != 0) { umask(oumask); return -1; } fprintf(stderr, "watchdogd: checking if the pid is valid\n"); if (kill(pid, 0) != 0 && errno == ESRCH) { close(ret); if (remove(path) < 0) { umask(oumask); return -1; } else { ret = open(path, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0644); if (ret < 0) { fprintf(stderr, "watchdogd: open failed: %s\n", strerror(errno)); umask(oumask); return ret; } else { fprintf(stdout, "successfully opened pid file\n"); } } } } } umask(oumask); return ret; } int Pidfile::Delete() { if (name == NULL) { return -1; } if (ret == 0) { return 0; } UnlockFile(ret, getpid()); close(ret); if (remove(name) < 0) { Logmsg(LOG_ERR, "remove failed: %s", strerror(errno)); return -2; } return 0; } <|start_filename|>src/futex.hpp<|end_filename|> #ifndef FUTEX_H #define FUTEX_H long FutexWait(std::atomic_int *, int); long FutexWake(std::atomic_int *); #endif <|start_filename|>src/logutils.cpp<|end_filename|> /* * Copyright 2013-2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ #include "watchdogd.hpp" #include "sub.hpp" #include "logutils.hpp" #include "linux.hpp" #define KNRM "\x1B[0m" #define KRED "\x1B[31m" #define KGRN "\x1B[32m" #define KYEL "\x1B[33m" #define KBLU "\x1B[34m" #define KMAG "\x1B[35m" #define KCYN "\x1B[36m" #define KWHT "\x1B[37m" #define KRESET "\x1B[0m" #define READ 0 #define WRITE 1 static sig_atomic_t logTarget = INVALID_LOG_TARGET; static int logFile = -1; static pthread_mutex_t mutex; static sig_atomic_t applesquePriority = 0; static sig_atomic_t autoUpperCase = 0; static sig_atomic_t autoPeriod = 1; static unsigned int logMask = 0xff; static locale_t locale; static bool noLog = false; static int ipri[] = { LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO, LOG_DEBUG }; static pthread_once_t initMutex = PTHREAD_ONCE_INIT; static void MutexInit(void) { pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED); pthread_mutex_init(&mutex, &attr); pthread_mutexattr_destroy(&attr); } enum { SHORT, LONG }; static const char * const spri[][2] = { {"LOG_EMERG", "LOG_Emergency"}, {"LOG_ALERT", ""}, {"LOG_CRIT", "LOG_Critical"}, {"LOG_ERR", "LOG_Error"}, {"LOG_WARNING", ""}, {"LOG_NOTICE", ""}, {"LOG_INFO", ""}, {"LOG_DEBUG", ""} }; struct message { char message[2048]; int pri; }; static_assert(PIPE_BUF > sizeof(struct message), "message struct cannot be witten atomically on this platform"); static int SystemdSyslog(int priority, const char *format, va_list ap) { static __thread char buf[2048] = {"MESSAGE="}; static __thread char p[64] = { '\0' }; struct iovec iov[3] = { 0 }; portable_snprintf(p, sizeof(p) - 1, "PRIORITY=%i", priority); portable_vsnprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), format, ap); iov[0].iov_base = buf; iov[0].iov_len = strlen(buf); iov[1].iov_base = p; iov[1].iov_len = strlen(p); iov[2].iov_base = (void *)"SYSLOG_IDENTIFIER=watchdogd"; iov[2].iov_len = strlen("SYSLOG_IDENTIFIER=watchdogd"); return sd_journal_sendv(iov, 3); } static bool IsTty(void) { if (logTarget != STANDARD_ERROR) { return false; } if (isatty(fileno(stderr)) == 0) { return false; } return true; } static char const * SetTextColor(int priority) { if (IsTty() == false) { return ""; } switch (priority) { case LOG_EMERG: return KRED; break; case LOG_ALERT: return KRED; break; case LOG_CRIT: return KRED; break; case LOG_ERR: return KRED; break; case LOG_WARNING: return KRED; break; case LOG_NOTICE: return ""; break; case LOG_INFO: return ""; break; case LOG_DEBUG: return ""; break; default: assert(false); } return ""; } static void CloseOldTarget(sig_atomic_t oldTarget) { if (oldTarget == INVALID_LOG_TARGET) { return; } if (oldTarget == SYSTEM_LOG) { closelog(); return; } if (oldTarget == STANDARD_ERROR) { return; } if (oldTarget == FILE_NEW || oldTarget == FILE_APPEND) { if (logFile != -1) { close(logFile); logFile = -1; return; } else { return; } } } void SetAutoPeriod(bool x) { if (x) { autoPeriod = 1; } else { autoPeriod = 0; } } void SetAutoUpperCase(bool x) { if (x) { autoUpperCase = 1; } else { autoUpperCase = 0; } } void HashTagPriority(bool x) { if (x) { applesquePriority = 1; } else { applesquePriority = 0; } } static void SetLogMask(unsigned int mask) { pthread_once(&initMutex, MutexInit); pthread_mutex_lock(&mutex); setlogmask(mask); logMask = setlogmask(mask);; pthread_mutex_unlock(&mutex); } void SetLogTarget(sig_atomic_t target, ...) { pthread_once(&initMutex, MutexInit); pthread_mutex_lock(&mutex); if (target == STANDARD_ERROR) { CloseOldTarget(logTarget); logTarget = STANDARD_ERROR; } if (target == SYSTEM_LOG) { CloseOldTarget(logTarget); logTarget = SYSTEM_LOG; } if (target == FILE_NEW || target == FILE_APPEND) { closelog(); va_list ap; va_start(ap, target); const char *fileName = va_arg(ap, const char *); assert(fileName != NULL); if (target == FILE_NEW) { logFile = open(fileName, O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR); if (logFile == -1) { if (logTarget == SYSTEM_LOG) { syslog(LOG_ALERT, "%m"); } else { fprintf(stderr, "%s\n", MyStrerror(errno)); } } else { CloseOldTarget(logTarget); logTarget = FILE_NEW; } } else if (target == FILE_APPEND) { logFile = open(fileName, O_WRONLY|O_APPEND|O_CREAT, S_IRUSR|S_IWUSR); if (logFile == -1) { if (logTarget == SYSTEM_LOG) { syslog(LOG_ALERT, "%m"); } else { fprintf(stderr, "%s\n", MyStrerror(errno)); } } else { CloseOldTarget(logTarget); logTarget = FILE_APPEND; } } else { assert(false); } va_end(ap); } pthread_mutex_unlock(&mutex); } bool LogUpToInt(long pri, bool cmdln) { if (pri < 0 || pri > 7) { if (cmdln) { fprintf(stderr, "illegal command line option argument for -l/--loglevel\n"); return false; } fprintf(stderr, "illegal value for configuration file entry named" " \"log-up-to\": %li\n", pri); return false; } SetLogMask(LOG_UPTO(ipri[pri])); return true; } static bool LogUpToString(const char *const str, bool cmdln) { char *tmp = strdup(str); if (tmp == NULL) { return false; } for (int i = 0; tmp[i] != '\0'; i += 1) { if (tmp[i] == '-' || ispunct(tmp[i])) { tmp[i] = '_'; } tmp[i] = toupper(tmp[i]); } if (strstr(tmp, "LOG_") == NULL) { char *buf = NULL; Wasprintf(&buf, "%s%s", "LOG_", tmp); free(tmp); tmp = buf; } bool matched = false; if (strcasecmp(tmp, "log_none") == 0) { noLog = true; free(tmp); return true; } for (size_t i = 0; i < ARRAY_SIZE(spri); i += 1) { if (strcasecmp(tmp, spri[i][SHORT]) == 0) { SetLogMask(LOG_UPTO(ipri[i])); matched = true; } if (strcasecmp(tmp, spri[i][LONG]) == 0) { SetLogMask(LOG_UPTO(ipri[i])); matched = true; } } if (matched == false && cmdln == false) { fprintf(stderr, "illegal value for configuration file entry named" " \"log-up-to\": %s\n", str); } else if (matched == false) { fprintf(stderr, "illegal command line option argument for [ -l | --loglevel ]\n"); } free(tmp); return matched; } bool LogUpTo(const char *const str, bool cmdln) { assert(str != NULL); if (str == NULL) { return false; } errno = 0; long logPri = ConvertStringToInt(str); if (errno != 0) { return LogUpToString(str, cmdln); } return LogUpToInt(logPri, cmdln); } void __attribute__ ((format (printf, 2, 3))) Logmsg(int priority, const char *const fmt, ...) { assert(fmt != NULL); if ((LOG_MASK(LOG_PRI(priority)) & logMask) == 0 || noLog == true) { return; } va_list args; static __thread char buf[2048]; buf[0] = 0; if ((logTarget == STANDARD_ERROR || logTarget == FILE_APPEND || logTarget == FILE_NEW) && applesquePriority == 0) { strcat(buf, SetTextColor(priority)); switch (priority) { case LOG_EMERG: strncpy(buf+strlen(SetTextColor(priority)), "<0>", sizeof(buf) - strlen(buf)); break; case LOG_ALERT: strncpy(buf+strlen(SetTextColor(priority)), "<1>", sizeof(buf) - strlen(buf)); break; case LOG_CRIT: strncpy(buf+strlen(SetTextColor(priority)), "<2>", sizeof(buf) - strlen(buf)); break; case LOG_ERR: strncpy(buf+strlen(SetTextColor(priority)), "<3>", sizeof(buf) - strlen(buf)); break; case LOG_WARNING: strncpy(buf+strlen(SetTextColor(priority)), "<4>", sizeof(buf) - strlen(buf)); break; case LOG_NOTICE: strncpy(buf+strlen(SetTextColor(priority)), "<5>", sizeof(buf) - strlen(buf)); break; case LOG_INFO: strncpy(buf+strlen(SetTextColor(priority)), "<6>", sizeof(buf) - strlen(buf)); break; case LOG_DEBUG: strncpy(buf+strlen(SetTextColor(priority)), "<7>", sizeof(buf) - strlen(buf)); break; default: assert(false); } va_start(args, fmt); portable_vsnprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), fmt, args); va_end(args); assert(buf[sizeof(buf) - 1] == '\0'); } else if (logTarget != SYSTEM_LOG && applesquePriority == 1) { va_start(args, fmt); portable_vsnprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), fmt, args); va_end(args); if (autoPeriod == 1) { if (buf[strlen(buf) - 1] != '.') { strncat(buf, ".", sizeof(buf) - strlen(buf) - 1); } } if (autoUpperCase == 1) { if (strstr(buf, "=") == NULL) { if (islower(buf[0])) { buf[0] = toupper(buf[0]); } } } switch (priority) { case LOG_EMERG: strncat(buf, " #System #Panic", sizeof(buf) - strlen(buf) - 1); break; case LOG_ALERT: strncat(buf, " #System #Attention", sizeof(buf) - strlen(buf) - 1); break; case LOG_CRIT: strncat(buf, " #System #Critical", sizeof(buf) - strlen(buf) - 1); break; case LOG_ERR: strncat(buf, " #System #Error", sizeof(buf) - strlen(buf) - 1); break; case LOG_WARNING: strncat(buf, " #System #Warning", sizeof(buf) - strlen(buf) - 1); break; case LOG_NOTICE: strncat(buf, " #System #Notice", sizeof(buf) - strlen(buf) - 1); break; case LOG_INFO: strncat(buf, " #System #Comment", sizeof(buf) - strlen(buf) - 1); break; case LOG_DEBUG: strncat(buf, " #System #Developer", sizeof(buf) - strlen(buf) - 1); break; default: assert(false); } } if (logTarget == STANDARD_ERROR || logTarget == FILE_APPEND || logTarget == FILE_NEW) { assert(buf[sizeof(buf) - 1] == '\0'); const char * format; if (strstr(buf, "\n") != NULL && strcmp(strstr(buf, "\n") + 1, "\0") == 0) { format = "%s"; } else { format = "%s\n"; } if (logTarget == STANDARD_ERROR) { int len = portable_snprintf(NULL, 0, format, buf) + 1; char t[len+strlen(KRESET)]; portable_snprintf(t, sizeof(t), format, buf); strncat(t, KRESET, sizeof(t) - strlen(t) - 1); write(STDERR_FILENO, t, strlen(t)); } else { int len = portable_snprintf(NULL, 0, format, buf) + 1; char t[len]; portable_snprintf(t, sizeof(t), format, buf); write(logFile, t, strlen(t)); } } if (logTarget == SYSTEM_LOG) { if (true) { va_start(args, fmt); SystemdSyslog(priority, fmt, args); //async-signal safe va_end(args); return; } } } bool MyStrerrorInit(void) { locale = newlocale(LC_CTYPE_MASK|LC_NUMERIC_MASK|LC_TIME_MASK| LC_COLLATE_MASK|LC_MONETARY_MASK|LC_MESSAGES_MASK, "",(locale_t)0); if (locale == (locale_t)0) { return false; } return true; } void FreeLocale(void) { freelocale(locale); } char * MyStrerror(int error) { return strerror_l(error, locale); } <|start_filename|>src/network_tester.cpp<|end_filename|> /* * Copyright 2013-2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ #include "watchdogd.hpp" #include "linux.hpp" #include <linux/if_link.h> struct NetworkDevices { struct list head; }; struct NetMonNode { struct list node; unsigned long long rx; char *name; }; typedef struct NetMonNode NetMonNode; static struct NetworkDevices networkDevices; static bool NetMonIsValidNetworkInterface(const char *name) { struct ifaddrs *ifaddr; getifaddrs(&ifaddr); for (struct ifaddrs *ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) { if (ifa->ifa_addr->sa_family != AF_PACKET) { continue; } if (strcmp(name, ifa->ifa_name) == 0) { freeifaddrs(ifaddr); return true; } } freeifaddrs(ifaddr); return false; } bool NetMonCheckNetworkInterfaces(char **name) { NetMonNode *c = NULL; NetMonNode *next = NULL; struct ifaddrs *ifaddr; *name = NULL; getifaddrs(&ifaddr); list_for_each_entry(c, next, &networkDevices.head, node) { for (struct ifaddrs *ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) { if (ifa->ifa_addr->sa_family != AF_PACKET) { continue; } if (strcmp(c->name, ifa->ifa_name) == 0) { assert(ifa->ifa_data != NULL); struct rtnl_link_stats *stats = (struct rtnl_link_stats*)ifa->ifa_data; if (stats->rx_bytes == c->rx) { *name = c->name; freeifaddrs(ifaddr); return false; } c->rx = stats->rx_bytes; break; } } } freeifaddrs(ifaddr); return true; } bool NetMonAdd(const char *name) { if (NetMonIsValidNetworkInterface(name) == false) { return false; } struct NetMonNode *node = (struct NetMonNode*)calloc(1, sizeof(struct NetMonNode)); if (node == NULL) { return false; } node->name = strdup(name); node->rx = -1; list_add(&node->node, &networkDevices.head); return true; } bool NetMonInit(void) { list_init(&networkDevices.head); return true; } <|start_filename|>src/threadpool.cpp<|end_filename|> /* * Copyright 2016-2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ #include "watchdogd.hpp" #include <semaphore.h> constexpr size_t MAX_WORKERS = 16; static std::atomic_bool canceled = {false}; extern unsigned long numberOfRepairScripts; struct threadpool { sem_t sem; void *(*func)(void*); union { void * arg; int active; }; }; static struct threadpool threads[MAX_WORKERS] = {0}; static void *Worker(void *arg) { struct threadpool * t = (struct threadpool *)arg; while (true) { sem_wait(&t->sem); __sync_synchronize(); t->func(t->arg); __atomic_store_n(&t->active, 0, __ATOMIC_SEQ_CST); __sync_synchronize(); } return NULL; } bool ThreadPoolNew(int numberOfThreads = numberOfRepairScripts) { pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setguardsize(&attr, 0); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); pthread_attr_setstacksize(&attr, PTHREAD_STACK_MIN*2); pthread_t thread = {0}; if (numberOfThreads > MAX_WORKERS) numberOfThreads = MAX_WORKERS; for (int i = 0; i < numberOfThreads; i++) { sem_init(&threads[i].sem, 0, 0); pthread_create(&thread, &attr, Worker, &threads[i]); } pthread_attr_destroy(&attr); return true; } bool ThreadPoolAddTask(void *(*entry)(void*), void * arg, bool retry) { if (entry == NULL) { return false; } if (canceled == true) { return false; } do { for (size_t i = 0; i < numberOfRepairScripts; i++) { if (__sync_val_compare_and_swap(&threads[i].active, 0, 1) == 0) { threads[i].func = entry; threads[i].arg = arg; __sync_synchronize(); sem_post(&threads[i].sem); return true; } } } while (retry); return false; } <|start_filename|>src/daemon.cpp<|end_filename|> /* * Copyright 2013-2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ #include "watchdogd.hpp" #include "sub.hpp" #include "init.hpp" #include "pidfile.hpp" #include "daemon.hpp" #include "logutils.hpp" int Daemonize(struct cfgoptions *const s) { assert(s != NULL); if (s == NULL) { return -1; } if (IsDaemon(s) == 0) { //shall we daemonize? return 0; } SetLogTarget(SYSTEM_LOG); kill(getppid(), SIGUSR1); return 0; } <|start_filename|>src/configfile.hpp<|end_filename|> #ifndef CONFIGFILE_H #define CONFIGFILE_H int ReadConfigurationFile(struct cfgoptions *const cfg); void NoWhitespace(char *); #endif <|start_filename|>src/sub.cpp<|end_filename|> /* * Copyright 2013-2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * This file contains functions that are used be more than one module. */ #include "watchdogd.hpp" #include "sub.hpp" #include "testdir.hpp" #include "logutils.hpp" int IsDaemon(struct cfgoptions *const s) { if (s->options & DAEMONIZE) return true; return false; } int LockFile(int fd, pid_t pid) { struct flock fl; fl.l_type = F_WRLCK; fl.l_whence = SEEK_SET; fl.l_start = 0; fl.l_len = 0; fl.l_pid = pid; return fcntl(fd, F_SETLKW, &fl); } int UnlockFile(int fd, pid_t pid) { struct flock fl; fl.l_type = F_UNLCK; fl.l_whence = SEEK_SET; fl.l_start = 0; fl.l_len = 0; fl.l_pid = pid; return fcntl(fd, F_SETLKW, &fl); } int Wasprintf(char **ret, const char *format, ...) { //http://stackoverflow.com/questions/4899221/substitute-or-workaround-for-asprintf-on-aix va_list ap; *ret = NULL; va_start(ap, format); int count = portable_vsnprintf(NULL, 0, format, ap); va_end(ap); if (count >= 0) { char *buffer = (char *)malloc((size_t) count + 1); if (buffer == NULL) return -1; va_start(ap, format); count = portable_vsnprintf(buffer, (size_t) count + 1, format, ap); va_end(ap); if (count < 0) { free(buffer); *ret = NULL; return count; } *ret = buffer; } return count; } int Wasnprintf(size_t *len, char **ret, const char *format, ...) { va_list ap; if (*len == 0) { *ret = NULL; } va_start(ap, format); int count = portable_vsnprintf(NULL, 0, format, ap); va_end(ap); if (count+1 < *len) { va_start(ap, format); count = portable_vsnprintf(*ret, (size_t) count + 1, format, ap); va_end(ap); return count; } else { free(*ret); } if (count >= 0) { char *buffer = (char *)malloc((size_t) count + 1); if (buffer == NULL) return -1; va_start(ap, format); count = portable_vsnprintf(buffer, (size_t) count + 1, format, ap); va_end(ap); if (count < 0) { free(buffer); *ret = NULL; *len = 0; return count; } *ret = buffer; *len = count; } return count; } int EndDaemon(struct cfgoptions *s, int keepalive) { if (s == NULL) return -1; extern volatile sig_atomic_t stop; stop = 1; if (s->options & ENABLEPING) { for (pingobj_iter_t * iter = ping_iterator_get(s->pingObj); iter != NULL; iter = ping_iterator_next(iter)) { free(ping_iterator_get_context(iter)); ping_iterator_set_context(iter, NULL); } for (int cnt = 0; cnt < config_setting_length(s->ipAddresses); cnt++) { const char *ipAddress = config_setting_get_string_elem(s->ipAddresses, cnt); if (ping_host_remove(s->pingObj, ipAddress) != 0) { fprintf(stderr, "watchdogd: %s\n", ping_get_error(s->pingObj)); ping_destroy(s->pingObj); return -1; } } ping_destroy(s->pingObj); } if (keepalive == 0) { FreeExeList(&processes); config_destroy(&s->cfg); Logmsg(LOG_INFO, "stopping watchdog daemon"); closelog(); munlockall(); FreeLocale(); return 0; } FreeExeList(&processes); Logmsg(LOG_INFO, "restarting system"); closelog(); SetLogTarget(STANDARD_ERROR); munlockall(); FreeLocale(); return 0; } void ResetSignalHandlers(size_t maxsigno) { if (maxsigno < 1) return; struct sigaction sa; sa.sa_handler = SIG_DFL; sa.sa_flags = 0; sigfillset(&sa.sa_mask); for (size_t i = 1; i < maxsigno; sigaction(i, &sa, NULL), i++) ; } void NormalizeTimespec(struct timespec *const tp) { assert(tp != NULL); while (tp->tv_nsec < 0) { if (tp->tv_sec == 0) { tp->tv_nsec = 0; return; } tp->tv_sec -= 1; tp->tv_nsec += 1000000000; } while (tp->tv_nsec >= 1000000000) { tp->tv_nsec -= 1000000000; tp->tv_sec++; } } long ConvertStringToInt(const char *const str) { if (str == NULL) { return -1; } char *endptr = NULL; long ret = strtol((str), &endptr, 10); if (*endptr != '\0') { if (errno == 0) { errno = ERANGE; } return -1; } return ret; } int IsExe(const char *pathname, bool returnfildes) { struct stat buffer; if (pathname == NULL) return -1; int fildes = open(pathname, O_RDONLY | O_CLOEXEC); if (fildes == -1) return -1; if (fstat(fildes, &buffer) != 0) { close(fildes); return -1; } if (S_ISREG(buffer.st_mode) == 0) { close(fildes); return -1; } if (!(buffer.st_mode & S_IXUSR)) { close(fildes); return -1; } if (!(buffer.st_mode & S_IRUSR)) { close(fildes); return -1; } if (returnfildes == true) //For use with fexecve return fildes; close(fildes); return 0; } int CreateDetachedThread(void *(*startFunction) (void *), void *const arg) { pthread_t thread; pthread_attr_t attr = {0}; if (arg == NULL) return -1; if (*startFunction == NULL) return -1; if (pthread_attr_init(&attr) != 0) return -1; size_t stackSize = 0; if (pthread_attr_getstacksize(&attr, &stackSize) == 0) { const size_t targetStackSize = 262144; if ((targetStackSize >= PTHREAD_STACK_MIN) && (stackSize > targetStackSize)) { if (pthread_attr_setstacksize(&attr, 1048576) != 0) { Logmsg(LOG_CRIT, "pthread_attr_setstacksize: %s\n", MyStrerror(errno)); } } } else { Logmsg(LOG_CRIT, "pthread_attr_getstacksize: %s\n", MyStrerror(errno)); } pthread_attr_setguardsize(&attr, 0); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); errno = 0; if (pthread_create(&thread, &attr, startFunction, arg) != 0) { int ret = -errno; pthread_attr_destroy(&attr); return ret; } pthread_attr_destroy(&attr); return 0; } void FatalError(struct cfgoptions *s) { assert(s != NULL); Logmsg(LOG_CRIT, "fatal error"); config_destroy(&s->cfg); abort(); } <|start_filename|>src/threads.cpp<|end_filename|> /* * Copyright 2013-2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ #define _DEFAULT_SOURCE #include "watchdogd.hpp" #include "logutils.hpp" #include <netdb.h> #include "sub.hpp" #include "errorlist.hpp" #include "threads.hpp" #include "testdir.hpp" #include "exe.hpp" #include "network_tester.hpp" #include "dbusapi.hpp" #include "linux.hpp" extern volatile sig_atomic_t stop; static pthread_mutex_t managerlock = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t workerupdate = PTHREAD_COND_INITIALIZER; static long pageSize = 0; static pthread_once_t getPageSize = PTHREAD_ONCE_INIT; static void GetPageSize(void) { pageSize = sysconf(_SC_PAGESIZE); } void *DbusHelper(void * arg) { struct dbusinfo * info = (struct dbusinfo *)arg; Watchdog * wdt = *info->wdt; cfgoptions * config = *info->config; unsigned int cmd = 0; long version = -1; char *identity = (char*)"EINVALID"; int timeout = 0; if (!info->miniMode) { version = wdt->GetFirmwareVersion(); identity = (char*)wdt->GetIdentity(); timeout = wdt->GetRawTimeout(); } while (stop == 0) { int ret = read(info->fd, &cmd, sizeof(unsigned int)); if (ret < 0 && errno != EINTR) { break; } int x = 0; pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &x); if (!info->miniMode) { switch (cmd) { case DBUSGETIMOUT: { write(info->fd, &timeout, sizeof(int)); }; break; case DBUSTIMELEFT: { int timeleft = wdt->GetTimeleft(); write(info->fd, &timeleft, sizeof(int)); }; break; case DBUSGETPATH: { write(info->fd, config->devicepath, strlen(config->devicepath)); }; break; case DBUSVERSION: { write(info->fd, &version, sizeof(version)); }; break; case DBUSGETNAME: { write(info->fd, identity, strlen((char *)identity)); }; break; case DBUSHUTDOWN: { Shutdown(9221996, config); }; break; } } else { switch (cmd) { case DBUSGETIMOUT: { write(info->fd, &timeout, sizeof(int)); }; break; case DBUSTIMELEFT: { int timeleft = 0; write(info->fd, &timeleft, sizeof(int)); }; break; case DBUSGETPATH: { write(info->fd, "ENIVALID", strlen("ENIVALID")); }; break; case DBUSVERSION: { write(info->fd, &version, sizeof(version)); }; break; case DBUSGETNAME: { write(info->fd, identity, strlen((char *)identity)); }; break; case DBUSHUTDOWN: { Shutdown(9221996, config); }; break; } } pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &x); } pthread_exit(NULL); } struct SystemdWatchdog { struct timespec tp; pid_t pid; }; static void *ServiceManagerKeepAliveNotification(void * arg) { struct SystemdWatchdog *tArg = (struct SystemdWatchdog*)arg; while (true) { int ret = sd_pid_notify(tArg->pid, 0, "WATCHDOG=1"); if (ret < 0) { Logmsg(LOG_ERR, "%s", MyStrerror(-ret)); } nanosleep(&tArg->tp, NULL); } return NULL; } static void * CheckNetworkInterfacesThread(void *arg) { struct cfgoptions *s = (struct cfgoptions *)arg; int retries = 0; while (true) { pthread_mutex_lock(&managerlock); char *ifname; if (NetMonCheckNetworkInterfaces(&ifname) == false) { retries += 1; if (retries > 12) { Logmsg(LOG_ERR, "network interface: %s is disconected", ifname); s->error |= NETWORKDOWN; } } else { if (s->error & NETWORKDOWN) { s->error &= !NETWORKDOWN; } retries = 0; } pthread_cond_wait(&workerupdate, &managerlock); pthread_mutex_unlock(&managerlock); } return NULL; } static void *Sync(void *arg) { for (;;) { pthread_mutex_lock(&managerlock); sync(); pthread_cond_wait(&workerupdate, &managerlock); pthread_mutex_unlock(&managerlock); } return NULL; } static void *Ping(void *arg) { struct cfgoptions *s = (struct cfgoptions *)arg; static char buf[NI_MAXHOST]; for (;;) { pthread_mutex_lock(&managerlock); if (ping_send(s->pingObj) > 0) { for (pingobj_iter_t * iter = ping_iterator_get(s->pingObj); iter != NULL; iter = ping_iterator_next(iter)) { double latency = -1.0; size_t len = sizeof(latency); ping_iterator_get_info(iter, PING_INFO_LATENCY, &latency, &len); len = NI_MAXHOST; ping_iterator_get_info(iter, PING_INFO_ADDRESS, &buf, &len); if (latency > 0.0) { void *cxt = ping_iterator_get_context(iter); if (cxt != NULL) { if (s->error & PINGFAILED) { s->error &= !PINGFAILED; } free(cxt); ping_iterator_set_context(iter, NULL); } continue; } else { Logmsg(LOG_ERR, "no response from ping (target: %s)", buf); } memset(buf, 0, NI_MAXHOST); if (ping_iterator_get_context(iter) == NULL) { ping_iterator_set_context(iter, calloc(1, sizeof (int ))); void *cxt = ping_iterator_get_context(iter); if (cxt == NULL) { Logmsg(LOG_ERR, "unable to allocate memory for ping context"); s->error |= PINGFAILED; } else { int *retries = (int *)cxt; *retries = *retries + 1; } } else { int *retries = (int *) ping_iterator_get_context(iter); if (*retries > 3) { //FIXME: This should really be a config value. free(ping_iterator_get_context (iter)); ping_iterator_set_context(iter, NULL); s->error |= PINGFAILED; } else { *retries += 1; } } } } else { Logmsg(LOG_ERR, "%s", ping_get_error(s->pingObj)); s->error |= PINGFAILED; } pthread_cond_wait(&workerupdate, &managerlock); pthread_mutex_unlock(&managerlock); } return NULL; } static void *LoadAvgThread(void *arg) { struct cfgoptions *s = (struct cfgoptions *)arg; double load[3] = { 0 }; for (;;) { pthread_mutex_lock(&managerlock); if (getloadavg(load, 3) == -1) { Logmsg(LOG_CRIT, "watchdogd: getloadavg() failed load monitoring disabled"); /*pthread_exit(NULL); */ } if (load[0] > s->maxLoadOne || load[1] > s->maxLoadFive || load[2] > s->maxLoadFifteen) { s->error |= LOADAVGTOOHIGH; } else { if (s->error & LOADAVGTOOHIGH) s->error &= !LOADAVGTOOHIGH; } pthread_cond_wait(&workerupdate, &managerlock); pthread_mutex_unlock(&managerlock); } return NULL; } static void *TestDirThread(void *arg) { //This thread is a bit different as we don't want to prevent the other //tests from running. struct cfgoptions *s = (struct cfgoptions *)arg; struct timespec tv = {0}; tv.tv_sec = 30; for (;;) { if (ExecuteRepairScripts() < 0) { s->error |= SCRIPTFAILED; } else { if (s->error & SCRIPTFAILED) { s->error &= !SCRIPTFAILED; } } tv.tv_sec = 30; syscall(SYS_pselect6, 0, NULL, NULL, NULL, &tv); if (stop == 1) { pthread_exit(NULL); } } return NULL; } static void *TestBinThread(void *arg) { //This thread is a bit different as we don't want to prevent the other //tests from running. struct cfgoptions *s = (struct cfgoptions *)arg; struct timespec rqtp; rqtp.tv_sec = 5; rqtp.tv_nsec = 5 * 1000; for (;;) { int ret = Spawn(s->testBinTimeout, s, s->testexepathname, s->testexepathname, "test", NULL); if (ret == 0) { s->testExeReturnValue = 0; } else { s->testExeReturnValue = ret; } nanosleep(&rqtp, NULL); if (stop == 1) { pthread_exit(NULL); } } return NULL; } static void *MinPagesThread(void *arg) { struct cfgoptions *s = (struct cfgoptions *)arg; struct sysinfo infostruct; pthread_once(&getPageSize, GetPageSize); if (pageSize < 0) { Logmsg(LOG_ERR, "%s", MyStrerror(errno)); return NULL; } for (;;) { pthread_mutex_lock(&managerlock); if (sysinfo(&infostruct) == -1) { /*sysinfo not in POSIX */ Logmsg(LOG_CRIT, "watchdogd: sysinfo() failed free page monitoring disabled"); /*pthread_exit(NULL); */ } unsigned long fpages = (infostruct.freeram + infostruct.freeswap) / 1024; if (fpages < s->minfreepages * (unsigned long)(pageSize / 1024)) { s->error |= OUTOFMEMORY; } else { if (s->error & OUTOFMEMORY) s->error &= !OUTOFMEMORY; } pthread_cond_wait(&workerupdate, &managerlock); pthread_mutex_unlock(&managerlock); } return NULL; } static void *TestMemoryAllocation(void *arg) { struct cfgoptions *config = (struct cfgoptions *)arg; if (config->allocatableMemory <= 0) { return NULL; } pthread_once(&getPageSize, GetPageSize); for (;;) { pthread_mutex_lock(&managerlock); void *buf = mmap(NULL, config->allocatableMemory * pageSize, PROT_READ | PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, 0 ,0); if (buf == MAP_FAILED) { Logmsg(LOG_ALERT, "mmap failed: %s", MyStrerror(errno)); config->error |= OUTOFMEMORY; } memset(buf, 0, (config->allocatableMemory * pageSize)); if (munmap(buf, config->allocatableMemory * pageSize) != 0) { Logmsg(LOG_CRIT, "munmap failed: %s", MyStrerror(errno)); assert(false); } pthread_cond_wait(&workerupdate, &managerlock); pthread_mutex_unlock(&managerlock); } return NULL; } static void *TestFork(void *arg) { assert(arg != NULL); struct cfgoptions *s = (struct cfgoptions *)arg; pid_t pid = 0; for (;;) { pid = fork(); if (pid == 0) { _Exit(EXIT_SUCCESS); } else if (pid < 0) { if (errno == EAGAIN) { s->error |= FORKFAILED; } } else { if (waitpid(pid, NULL, 0) != pid) { Logmsg(LOG_ERR, "watchdogd: %s", MyStrerror(errno)); Logmsg(LOG_ERR, "watchdogd: waitpid failed"); } } sleep(60); } return NULL; } static void *TestPidfileThread(void *arg) { assert(arg != NULL); struct cfgoptions *s = (struct cfgoptions *)arg; for (;;) { pthread_mutex_lock(&managerlock); for (int cnt = 0; cnt < config_setting_length(s->pidFiles); cnt++) { const char *pidFilePathName = NULL; pidFilePathName = config_setting_get_string_elem(s->pidFiles, cnt); if (pidFilePathName == NULL) { s->error |= UNKNOWNPIDFILERROR; break; } int fd = 0; time_t startTime = 0; if (time(&startTime) == (time_t) (-1)) { s->error |= UNKNOWNPIDFILERROR; break; } time_t currentTime = 0; do { struct timespec rqtp; rqtp.tv_sec = 0; rqtp.tv_nsec = 250; if (time(&currentTime) == (time_t) (-1)) { currentTime = 0; break; } fd = open(pidFilePathName, O_RDONLY | O_CLOEXEC); if (fd >= 0) { break; } nanosleep(&rqtp, NULL); } while (difftime(currentTime, startTime) <= s->retryLimit); if (fd < 0) { Logmsg(LOG_ERR, "cannot open %s: %s", pidFilePathName, MyStrerror(errno)); s->error |= PIDFILERROR; break; } struct stat buffer; if (fstat(fd, &buffer) != 0) { Logmsg(LOG_ERR, "%s: %s", pidFilePathName, MyStrerror(errno)); if (s->options & SOFTBOOT) { close(fd); s->error |= PIDFILERROR; break; } else { close(fd); continue; } } else { if (S_ISBLK(buffer.st_mode) == true || S_ISCHR(buffer.st_mode) == true || S_ISDIR(buffer.st_mode) == true || S_ISFIFO(buffer.st_mode) == true || S_ISSOCK(buffer.st_mode) == true || S_ISREG(buffer.st_mode) == false) { Logmsg(LOG_ERR, "invalid file type %s", pidFilePathName); close(fd); s->error |= PIDFILERROR; break; } } char buf[64] = { 0 }; if (pread(fd, buf, sizeof(buf), 0) == -1) { Logmsg(LOG_ERR, "unable to read pidfile %s: %s", pidFilePathName, MyStrerror(errno)); close(fd); s->error |= PIDFILERROR; break; } close(fd); errno = 0; pid_t pid = (pid_t) strtol(buf, (char **)NULL, 10); if (pid == 0) { Logmsg(LOG_ERR, "strtol failed: %s", MyStrerror(errno)); s->error |= UNKNOWNPIDFILERROR; break; } if (kill(pid, 0) == -1) { Logmsg(LOG_ERR, "unable to send null signal to pid %i: %s: %s", pid, pidFilePathName, MyStrerror(errno)); if (errno == ESRCH) { s->error |= PIDFILERROR; break; } if (s->options & SOFTBOOT) { s->error |= PIDFILERROR; break; } } } pthread_cond_wait(&workerupdate, &managerlock); pthread_mutex_unlock(&managerlock); } return NULL; } void *IdentityThread(void *arg) { struct identinfo *i = (struct identinfo*)arg; struct sockaddr_un address = {0}; address.sun_family = AF_UNIX; strncpy(address.sun_path, "\0watchdogd.wdt.identity", sizeof(address.sun_path)-1); int fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0); if (fd < 0) { return NULL; } if (bind(fd, (struct sockaddr*)&address, sizeof(address)) == -1) { close(fd); return NULL; } if (listen(fd, 2) == -1) { close(fd); return NULL; } while (true) { int conection = accept(fd, NULL, NULL); if (IsClientAdmin(conection) == false) { struct identinfo tmp = *i; tmp.flags = 0; tmp.firmwareVersion = 0; memset(tmp.deviceName, 7, sizeof(tmp.deviceName)); write(conection, &tmp, sizeof(tmp)); close(conection); continue; } write(conection, i, sizeof(*i)); close(conection); } return NULL; } static void *ManagerThread(void *arg) { /*This thread gets data from the non main threads and calls a function to take care of the problem */ cfgoptions *s = (cfgoptions *)arg; struct timespec rqtp; rqtp.tv_sec = 5; rqtp.tv_nsec = 5 * 1000; for (;;) { pthread_mutex_lock(&managerlock); pthread_cond_broadcast(&workerupdate); #if 0 if (s->temptoohigh == 1) { /*Shutdown(true) */ ; } #endif if (s->error & LOADAVGTOOHIGH) { Logmsg(LOG_ERR, "polled load average exceed configured load average limit"); if (Shutdown(WESYSOVERLOAD, s) < 0) { Logmsg(LOG_ERR, "watchdogd: Unable to shutdown system"); exit(EXIT_FAILURE); } } if (s->error & OUTOFMEMORY) { Logmsg(LOG_ERR, "less than configured free pages available"); if (Shutdown(WEOTHER, s) < 0) { Logmsg(LOG_ERR, "watchdogd: Unable to shutdown system"); exit(EXIT_FAILURE); } } if (s->error & FORKFAILED) { Logmsg(LOG_ERR, "process table test failed because fork failed"); if (Shutdown(WEOTHER, s) < 0) { Logmsg(LOG_ERR, "watchdogd: Unable to shutdown system"); exit(EXIT_FAILURE); } } if (s->error & SCRIPTFAILED) { Logmsg(LOG_ERR, "repair script failed"); if (Shutdown(WESCRIPT, s) < 0) { Logmsg(LOG_ERR, "watchdogd: Unable to shutdown system"); exit(EXIT_FAILURE); } } if (s->error & PIDFILERROR || s->error & UNKNOWNPIDFILERROR) { Logmsg(LOG_ERR, "pid file test failed"); if (Shutdown(WEPIDFILE, s) < 0) { Logmsg(LOG_ERR, "watchdogd: Unable to shutdown system"); exit(EXIT_FAILURE); } } if (s->testExeReturnValue > 0 || s->testExeReturnValue < 0) { Logmsg(LOG_ERR, "check executable failed"); if (Shutdown(s->testExeReturnValue, s) < 0) { Logmsg(LOG_ERR, "watchdogd: Unable to shutdown system"); exit(EXIT_FAILURE); } } if (s->error & PINGFAILED) { Logmsg(LOG_ERR, "ping test failed... rebooting system"); if (Shutdown(PINGFAILED, s) < 0) { Logmsg(LOG_ERR, "watchdogd: Unable to shutdown system"); exit(EXIT_FAILURE); } } if (s->error & NETWORKDOWN) { Logmsg(LOG_ERR, "network down... rebooting system"); if (Shutdown(PINGFAILED, s) < 0) { Logmsg(LOG_ERR, "watchdogd: Unable to shutdown system"); exit(EXIT_FAILURE); } } pthread_mutex_unlock(&managerlock); nanosleep(&rqtp, NULL); if (stop == 1) { break; } } return NULL; } int StartHelperThreads(struct cfgoptions *options) { if (StartServiceManagerKeepAliveNotification(NULL) < 0) { return -1; } if (SetupTestFork(options) < 0) { return -1; } if (SetupExeDir(options) < 0) { return -1; } if (options->testexepathname != NULL) { if (SetupTestBinThread(options) < 0) { return -1; } } if (options->maxLoadOne > 0) { if (SetupLoadAvgThread(options) < 0) { return -1; } } if (options->options & SYNC) { if (SetupSyncThread(options) < 0) { return -1; } } if (options->minfreepages != 0) { if (SetupMinPagesThread(options) < 0) { return -1; } } if (options->options & ENABLEPIDCHECKER) { if (StartPidFileTestThread(options) < 0) { return -1; } } if (options->options & ENABLEPING && StartPingThread(options) < 0) { return -1; } if (SetupTestMemoryAllocationThread(options) < 0) { return -1; } if (options->networkInterfaces != NULL) { StartCheckNetworkInterfacesThread(options); } return 0; } int SetupTestFork(void *arg) { if (CreateDetachedThread(TestFork, arg) < 0) return -1; return 0; } int SetupExeDir(void *arg) { extern struct repairscriptTranctions *rst; if (rst == NULL) return 0; if (CreateDetachedThread(TestDirThread, arg) < 0) return -1; return 0; } int SetupMinPagesThread(void *arg) { struct cfgoptions *s = (struct cfgoptions *)arg; assert(arg != NULL); if (s->minfreepages == 0) return 0; if (CreateDetachedThread(MinPagesThread, arg) < 0) return -1; return 0; } int SetupLoadAvgThread(void *arg) { assert(arg != NULL); if (CreateDetachedThread(LoadAvgThread, arg) < 0) return -1; return 0; } int SetupTestBinThread(void *arg) { assert(arg != NULL); if (CreateDetachedThread(TestBinThread, arg) < 0) return -1; return 0; } int SetupTestMemoryAllocationThread(void *arg) { assert(arg != NULL); if (CreateDetachedThread(TestMemoryAllocation, arg) < 0) { return -1; } return 0; } int SetupAuxManagerThread(void *arg) { assert(arg != NULL); if (CreateDetachedThread(ManagerThread, arg) < 0) return -1; return 0; } int SetupSyncThread(void *arg) { assert(arg != NULL); if (CreateDetachedThread(Sync, arg) < 0) return -1; return 0; } int StartPidFileTestThread(void *arg) { assert(arg != NULL); if (CreateDetachedThread(TestPidfileThread, arg) < 0) return -1; return 0; } int StartPingThread(void *arg) { assert(arg != NULL); if (CreateDetachedThread(Ping, arg) < 0) return -1; return 0; } int StartServiceManagerKeepAliveNotification(void *arg) { long long int usec = 0; pid_t pid = 0; int ret = SystemdWatchdogEnabled(&pid, &usec); if (ret == -1) { return 0; } usec *= 1000; usec /= 2; static struct SystemdWatchdog tArg; tArg.pid = pid; while (usec > 999999999) { tArg.tp.tv_sec += 1; usec -= 999999999; } tArg.tp.tv_nsec = (long)usec; if (CreateDetachedThread(ServiceManagerKeepAliveNotification, &tArg) < 0) { return -1; } return 0; } int StartCheckNetworkInterfacesThread(void *arg) { assert(arg != NULL); if (CreateDetachedThread(CheckNetworkInterfacesThread, arg) < 0) return -1; return 0; } <|start_filename|>src/identify.cpp<|end_filename|> /* * Copyright 2016-2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ #include "watchdogd.hpp" int Identify(long timeout, const char * identity, const char * deviceName, bool verbose) { struct sockaddr_un address = {0}; struct identinfo buf; int fd = -1; address.sun_family = AF_UNIX; strncpy(address.sun_path, "\0watchdogd.wdt.identity", sizeof(address.sun_path)-1); fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0); if (fd < 0) { goto error; } if (connect(fd, (struct sockaddr*)&address, sizeof(address)) < 0) { close(fd); goto direct; } read(fd, &buf, sizeof(buf)); close(fd); if (verbose) { printf("watchdog was set to %li seconds\n", buf.timeout); } printf("%s\n", buf.name); return 0; direct: if (!identity) { size_t len0 = 0, len1 = 0; int addZero = isdigit(*(basename(deviceName)+(strlen(basename(deviceName))-1))); size_t l = strlen(basename(deviceName))+1; char * watchdogBasename = (char*)calloc(1, l+1); memcpy(watchdogBasename, basename(deviceName), l); if (!addZero) { watchdogBasename[strlen(watchdogBasename)] = '0'; } char * sysfsIdentity = (char*)calloc(1, strlen(watchdogBasename)+strlen("/sys/class/watchdog//identity")+1); char * sysfsTimeout = (char*)calloc(1, strlen(watchdogBasename)+strlen("/sys/class/watchdog//identity")+1); sprintf(sysfsIdentity, "/sys/class/watchdog/%s/identity", watchdogBasename); sprintf(sysfsTimeout, "/sys/class/watchdog/%s/timeout", watchdogBasename); FILE * timeoutFile = fopen(sysfsTimeout, "r"); FILE * identityFile = fopen(sysfsIdentity, "r"); if (!identityFile||!timeoutFile) goto error; char *timeoutString = nullptr; char *identityString = nullptr; getline(&timeoutString, &len0, timeoutFile); getline(&identityString, &len1, identityFile); timeoutString[strlen(timeoutString)-1] = '\0'; identityString[strlen(identityString)-1] = '\0'; if (verbose) { printf("watchdog was set to %s seconds\n", timeoutString); } printf("%s\n", identityString); return 0; } if (verbose) { printf("watchdog was set to %li seconds\n", timeout); } printf("%s\n", identity); return 0; error: if (access(deviceName, R_OK|W_OK) != 0) { printf("%s\n", "unable to open watchdog device, this operation requires permission from system Administrator"); return 0; } printf("%s\n", "Unable to open watchdog device"); return 0; } <|start_filename|>src/snprintf.cpp<|end_filename|> /* * snprintf.c - a portable implementation of snprintf * * AUTHOR * <NAME> <<EMAIL>>, April 1999. * * Copyright 1999, <NAME>. All rights reserved. * * TERMS AND CONDITIONS * This program is free software; you can redistribute it and/or modify * it under the terms of the "Frontier Artistic License" which comes * with this Kit. * * 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 Frontier Artistic License for more details. * * You should have received a copy of the Frontier Artistic License * with this Kit in the file named LICENSE.txt . * If not, I'll be glad to provide one. * * FEATURES * - careful adherence to specs regarding flags, field width and precision; * - good performance for large string handling (large format, large * argument or large paddings). Performance is similar to system's sprintf * and in several cases significantly better (make sure you compile with * optimizations turned on, tell the compiler the code is strict ANSI * if necessary to give it more freedom for optimizations); * - return value semantics per ISO/IEC 9899:1999 ("ISO C99"); * - written in standard ISO/ANSI C - requires an ANSI C compiler. * * SUPPORTED CONVERSION SPECIFIERS AND DATA TYPES * * This snprintf only supports the following conversion specifiers: * s, c, d, u, o, x, X, p (and synonyms: i, D, U, O - see below) * with flags: '-', '+', ' ', '0' and '#'. * An asterisk is supported for field width as well as precision. * * Length modifiers 'h' (short int), 'l' (long int), * and 'll' (long long int) are supported. * NOTE: * If macro SNPRINTF_LONGLONG_SUPPORT is not defined (default) the * length modifier 'll' is recognized but treated the same as 'l', * which may cause argument value truncation! Defining * SNPRINTF_LONGLONG_SUPPORT requires that your system's sprintf also * handles length modifier 'll'. long long int is a language extension * which may not be portable. * * Conversion of numeric data (conversion specifiers d, u, o, x, X, p) * with length modifiers (none or h, l, ll) is left to the system routine * sprintf, but all handling of flags, field width and precision as well as * c and s conversions is done very carefully by this portable routine. * If a string precision (truncation) is specified (e.g. %.8s) it is * guaranteed the string beyond the specified precision will not be referenced. * * Length modifiers h, l and ll are ignored for c and s conversions (data * types wint_t and wchar_t are not supported). * * The following common synonyms for conversion characters are supported: * - i is a synonym for d * - D is a synonym for ld, explicit length modifiers are ignored * - U is a synonym for lu, explicit length modifiers are ignored * - O is a synonym for lo, explicit length modifiers are ignored * The D, O and U conversion characters are nonstandard, they are supported * for backward compatibility only, and should not be used for new code. * * The following is specifically NOT supported: * - flag ' (thousands' grouping character) is recognized but ignored * - numeric conversion specifiers: f, e, E, g, G and synonym F, * as well as the new a and A conversion specifiers * - length modifier 'L' (long double) and 'q' (quad - use 'll' instead) * - wide character/string conversions: lc, ls, and nonstandard * synonyms C and S * - writeback of converted string length: conversion character n * - the n$ specification for direct reference to n-th argument * - locales * * It is permitted for str_m to be zero, and it is permitted to specify NULL * pointer for resulting string argument if str_m is zero (as per ISO C99). * * The return value is the number of characters which would be generated * for the given input, excluding the trailing null. If this value * is greater or equal to str_m, not all characters from the result * have been stored in str, output bytes beyond the (str_m-1) -th character * are discarded. If str_m is greater than zero it is guaranteed * the resulting string will be null-terminated. * * NOTE that this matches the ISO C99, OpenBSD, and GNU C library 2.1, * but is different from some older and vendor implementations, * and is also different from XPG, XSH5, SUSv2 specifications. * For historical discussion on changes in the semantics and standards * of snprintf see printf(3) man page in the Linux programmers manual. * * Routines asprintf and vasprintf return a pointer (in the ptr argument) * to a buffer sufficiently large to hold the resulting string. This pointer * should be passed to free(3) to release the allocated storage when it is * no longer needed. If sufficient space cannot be allocated, these functions * will return -1 and set ptr to be a NULL pointer. These two routines are a * GNU C library extensions (glibc). * * Routines asnprintf and vasnprintf are similar to asprintf and vasprintf, * yet, like snprintf and vsnprintf counterparts, will write at most str_m-1 * characters into the allocated output string, the last character in the * allocated buffer then gets the terminating null. If the formatted string * length (the return value) is greater than or equal to the str_m argument, * the resulting string was truncated and some of the formatted characters * were discarded. These routines present a handy way to limit the amount * of allocated memory to some sane value. * * AVAILABILITY * http://www.ijs.si/software/snprintf/ * * REVISION HISTORY * 1999-04 V0.9 <NAME> * - initial version, some modifications after comparing printf * man pages for Digital Unix 4.0, Solaris 2.6 and HPUX 10, * and checking how Perl handles sprintf (differently!); * 1999-04-09 V1.0 <NAME> <<EMAIL>> * - added main test program, fixed remaining inconsistencies, * added optional (long long int) support; * 1999-04-12 V1.1 <NAME> <<EMAIL>> * - support the 'p' conversion (pointer to void); * - if a string precision is specified * make sure the string beyond the specified precision * will not be referenced (e.g. by strlen); * 1999-04-13 V1.2 <NAME> <<EMAIL>> * - support synonyms %D=%ld, %U=%lu, %O=%lo; * - speed up the case of long format string with few conversions; * 1999-06-30 V1.3 <NAME> <<EMAIL>> * - fixed runaway loop (eventually crashing when str_l wraps * beyond 2^31) while copying format string without * conversion specifiers to a buffer that is too short * (thanks to <NAME> <<EMAIL>> for * spotting the problem); * - added macros PORTABLE_SNPRINTF_VERSION_(MAJOR|MINOR) * to snprintf.h * 2000-02-14 V2.0 (never released) <NAME> <<EMAIL>> * - relaxed license terms: The Artistic License now applies. * You may still apply the GNU GENERAL PUBLIC LICENSE * as was distributed with previous versions, if you prefer; * - changed REVISION HISTORY dates to use ISO 8601 date format; * - added vsnprintf (patch also independently proposed by * Caol<NAME> 2000-05-04, and <NAME> 2000-06-01) * 2000-06-27 V2.1 <NAME> <<EMAIL>> * - removed POSIX check for str_m<1; value 0 for str_m is * allowed by ISO C99 (and GNU C library 2.1) - (pointed out * on 2000-05-04 by <NAME>, caolan@ csn dot ul dot ie). * Besides relaxed license this change in standards adherence * is the main reason to bump up the major version number; * - added nonstandard routines asnprintf, vasnprintf, asprintf, * vasprintf that dynamically allocate storage for the * resulting string; these routines are not compiled by default, * see comments where NEED_V?ASN?PRINTF macros are defined; * - autoconf contributed by <NAME> * 2000-10-06 V2.2 <NAME> <<EMAIL>> * - BUG FIX: the %c conversion used a temporary variable * that was no longer in scope when referenced, * possibly causing incorrect resulting character; * - BUG FIX: make precision and minimal field width unsigned * to handle huge values (2^31 <= n < 2^32) correctly; * also be more careful in the use of signed/unsigned/size_t * internal variables - probably more careful than many * vendor implementations, but there may still be a case * where huge values of str_m, precision or minimal field * could cause incorrect behaviour; * - use separate variables for signed/unsigned arguments, * and for short/int, long, and long long argument lengths * to avoid possible incompatibilities on certain * computer architectures. Also use separate variable * arg_sign to hold sign of a numeric argument, * to make code more transparent; * - some fiddling with zero padding and "0x" to make it * Linux compatible; * - systematically use macros fast_memcpy and fast_memset * instead of case-by-case hand optimization; determine some * breakeven string lengths for different architectures; * - terminology change: 'format' -> 'conversion specifier', * 'C9x' -> 'ISO/IEC 9899:1999 ("ISO C99")', * 'alternative form' -> 'alternate form', * 'data type modifier' -> 'length modifier'; * - several comments rephrased and new ones added; * - make compiler not complain about 'credits' defined but * not used; */ /* Define HAVE_SNPRINTF if your system already has snprintf and vsnprintf. * * If HAVE_SNPRINTF is defined this module will not produce code for * snprintf and vsnprintf, unless PREFER_PORTABLE_SNPRINTF is defined as well, * causing this portable version of snprintf to be called portable_snprintf * (and portable_vsnprintf). */ #define HAVE_SNPRINTF /* Define PREFER_PORTABLE_SNPRINTF if your system does have snprintf and * vsnprintf but you would prefer to use the portable routine(s) instead. * In this case the portable routine is declared as portable_snprintf * (and portable_vsnprintf) and a macro 'snprintf' (and 'vsnprintf') * is defined to expand to 'portable_v?snprintf' - see file snprintf.h . * Defining this macro is only useful if HAVE_SNPRINTF is also defined, * but does does no harm if defined nevertheless. */ #define PREFER_PORTABLE_SNPRINTF /* Define SNPRINTF_LONGLONG_SUPPORT if you want to support * data type (long long int) and length modifier 'll' (e.g. %lld). * If undefined, 'll' is recognized but treated as a single 'l'. * * If the system's sprintf does not handle 'll' * the SNPRINTF_LONGLONG_SUPPORT must not be defined! * * This is off by default as (long long int) is a language extension. */ #define SNPRINTF_LONGLONG_SUPPORT /* Define NEED_SNPRINTF_ONLY if you only need snprintf, and not vsnprintf. * If NEED_SNPRINTF_ONLY is defined, the snprintf will be defined directly, * otherwise both snprintf and vsnprintf routines will be defined * and snprintf will be a simple wrapper around vsnprintf, at the expense * of an extra procedure call. */ /* #define NEED_SNPRINTF_ONLY */ /* Define NEED_V?ASN?PRINTF macros if you need library extension * routines asprintf, vasprintf, asnprintf, vasnprintf respectively, * and your system library does not provide them. They are all small * wrapper routines around portable_vsnprintf. Defining any of the four * NEED_V?ASN?PRINTF macros automatically turns off NEED_SNPRINTF_ONLY * and turns on PREFER_PORTABLE_SNPRINTF. * * Watch for name conflicts with the system library if these routines * are already present there. * * NOTE: vasprintf and vasnprintf routines need va_copy() from stdarg.h, as * specified by C99, to be able to traverse the same list of arguments twice. * I don't know of any other standard and portable way of achieving the same. * With some versions of gcc you may use __va_copy(). You might even get away * with "ap2 = ap", in this case you must not call va_end(ap2) ! * #define va_copy(ap2,ap) ap2 = ap */ /* #define NEED_ASPRINTF */ /* #define NEED_ASNPRINTF */ /* #define NEED_VASPRINTF */ /* #define NEED_VASNPRINTF */ /* Define the following macros if desired: * SOLARIS_COMPATIBLE, SOLARIS_BUG_COMPATIBLE, * HPUX_COMPATIBLE, HPUX_BUG_COMPATIBLE, LINUX_COMPATIBLE, * DIGITAL_UNIX_COMPATIBLE, DIGITAL_UNIX_BUG_COMPATIBLE, * PERL_COMPATIBLE, PERL_BUG_COMPATIBLE, * * - For portable applications it is best not to rely on peculiarities * of a given implementation so it may be best not to define any * of the macros that select compatibility and to avoid features * that vary among the systems. * * - Selecting compatibility with more than one operating system * is not strictly forbidden but is not recommended. * * - 'x'_BUG_COMPATIBLE implies 'x'_COMPATIBLE . * * - 'x'_COMPATIBLE refers to (and enables) a behaviour that is * documented in a sprintf man page on a given operating system * and actually adhered to by the system's sprintf (but not on * most other operating systems). It may also refer to and enable * a behaviour that is declared 'undefined' or 'implementation specific' * in the man page but a given implementation behaves predictably * in a certain way. * * - 'x'_BUG_COMPATIBLE refers to (and enables) a behaviour of system's sprintf * that contradicts the sprintf man page on the same operating system. * * - I do not claim that the 'x'_COMPATIBLE and 'x'_BUG_COMPATIBLE * conditionals take into account all idiosyncrasies of a particular * implementation, there may be other incompatibilities. */ /* ============================================= */ /* NO USER SERVICABLE PARTS FOLLOWING THIS POINT */ /* ============================================= */ #define PORTABLE_SNPRINTF_VERSION_MAJOR 2 #define PORTABLE_SNPRINTF_VERSION_MINOR 2 #if defined(NEED_ASPRINTF) || defined(NEED_ASNPRINTF) || defined(NEED_VASPRINTF) || defined(NEED_VASNPRINTF) # if defined(NEED_SNPRINTF_ONLY) # undef NEED_SNPRINTF_ONLY # endif # if !defined(PREFER_PORTABLE_SNPRINTF) # define PREFER_PORTABLE_SNPRINTF # endif #endif #if defined(SOLARIS_BUG_COMPATIBLE) && !defined(SOLARIS_COMPATIBLE) #define SOLARIS_COMPATIBLE #endif #if defined(HPUX_BUG_COMPATIBLE) && !defined(HPUX_COMPATIBLE) #define HPUX_COMPATIBLE #endif #if defined(DIGITAL_UNIX_BUG_COMPATIBLE) && !defined(DIGITAL_UNIX_COMPATIBLE) #define DIGITAL_UNIX_COMPATIBLE #endif #if defined(PERL_BUG_COMPATIBLE) && !defined(PERL_COMPATIBLE) #define PERL_COMPATIBLE #endif #if defined(LINUX_BUG_COMPATIBLE) && !defined(LINUX_COMPATIBLE) #define LINUX_COMPATIBLE #endif #include <sys/types.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <stdarg.h> #include <assert.h> #include <errno.h> #ifdef isdigit #undef isdigit #endif #define isdigit(c) ((c) >= '0' && (c) <= '9') /* For copying strings longer or equal to 'breakeven_point' * it is more efficient to call memcpy() than to do it inline. * The value depends mostly on the processor architecture, * but also on the compiler and its optimization capabilities. * The value is not critical, some small value greater than zero * will be just fine if you don't care to squeeze every drop * of performance out of the code. * * Small values favor memcpy, large values favor inline code. */ #if defined(__alpha__) || defined(__alpha) # define breakeven_point 2 /* AXP (DEC Alpha) - gcc or cc or egcs */ #endif #if defined(__i386__) || defined(__i386) # define breakeven_point 12 /* Intel Pentium/Linux - gcc 2.96 */ #endif #if defined(__hppa) # define breakeven_point 10 /* HP-PA - gcc */ #endif #if defined(__sparc__) || defined(__sparc) # define breakeven_point 33 /* Sun Sparc 5 - gcc 2.8.1 */ #endif /* some other values of possible interest: */ /* #define breakeven_point 8 */ /* VAX 4000 - vaxc */ /* #define breakeven_point 19 */ /* VAX 4000 - gcc 2.7.0 */ #ifndef breakeven_point # define breakeven_point 6 /* some reasonable one-size-fits-all value */ #endif #define fast_memcpy(d,s,n) \ { size_t nn = (size_t)(n); \ if (nn >= breakeven_point) memcpy((d), (s), nn); \ else if (nn > 0) { /* proc call overhead is worth only for large strings*/\ char *dd; const char *ss; \ for (ss=(s), dd=(d); nn>0; nn--) *dd++ = *ss++; } } #define fast_memset(d,c,n) \ { size_t nn = (size_t)(n); \ if (nn >= breakeven_point) memset((d), (int)(c), nn); \ else if (nn > 0) { /* proc call overhead is worth only for large strings*/\ char *dd; const int cc=(int)(c); \ for (dd=(d); nn>0; nn--) *dd++ = cc; } } /* prototypes */ #if defined(NEED_ASPRINTF) int asprintf (char **ptr, const char *fmt, /*args*/ ...); #endif #if defined(NEED_VASPRINTF) int vasprintf (char **ptr, const char *fmt, va_list ap); #endif #if defined(NEED_ASNPRINTF) int asnprintf (char **ptr, size_t str_m, const char *fmt, /*args*/ ...); #endif #if defined(NEED_VASNPRINTF) int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap); #endif #if defined(HAVE_SNPRINTF) /* declare our portable snprintf routine under name portable_snprintf */ /* declare our portable vsnprintf routine under name portable_vsnprintf */ #else /* declare our portable routines under names snprintf and vsnprintf */ #define portable_snprintf snprintf #if !defined(NEED_SNPRINTF_ONLY) #define portable_vsnprintf vsnprintf #endif #endif #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF) int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...); #if !defined(NEED_SNPRINTF_ONLY) int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap); #endif #endif /* declarations */ static char credits[] = "\n\ @(#)snprintf.c, v2.2: <NAME>, <<EMAIL>>\n\ @(#)snprintf.c, v2.2: Copyright 1999, <NAME>. Frontier Artistic License applies.\n\ @(#)snprintf.c, v2.2: http://www.ijs.si/software/snprintf/\n"; #if defined(NEED_ASPRINTF) int asprintf(char **ptr, const char *fmt, /*args*/ ...) { va_list ap; size_t str_m; int str_l; *ptr = NULL; va_start(ap, fmt); /* measure the required size */ str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap); va_end(ap); assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */ *ptr = (char *) malloc(str_m = (size_t)str_l + 1); if (*ptr == NULL) { errno = ENOMEM; str_l = -1; } else { int str_l2; va_start(ap, fmt); str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap); va_end(ap); assert(str_l2 == str_l); } return str_l; } #endif #if defined(NEED_VASPRINTF) int vasprintf(char **ptr, const char *fmt, va_list ap) { size_t str_m; int str_l; *ptr = NULL; { va_list ap2; va_copy(ap2, ap); /* don't consume the original ap, we'll need it again */ str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap2);/*get required size*/ va_end(ap2); } assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */ *ptr = (char *) malloc(str_m = (size_t)str_l + 1); if (*ptr == NULL) { errno = ENOMEM; str_l = -1; } else { int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap); assert(str_l2 == str_l); } return str_l; } #endif #if defined(NEED_ASNPRINTF) int asnprintf (char **ptr, size_t str_m, const char *fmt, /*args*/ ...) { va_list ap; int str_l; *ptr = NULL; va_start(ap, fmt); /* measure the required size */ str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap); va_end(ap); assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */ if ((size_t)str_l + 1 < str_m) str_m = (size_t)str_l + 1; /* truncate */ /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */ if (str_m == 0) { /* not interested in resulting string, just return size */ } else { *ptr = (char *) malloc(str_m); if (*ptr == NULL) { errno = ENOMEM; str_l = -1; } else { int str_l2; va_start(ap, fmt); str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap); va_end(ap); assert(str_l2 == str_l); } } return str_l; } #endif #if defined(NEED_VASNPRINTF) int vasnprintf (char **ptr, size_t str_m, const char *fmt, va_list ap) { int str_l; *ptr = NULL; { va_list ap2; va_copy(ap2, ap); /* don't consume the original ap, we'll need it again */ str_l = portable_vsnprintf(NULL, (size_t)0, fmt, ap2);/*get required size*/ va_end(ap2); } assert(str_l >= 0); /* possible integer overflow if str_m > INT_MAX */ if ((size_t)str_l + 1 < str_m) str_m = (size_t)str_l + 1; /* truncate */ /* if str_m is 0, no buffer is allocated, just set *ptr to NULL */ if (str_m == 0) { /* not interested in resulting string, just return size */ } else { *ptr = (char *) malloc(str_m); if (*ptr == NULL) { errno = ENOMEM; str_l = -1; } else { int str_l2 = portable_vsnprintf(*ptr, str_m, fmt, ap); assert(str_l2 == str_l); } } return str_l; } #endif /* * If the system does have snprintf and the portable routine is not * specifically required, this module produces no code for snprintf/vsnprintf. */ #if !defined(HAVE_SNPRINTF) || defined(PREFER_PORTABLE_SNPRINTF) #if !defined(NEED_SNPRINTF_ONLY) int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) { va_list ap; int str_l; va_start(ap, fmt); str_l = portable_vsnprintf(str, str_m, fmt, ap); va_end(ap); return str_l; } #endif #if defined(NEED_SNPRINTF_ONLY) int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...) { #else int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap) { #endif #if defined(NEED_SNPRINTF_ONLY) va_list ap; #endif size_t str_l = 0; const char *p = fmt; /* In contrast with POSIX, the ISO C99 now says * that str can be NULL and str_m can be 0. * This is more useful than the old: if (str_m < 1) return -1; */ #if defined(NEED_SNPRINTF_ONLY) va_start(ap, fmt); #endif if (!p) p = ""; while (*p) { if (*p != '%') { /* if (str_l < str_m) str[str_l++] = *p++; -- this would be sufficient */ /* but the following code achieves better performance for cases * where format string is long and contains few conversions */ const char *q = strchr(p+1,'%'); size_t n = !q ? strlen(p) : (q-p); if (str_l < str_m) { size_t avail = str_m-str_l; fast_memcpy(str+str_l, p, (n>avail?avail:n)); } p += n; str_l += n; } else { size_t min_field_width = 0, precision = 0; int zero_padding = 0, precision_specified = 0, justify_left = 0; int alternate_form = 0, force_sign = 0; int space_for_positive = 1; /* If both the ' ' and '+' flags appear, the ' ' flag should be ignored. */ char length_modifier = '\0'; /* allowed values: \0, h, l, L */ char tmp[32];/* temporary buffer for simple numeric->string conversion */ const char *str_arg; /* string address in case of string argument */ size_t str_arg_l; /* natural field width of arg without padding and sign */ unsigned char uchar_arg; /* unsigned char argument value - only defined for c conversion. N.B. standard explicitly states the char argument for the c conversion is unsigned */ size_t number_of_zeros_to_pad = 0; /* number of zeros to be inserted for numeric conversions as required by the precision or minimal field width */ size_t zero_padding_insertion_ind = 0; /* index into tmp where zero padding is to be inserted */ char fmt_spec = '\0'; /* current conversion specifier character */ str_arg = credits;/* just to make compiler happy (defined but not used)*/ str_arg = NULL; p++; /* skip '%' */ /* parse flags */ while (*p == '0' || *p == '-' || *p == '+' || *p == ' ' || *p == '#' || *p == '\'') { switch (*p) { case '0': zero_padding = 1; break; case '-': justify_left = 1; break; case '+': force_sign = 1; space_for_positive = 0; break; case ' ': force_sign = 1; /* If both the ' ' and '+' flags appear, the ' ' flag should be ignored */ #ifdef PERL_COMPATIBLE /* ... but in Perl the last of ' ' and '+' applies */ space_for_positive = 1; #endif break; case '#': alternate_form = 1; break; case '\'': break; } p++; } /* If the '0' and '-' flags both appear, the '0' flag should be ignored. */ /* parse field width */ if (*p == '*') { int j; p++; j = va_arg(ap, int); if (j >= 0) min_field_width = j; else { min_field_width = -j; justify_left = 1; } } else if (isdigit((int)(*p))) { /* size_t could be wider than unsigned int; make sure we treat argument like common implementations do */ unsigned int uj = *p++ - '0'; while (isdigit((int)(*p))) uj = 10*uj + (unsigned int)(*p++ - '0'); min_field_width = uj; } /* parse precision */ if (*p == '.') { p++; precision_specified = 1; if (*p == '*') { int j = va_arg(ap, int); p++; if (j >= 0) precision = j; else { precision_specified = 0; precision = 0; /* NOTE: * Solaris 2.6 man page claims that in this case the precision * should be set to 0. Digital Unix 4.0, HPUX 10 and BSD man page * claim that this case should be treated as unspecified precision, * which is what we do here. */ } } else if (isdigit((int)(*p))) { /* size_t could be wider than unsigned int; make sure we treat argument like common implementations do */ unsigned int uj = *p++ - '0'; while (isdigit((int)(*p))) uj = 10*uj + (unsigned int)(*p++ - '0'); precision = uj; } } /* parse 'h', 'l' and 'll' length modifiers */ if (*p == 'h' || *p == 'l') { length_modifier = *p; p++; if (length_modifier == 'l' && *p == 'l') { /* double l = long long */ #ifdef SNPRINTF_LONGLONG_SUPPORT length_modifier = '2'; /* double l encoded as '2' */ #else length_modifier = 'l'; /* treat it as a single 'l' */ #endif p++; } } fmt_spec = *p; /* common synonyms: */ switch (fmt_spec) { case 'i': fmt_spec = 'd'; break; case 'D': fmt_spec = 'd'; length_modifier = 'l'; break; case 'U': fmt_spec = 'u'; length_modifier = 'l'; break; case 'O': fmt_spec = 'o'; length_modifier = 'l'; break; default: break; } /* get parameter value, do initial processing */ switch (fmt_spec) { case '%': /* % behaves similar to 's' regarding flags and field widths */ case 'c': /* c behaves similar to 's' regarding flags and field widths */ case 's': length_modifier = '\0'; /* wint_t and wchar_t not supported */ /* the result of zero padding flag with non-numeric conversion specifier*/ /* is undefined. Solaris and HPUX 10 does zero padding in this case, */ /* Digital Unix and Linux does not. */ #if !defined(SOLARIS_COMPATIBLE) && !defined(HPUX_COMPATIBLE) zero_padding = 0; /* turn zero padding off for string conversions */ #endif str_arg_l = 1; switch (fmt_spec) { case '%': str_arg = p; break; case 'c': { int j = va_arg(ap, int); uchar_arg = (unsigned char) j; /* standard demands unsigned char */ str_arg = (const char *) &uchar_arg; break; } case 's': str_arg = va_arg(ap, const char *); if (!str_arg) str_arg_l = 0; /* make sure not to address string beyond the specified precision !!! */ else if (!precision_specified) str_arg_l = strlen(str_arg); /* truncate string if necessary as requested by precision */ else if (precision == 0) str_arg_l = 0; else { /* memchr on HP does not like n > 2^31 !!! */ const char *q = (const char *)memchr(str_arg, '\0', precision <= 0x7fffffff ? precision : 0x7fffffff); str_arg_l = !q ? precision : (q-str_arg); } break; default: break; } break; case 'd': case 'u': case 'o': case 'x': case 'X': case 'p': { /* NOTE: the u, o, x, X and p conversion specifiers imply the value is unsigned; d implies a signed value */ int arg_sign = 0; /* 0 if numeric argument is zero (or if pointer is NULL for 'p'), +1 if greater than zero (or nonzero for unsigned arguments), -1 if negative (unsigned argument is never negative) */ int int_arg = 0; unsigned int uint_arg = 0; /* only defined for length modifier h, or for no length modifiers */ long int long_arg = 0; unsigned long int ulong_arg = 0; /* only defined for length modifier l */ void *ptr_arg = NULL; /* pointer argument value -only defined for p conversion */ #ifdef SNPRINTF_LONGLONG_SUPPORT long long int long_long_arg = 0; unsigned long long int ulong_long_arg = 0; /* only defined for length modifier ll */ #endif if (fmt_spec == 'p') { /* HPUX 10: An l, h, ll or L before any other conversion character * (other than d, i, u, o, x, or X) is ignored. * Digital Unix: * not specified, but seems to behave as HPUX does. * Solaris: If an h, l, or L appears before any other conversion * specifier (other than d, i, u, o, x, or X), the behavior * is undefined. (Actually %hp converts only 16-bits of address * and %llp treats address as 64-bit data which is incompatible * with (void *) argument on a 32-bit system). */ #ifdef SOLARIS_COMPATIBLE # ifdef SOLARIS_BUG_COMPATIBLE /* keep length modifiers even if it represents 'll' */ # else if (length_modifier == '2') length_modifier = '\0'; # endif #else length_modifier = '\0'; #endif ptr_arg = va_arg(ap, void *); if (ptr_arg != NULL) arg_sign = 1; } else if (fmt_spec == 'd') { /* signed */ switch (length_modifier) { case '\0': case 'h': /* It is non-portable to specify a second argument of char or short * to va_arg, because arguments seen by the called function * are not char or short. C converts char and short arguments * to int before passing them to a function. */ int_arg = va_arg(ap, int); if (int_arg > 0) arg_sign = 1; else if (int_arg < 0) arg_sign = -1; break; case 'l': long_arg = va_arg(ap, long int); if (long_arg > 0) arg_sign = 1; else if (long_arg < 0) arg_sign = -1; break; #ifdef SNPRINTF_LONGLONG_SUPPORT case '2': long_long_arg = va_arg(ap, long long int); if (long_long_arg > 0) arg_sign = 1; else if (long_long_arg < 0) arg_sign = -1; break; #endif } } else { /* unsigned */ switch (length_modifier) { case '\0': case 'h': uint_arg = va_arg(ap, unsigned int); if (uint_arg) arg_sign = 1; break; case 'l': ulong_arg = va_arg(ap, unsigned long int); if (ulong_arg) arg_sign = 1; break; #ifdef SNPRINTF_LONGLONG_SUPPORT case '2': ulong_long_arg = va_arg(ap, unsigned long long int); if (ulong_long_arg) arg_sign = 1; break; #endif } } str_arg = tmp; str_arg_l = 0; /* NOTE: * For d, i, u, o, x, and X conversions, if precision is specified, * the '0' flag should be ignored. This is so with Solaris 2.6, * Digital UNIX 4.0, HPUX 10, Linux, FreeBSD, NetBSD; but not with Perl. */ #ifndef PERL_COMPATIBLE if (precision_specified) zero_padding = 0; #endif if (fmt_spec == 'd') { if (force_sign && arg_sign >= 0) tmp[str_arg_l++] = space_for_positive ? ' ' : '+'; /* leave negative numbers for sprintf to handle, to avoid handling tricky cases like (short int)(-32768) */ #ifdef LINUX_COMPATIBLE } else if (fmt_spec == 'p' && force_sign && arg_sign > 0) { tmp[str_arg_l++] = space_for_positive ? ' ' : '+'; #endif } else if (alternate_form) { if (arg_sign != 0 && (fmt_spec == 'x' || fmt_spec == 'X') ) { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = fmt_spec; } /* alternate form should have no effect for p conversion, but ... */ #ifdef HPUX_COMPATIBLE else if (fmt_spec == 'p' /* HPUX 10: for an alternate form of p conversion, * a nonzero result is prefixed by 0x. */ #ifndef HPUX_BUG_COMPATIBLE /* Actually it uses 0x prefix even for a zero value. */ && arg_sign != 0 #endif ) { tmp[str_arg_l++] = '0'; tmp[str_arg_l++] = 'x'; } #endif } zero_padding_insertion_ind = str_arg_l; if (!precision_specified) precision = 1; /* default precision is 1 */ if (precision == 0 && arg_sign == 0 #if defined(HPUX_BUG_COMPATIBLE) || defined(LINUX_COMPATIBLE) && fmt_spec != 'p' /* HPUX 10 man page claims: With conversion character p the result of * converting a zero value with a precision of zero is a null string. * Actually HP returns all zeroes, and Linux returns "(nil)". */ #endif ) { /* converted to null string */ /* When zero value is formatted with an explicit precision 0, the resulting formatted string is empty (d, i, u, o, x, X, p). */ } else { char f[5]; int f_l = 0; f[f_l++] = '%'; /* construct a simple format string for sprintf */ if (!length_modifier) { } else if (length_modifier=='2') { f[f_l++] = 'l'; f[f_l++] = 'l'; } else f[f_l++] = length_modifier; f[f_l++] = fmt_spec; f[f_l++] = '\0'; if (fmt_spec == 'p') str_arg_l += sprintf(tmp+str_arg_l, f, ptr_arg); else if (fmt_spec == 'd') { /* signed */ switch (length_modifier) { case '\0': case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, int_arg); break; case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, long_arg); break; #ifdef SNPRINTF_LONGLONG_SUPPORT case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,long_long_arg); break; #endif } } else { /* unsigned */ switch (length_modifier) { case '\0': case 'h': str_arg_l+=sprintf(tmp+str_arg_l, f, uint_arg); break; case 'l': str_arg_l+=sprintf(tmp+str_arg_l, f, ulong_arg); break; #ifdef SNPRINTF_LONGLONG_SUPPORT case '2': str_arg_l+=sprintf(tmp+str_arg_l,f,ulong_long_arg);break; #endif } } /* include the optional minus sign and possible "0x" in the region before the zero padding insertion point */ if (zero_padding_insertion_ind < str_arg_l && tmp[zero_padding_insertion_ind] == '-') { zero_padding_insertion_ind++; } if (zero_padding_insertion_ind+1 < str_arg_l && tmp[zero_padding_insertion_ind] == '0' && (tmp[zero_padding_insertion_ind+1] == 'x' || tmp[zero_padding_insertion_ind+1] == 'X') ) { zero_padding_insertion_ind += 2; } } { size_t num_of_digits = str_arg_l - zero_padding_insertion_ind; if (alternate_form && fmt_spec == 'o' #ifdef HPUX_COMPATIBLE /* ("%#.o",0) -> "" */ && (str_arg_l > 0) #endif #ifdef DIGITAL_UNIX_BUG_COMPATIBLE /* ("%#o",0) -> "00" */ #else /* unless zero is already the first character */ && !(zero_padding_insertion_ind < str_arg_l && tmp[zero_padding_insertion_ind] == '0') #endif ) { /* assure leading zero for alternate-form octal numbers */ if (!precision_specified || precision < num_of_digits+1) { /* precision is increased to force the first character to be zero, except if a zero value is formatted with an explicit precision of zero */ precision = num_of_digits+1; precision_specified = 1; } } /* zero padding to specified precision? */ if (num_of_digits < precision) number_of_zeros_to_pad = precision - num_of_digits; } /* zero padding to specified minimal field width? */ if (!justify_left && zero_padding) { int n = min_field_width - (str_arg_l+number_of_zeros_to_pad); if (n > 0) number_of_zeros_to_pad += n; } break; } default: /* unrecognized conversion specifier, keep format string as-is*/ zero_padding = 0; /* turn zero padding off for non-numeric convers. */ #ifndef DIGITAL_UNIX_COMPATIBLE justify_left = 1; min_field_width = 0; /* reset flags */ #endif #if defined(PERL_COMPATIBLE) || defined(LINUX_COMPATIBLE) /* keep the entire format string unchanged */ str_arg = starting_p; str_arg_l = p - starting_p; /* well, not exactly so for Linux, which does something inbetween, * and I don't feel an urge to imitate it: "%+++++hy" -> "%+y" */ #else /* discard the unrecognized conversion, just keep * * the unrecognized conversion character */ str_arg = p; str_arg_l = 0; #endif if (*p) str_arg_l++; /* include invalid conversion specifier unchanged if not at end-of-string */ break; } if (*p) p++; /* step over the just processed conversion specifier */ /* insert padding to the left as requested by min_field_width; this does not include the zero padding in case of numerical conversions*/ if (!justify_left) { /* left padding with blank or zero */ int n = min_field_width - (str_arg_l+number_of_zeros_to_pad); if (n > 0) { if (str_l < str_m) { size_t avail = str_m-str_l; fast_memset(str+str_l, (zero_padding?'0':' '), (n>avail?avail:n)); } str_l += n; } } /* zero padding as requested by the precision or by the minimal field width * for numeric conversions required? */ if (number_of_zeros_to_pad <= 0) { /* will not copy first part of numeric right now, * * force it to be copied later in its entirety */ zero_padding_insertion_ind = 0; } else { /* insert first part of numerics (sign or '0x') before zero padding */ int n = zero_padding_insertion_ind; if (n > 0) { if (str_l < str_m) { size_t avail = str_m-str_l; fast_memcpy(str+str_l, str_arg, (n>avail?avail:n)); } str_l += n; } /* insert zero padding as requested by the precision or min field width */ n = number_of_zeros_to_pad; if (n > 0) { if (str_l < str_m) { size_t avail = str_m-str_l; fast_memset(str+str_l, 0, (n>avail?avail:n)); } str_l += n; } } /* insert formatted string * (or as-is conversion specifier for unknown conversions) */ { int n = str_arg_l - zero_padding_insertion_ind; if (n > 0) { if (str_l < str_m) { size_t avail = str_m-str_l; fast_memcpy(str+str_l, str_arg+zero_padding_insertion_ind, (n>avail?avail:n)); } str_l += n; } } /* insert right padding */ if (justify_left) { /* right blank padding to the field width */ int n = min_field_width - (str_arg_l+number_of_zeros_to_pad); if (n > 0) { if (str_l < str_m) { size_t avail = str_m-str_l; fast_memset(str+str_l, ' ', (n>avail?avail:n)); } str_l += n; } } } } #if defined(NEED_SNPRINTF_ONLY) va_end(ap); #endif if (str_m > 0) { /* make sure the string is null-terminated even at the expense of overwriting the last character (shouldn't happen, but just in case) */ str[str_l <= str_m-1 ? str_l : str_m-1] = '\0'; } /* Return the number of characters formatted (excluding trailing null * character), that is, the number of characters that would have been * written to the buffer if it were large enough. * * The value of str_l should be returned, but str_l is of unsigned type * size_t, and snprintf is int, possibly leading to an undetected * integer overflow, resulting in a negative return value, which is illegal. * Both XSH5 and ISO C99 (at least the draft) are silent on this issue. * Should errno be set to EOVERFLOW and EOF returned in this case??? */ return (int) str_l; } #endif <|start_filename|>src/watchdogd.hpp<|end_filename|> #ifndef WATCHDOGD_H #define WATCHDOGD_H #ifdef __COVERITY__ #define __INCLUDE_LEVEL__ 22 //XXX: This is nessary for cov-build to work #endif #define _XOPEN_SOURCE 700 #define _FILE_OFFSET_BITS 64 #define PREFER_PORTABLE_SNPRINTF #define HAVE_SNPRINTF #include <atomic> #include <cassert> #include <cctype> #include <cerrno> #include <cinttypes> #include <climits> #include <config.h> #include <csignal> #include <cstdarg> #include <cstddef> #include <cstdint> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <dirent.h> #include <fcntl.h> #include <grp.h> #include <libconfig.h> #include <oping.h> #include <pthread.h> #include <pwd.h> #include <sched.h> #include <syslog.h> #include <sys/mman.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/time.h> #include <sys/un.h> #include <sys/wait.h> #include <thread> #include <unistd.h> #include "snprintf.hpp" #include "watchdog.hpp" #ifndef NSIG #if defined(_NSIG) #define NSIG _NSIG /* For BSD/SysV */ #elif defined(_SIGMAX) #define NSIG (_SIGMAX + 1) /* For QNX */ #elif defined(SIGMAX) #define NSIG (SIGMAX + 1) /* For djgpp */ #else #define NSIG 64 /* Use a reasonable default value */ #endif #endif #include "list.hpp" #if defined __cplusplus #define restrict #endif #define ARRAY_SIZE(a) (sizeof(a)/sizeof((a)[0])) #define SOFTBOOT 0x1 #define SYNC 0x2 #define USEPIDFILE 0x4 #define ENABLEPING 0x8 #define KEXEC 0x10 #define DAEMONIZE 0x20 #define ENABLEPIDCHECKER 0x40 #define FORCE 0x80 #define NOACTION 0x100 #define REALTIME 0x200 #define VERBOSE 0x400 #define IDENTIFY 0x800 #define BUSYBOXDEVOPTCOMPAT 0x1000 #define LOGLVLSETCMDLN 0x2000 #define SCRIPTFAILED 0x1 #define FORKFAILED 0x2 #define OUTOFMEMORY 0x4 #define LOADAVGTOOHIGH 0x8 #define UNKNOWNPIDFILERROR 0x10 #define PIDFILERROR 0x20 #define PINGFAILED 0x40 #define NETWORKDOWN 0x80 //TODO: Split this struct into an options struct(values read in from config file) and a runtime struct. struct cfgoptions { config_t cfg = {0}; double maxLoadFifteen = 0.0; double maxLoadOne = 0.0; double maxLoadFive = 0.0; double retryLimit = 0.0; const config_setting_t *ipAddresses = NULL; const config_setting_t *networkInterfaces = NULL; pingobj_t *pingObj = NULL; const config_setting_t *pidFiles = NULL; const char *devicepath = NULL; const char *pidfileName = NULL; const char *testexepath = "/usr/libexec/watchdog/scripts"; const char *exepathname = NULL; const char *testexepathname = NULL; const char *confile = "/etc/watchdogd.conf"; unsigned long options = 0; const char *logTarget = NULL; const char *logUpto = NULL; time_t sleeptime = -1; unsigned long minfreepages = 0; int testBinTimeout = 60; int repairBinTimeout = 60; int sigtermDelay = 0; int priority = 0; int watchdogTimeout = -1; int testExeReturnValue = 0; int allocatableMemory = 0; volatile std::atomic_uint error = {0}; bool haveConfigFile = false; }; struct ProcessList { struct list head; }; typedef struct ProcessList ProcessList; struct spawnattr_t { char *workingDirectory; const char *repairFilePathname; char *execStart; char *user; char *group; int timeout; int nice; mode_t umask; bool noNewPrivileges; bool hasUmask; }; struct repaircmd_t { spawnattr_t spawnattr; struct list entry; const char *path; char retString[8]; int ret; std::atomic_bool mode; bool legacy; }; struct dbusinfo { cfgoptions **config; Watchdog **wdt; int fd; bool miniMode; }; struct identinfo { char name[128]; char deviceName[128]; char daemonVersion[8]; long unsigned flags; long timeout; long firmwareVersion; }; struct dev { char name[64]; unsigned long minor; unsigned long major; }; extern ProcessList processes; enum logTarget_t { INVALID_LOG_TARGET, STANDARD_ERROR, SYSTEM_LOG, FILE_APPEND, FILE_NEW, }; #endif <|start_filename|>src/bootstatus.cpp<|end_filename|> /* * Copyright 2016-2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ #include "watchdogd.hpp" #include "bootstatus.hpp" int WriteBootStatus(unsigned long status, const char * const pathName, long long sleeptime, int timeout) { if (pathName == NULL) { return -1; } int fd = open("/run/watchdogd.status", O_WRONLY|O_CLOEXEC|O_CREAT, 0644); if (fd < 0) { return fd; } dprintf(fd, "Reset cause : 0x%04lx\n", status); dprintf(fd, "Timeout (sec) : %i\n", timeout); dprintf(fd, "Kick Interval : %lli\n", sleeptime); close(fd); return 0; } <|start_filename|>src/myvsnprintf_ss.hpp<|end_filename|> #ifndef MYVSNPRINTF_SS_H #define MYVSNPRINTF_SS_H int MyVsnprintf_ss(char *, size_t, const char *, va_list); #endif <|start_filename|>src/logutils.hpp<|end_filename|> #ifndef LOGUTILS_H #define LOGUTILS_H #ifndef LOG_PRIMASK #define LOG_PRIMASK 0x07 #endif #ifndef LOG_PRI #define LOG_PRI(p) ((p) & LOG_PRIMASK) #endif #ifndef LOG_MASK #define LOG_MASK(pri) (1 << (pri)) #endif #ifndef LOG_UPTO #define LOG_UPTO(pri) ((1 << ((pri)+1)) - 1) #endif void __attribute__ ((format (printf, 2, 3))) Logmsg(int priority, const char *const fmt, ...); void SetLogTarget(sig_atomic_t target, ...); void SetAutoUpperCase(bool); void SetAutoPeriod(bool); void HashTagPriority(bool); bool LogUpTo(const char *const, bool); bool LogUpToInt(long pri, bool); bool MyStrerrorInit(void); char * MyStrerror(int); void FreeLocale(void); #endif <|start_filename|>src/list.hpp<|end_filename|> /* * Copyright © 2010-2012 Intel Corporation * Copyright © 2010 <NAME> <<EMAIL>> * * 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 (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. * */ #include "watchdogd.hpp" #ifndef LIST_H_ #define LIST_H_ /** * The linkage struct for list nodes. This struct must be part of your * to-be-linked struct. struct list is required for both the head of the * list and for each list node. * * Position and name of the struct list field is irrelevant. * There are no requirements that elements of a list are of the same type. * There are no requirements for a list head, any struct list can be a list * head. */ struct list { struct list *next, *prev; }; bool list_is_empty(const struct list *head); void list_move_tail(struct list *list, struct list *head); void list_move(struct list *list, struct list *head); void list_del(struct list *entry); void list_append(struct list *entry, struct list *head); void list_replace(struct list *old, struct list *_new); void list_add_tail(struct list *entry, struct list *head); void list_init(struct list *list); void list_add(struct list *entry, struct list *head); /** * @file Classic doubly-link circular list implementation. * For real usage examples of the linked list, see the file test/list.c * * Example: * We need to keep a list of struct foo in the parent struct bar, i.e. what * we want is something like this. * * struct bar { * ... * struct foo *list_of_foos; -----> struct foo {}, struct foo {}, struct foo{} * ... * } * * We need one list head in bar and a list element in all list_of_foos (both are of * data type 'struct list'). * * struct bar { * ... * struct list list_of_foos; * ... * } * * struct foo { * ... * struct list entry; * ... * } * * Now we initialize the list head: * * struct bar bar; * ... * list_init(&bar.list_of_foos); * * Then we create the first element and add it to this list: * * struct foo *foo = malloc(...); * .... * list_add(&foo->entry, &bar.list_of_foos); * * Repeat the above for each element you want to add to the list. Deleting * works with the element itself. * list_del(&foo->entry); * free(foo); * * Note: calling list_del(&bar.list_of_foos) will set bar.list_of_foos to an empty * list again. * * Looping through the list requires a 'struct foo' as iterator and the * name of the field the subnodes use. * * struct foo *iterator; * list_for_each_entry(iterator, &bar.list_of_foos, entry) { * if (iterator->something == ...) * ... * } * * Note: You must not call list_del() on the iterator if you continue the * loop. You need to run the safe for-each loop instead: * * struct foo *iterator, *next; * list_for_each_entry_safe(iterator, next, &bar.list_of_foos, entry) { * if (...) * list_del(&iterator->entry); * } * */ /** * Alias of container_of */ #define list_entry(ptr, type, member) \ container_of(ptr, type, member) /** * Retrieve the first list entry for the given list pointer. * * Example: * struct foo *first; * first = list_first_entry(&bar->list_of_foos, struct foo, list_of_foos); * * @param ptr The list head * @param type Data type of the list element to retrieve * @param member Member name of the struct list field in the list element. * @return A pointer to the first list element. */ #define list_first_entry(ptr, type, member) \ list_entry((ptr)->next, type, member) /** * Retrieve the last list entry for the given listpointer. * * Example: * struct foo *first; * first = list_last_entry(&bar->list_of_foos, struct foo, list_of_foos); * * @param ptr The list head * @param type Data type of the list element to retrieve * @param member Member name of the struct list field in the list element. * @return A pointer to the last list element. */ #ifndef __cplusplus #define decltype __typeof__ #endif #define list_last_entry(ptr, type, member) \ list_entry((ptr)->prev, type, member) #define __container_of(ptr, sample, member) \ (decltype(sample))(void*)((char *)(ptr) \ - ((char *)&(sample)->member - (char *)(sample))) /** * Loop through the list, keeping a backup pointer to the element. This * macro allows for the deletion of a list element while looping through the * list. * * See list_for_each_entry for more details. */ #define list_for_each_entry(pos, tmp, head, member) \ for (pos = __container_of((head)->next, pos, member), \ tmp = __container_of(pos->member.next, pos, member); \ &pos->member != (head); \ pos = tmp, tmp = __container_of(pos->member.next, tmp, member)) #define list_last_entry(ptr, type, member) \ list_entry((ptr)->prev, type, member) #define container_of(ptr, type, member) ({ \ decltype( ((type *)0)->member ) *__mptr = (ptr); \ (type *)( (char *)__mptr - offsetof(type,member));}) #endif /* LIST_H_ */ <|start_filename|>src/pidfile.hpp<|end_filename|> #ifndef PIDFILE_H #define PIDFILE_H #include <unistd.h> class Pidfile { const char * name = NULL; int ret = 0; public: int Open(const char *const); int Write(pid_t); int Delete(); }; #endif <|start_filename|>src/user.cpp<|end_filename|> /* * Copyright 2014-2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ #include "watchdogd.hpp" #include "logutils.hpp" #include "user.hpp" static bool SetGroup(const char *restrict const group) { if (group == NULL) { errno = -1; return false; } long int initlen = sysconf(_SC_GETGR_R_SIZE_MAX); size_t len = 0; int ret = 0; if (initlen == -1) { len = 4096; } else { len = (size_t) initlen; } struct group grp = {0}; struct group *result = NULL; char buf [len]; memset(buf, 0, sizeof(len)); if (strtoll(group, NULL, 10) != 0) { gid_t gid = (gid_t)strtoll(group, NULL, 10); if (getgrgid_r(gid, &grp, buf, len, &result) != 0) { goto error; } if (setgid(grp.gr_gid) != 0) { goto error; } return true; } ret = getgrnam_r(group, &grp, buf, len, &result); if (ret != 0) { goto error; } if (setgid(grp.gr_gid) != 0) { goto error; } return true; error: return false; } int RunAsUser(const char *restrict const user, const char *restrict const group) { struct passwd pwd = {0}; struct passwd *result = NULL; long int initlen = sysconf(_SC_GETPW_R_SIZE_MAX); size_t len = 0; if (initlen == -1) { len = 4096; } else { len = (size_t) initlen; } char buf [len]; memset(buf, 0, sizeof(len)); if (user != NULL) { if (strtoll(user, NULL, 10) != 0) { uid_t uid = (uid_t)strtoll(group, NULL, 10); if (getpwuid_r(uid, &pwd, buf, len, &result) != 0) { goto error; } if (setgid(pwd.pw_uid) != 0) { goto error; } return 0; } int ret = getpwnam_r(user, &pwd, buf, len, &result); if (result == NULL) { goto error; } if (ret != 0) { goto error; } } if (group == NULL && user != NULL) { if (setgid(pwd.pw_gid) != 0) { goto error; } if (setuid(pwd.pw_uid) != 0) { goto error; } if (setgid(0) == 0) { goto error; } } else { if (SetGroup(group) == false) { if (errno != -1) { Logmsg(LOG_ERR, "unable run executable in group: %s", group); Logmsg(LOG_ERR, "trying default group"); } if (setgid(pwd.pw_gid) != 0) { goto error; } if (user != NULL && setuid(pwd.pw_uid) != 0) { goto error; } if (setgid(0) == 0 && pwd.pw_gid != 0) { goto error; } } else { if (user != NULL && setuid(pwd.pw_uid) != 0) { goto error; } } } return 0; error: return -1; } <|start_filename|>src/dbusapi.cpp<|end_filename|> /* * Copyright 2016-2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ #define DBUSAPI_PROTOTYPES #include "dbusapi.hpp" #include <errno.h> #include <stdlib.h> #include <zlib.h> #define MAX_CLIENT_ID 4096 typedef uint64_t usec_t; static sd_event *event = NULL; static sd_bus *bus = NULL; static sd_event_source *clients[MAX_CLIENT_ID] = {NULL}; static short freeIds[MAX_CLIENT_ID] = {-1}; static usec_t clientTimeout[MAX_CLIENT_ID] = {0}; static int lastAllocatedId = 0; static int openSlots = MAX_CLIENT_ID; static int lastFreedSlot = -1; static int fd = 0; static char identity[64] = {'\0'}; static char path[64] = {'\0'}; static long version = -1; static long timeout = 0; static const sd_bus_vtable watchdogPmon[] = { SD_BUS_VTABLE_START(0), SD_BUS_METHOD("DevicePath", "", "s", DevicePath, 0), SD_BUS_METHOD("Identity", "", "s", Identity, 0), SD_BUS_METHOD("Version", "", "x", Version, 0), SD_BUS_METHOD("GetTimeout", "", "x", GetTimeoutDbus, 0), SD_BUS_METHOD("GetTimeleft", "", "x", GetTimeleftDbus, 0), SD_BUS_METHOD("PmonInit", "t", "u", PmonInit, 0), SD_BUS_METHOD("PmonPing", "u", "b", PmonPing, 0), SD_BUS_METHOD("PmonRemove", "u", "b", PmonRemove, 0), SD_BUS_METHOD("ReloadConfig", "", "b", ReloadService, 0), SD_BUS_VTABLE_END }; static int ReloadService(sd_bus_message *m, void *userdata, sd_bus_error *retError) { int x = 0; int y = kill(getppid(), SIGHUP); read(fd, &x, sizeof(x)); return sd_bus_reply_method_return(m, "b", y == 0); } static int Timeout(sd_event_source *source, usec_t usec, void *userdata) { int cmd = DBUSHUTDOWN; do write(fd, &cmd, sizeof(long)); while (errno != 0); return -1; } static int PmonRemove(sd_bus_message *m, void *userdata, sd_bus_error *retError) { int id = 0; sd_bus_message_read(m, "u", &id); char *sid = (char*)sd_event_source_get_userdata(clients[id]); if (sid == NULL) { return sd_bus_reply_method_return(m, "b", false); } if (strcmp((char*)sd_event_source_get_userdata(clients[id]), sd_bus_message_get_sender(m)) != 0) { return sd_bus_reply_method_return(m, "b", false); } sd_event_source_set_enabled(clients[id], SD_EVENT_OFF); sd_event_source_unref(clients[id]); //systemd will gc object after unrefing it. clients[id] = NULL; lastFreedSlot += 1; openSlots += 1; freeIds[lastFreedSlot] = id; return sd_bus_reply_method_return(m, "b", true); } static int PmonPing(sd_bus_message *m, void *userdata, sd_bus_error *retError) { int id = 0; sd_bus_message_read(m, "u", &id); char *sid = (char*)sd_event_source_get_userdata(clients[id]); if (sid == NULL) { return sd_bus_reply_method_return(m, "b", false); } if (strcmp((char*)sd_event_source_get_userdata(clients[id]), sd_bus_message_get_sender(m)) != 0) { return sd_bus_reply_method_return(m, "b", false); } uint64_t usec = 0; sd_event_now(event, CLOCK_MONOTONIC, &usec); sd_event_source_set_time(clients[id], clientTimeout[id]+usec); return sd_bus_reply_method_return(m, "b", true); } static int PmonInit(sd_bus_message *m, void *userdata, sd_bus_error *retError) { usec_t time = 0; sd_bus_message_read(m, "t", &time); int id = 0; if (openSlots == 0) { return sd_bus_reply_method_return(m, "u", -1); } uint64_t usec = 0; sd_event_now(event, CLOCK_MONOTONIC, &usec); usec += time; if (clients[lastAllocatedId] == NULL) { id = lastAllocatedId; sd_event_add_time(event, &clients[lastAllocatedId], CLOCK_MONOTONIC, usec, 1000, Timeout, (void *)sd_bus_message_get_sender(m)); lastAllocatedId += 1; openSlots -= 1; clientTimeout[id] = time; return sd_bus_reply_method_return(m, "u", id); } id = freeIds[lastFreedSlot]; sd_event_add_time(event, &clients[freeIds[lastFreedSlot]], CLOCK_MONOTONIC, usec, 1000, Timeout, (void *)sd_bus_message_get_sender(m)); lastFreedSlot -= 1; openSlots -= 1; clientTimeout[id] = time; return sd_bus_reply_method_return(m, "u", id); } static int DevicePath(sd_bus_message *m, void *userdata, sd_bus_error *retError) { int cmd = DBUSGETPATH; if (strlen(path) == 0) { write(fd, &cmd, sizeof(int)); read(fd, path, sizeof(path)); } return sd_bus_reply_method_return(m, "s", path); } static int Identity(sd_bus_message *m, void *userdata, sd_bus_error *retError) { int cmd = DBUSGETNAME; if (strlen(identity) == 0) { write(fd, &cmd, sizeof(int)); read(fd, identity, sizeof(identity)); } return sd_bus_reply_method_return(m, "s", identity); } static int Version(sd_bus_message *m, void *userdata, sd_bus_error *retError) { int cmd = DBUSVERSION; if (version == -1) { write(fd, &cmd, sizeof(long)); read(fd, &version, sizeof(long)); } return sd_bus_reply_method_return(m, "x", version); } static int GetTimeoutDbus(sd_bus_message *m, void *userdata, sd_bus_error *retError) { int cmd = DBUSGETIMOUT; if (timeout == 0) { write(fd, &cmd, sizeof(long)); read(fd, &timeout, sizeof(long)); } return sd_bus_reply_method_return(m, "x", timeout); } static int GetTimeleftDbus(sd_bus_message *m, void *userdata, sd_bus_error *retError) { int cmd = DBUSTIMELEFT; static long buf; static time_t last; if (difftime(time(nullptr), last) > 2.0) { last = time(nullptr); write(fd, &cmd, sizeof(long)); read(fd, &buf, sizeof(long)); } return sd_bus_reply_method_return(m, "x", buf); } static int BusHandler(sd_event_source *es, int fd, uint32_t revents, void *userdata) { sd_bus_process(bus, NULL); return 1; } static int ReloadDbusDaemon(void) { static const unsigned char cFile[] = { 0x78, 0x9c, 0x8d, 0x8f, 0xc1, 0x4a, 0xc4, 0x30, 0x10, 0x86, 0xef, 0x0b, 0xfb, 0x0e, 0xe3, 0xdc, 0xdb, 0x71, 0x6f, 0x22, 0xed, 0x2e, 0xb4, 0x5d, 0x41, 0x10, 0x5d, 0xb0, 0x7b, 0xf0, 0x24, 0xb1, 0x49, 0xdb, 0x60, 0xcd, 0x94, 0x24, 0x35, 0xfa, 0xf6, 0xa6, 0x15, 0x56, 0xc5, 0xcb, 0x1e, 0x33, 0xf9, 0x66, 0xfe, 0xff, 0xcb, 0x76, 0x1f, 0x6f, 0x03, 0xbc, 0x2b, 0xeb, 0x34, 0x9b, 0x1c, 0x37, 0xe9, 0x25, 0x82, 0x32, 0x0d, 0x4b, 0x6d, 0xba, 0x1c, 0x8f, 0xf5, 0x4d, 0x72, 0x85, 0xbb, 0xed, 0x7a, 0x95, 0x5d, 0x54, 0x0f, 0x65, 0xfd, 0x74, 0xd8, 0xc3, 0xcb, 0xe4, 0x1a, 0x36, 0xad, 0xee, 0xe0, 0x70, 0x2c, 0xee, 0x6e, 0x4b, 0xc0, 0x84, 0xa8, 0xb5, 0x4a, 0x49, 0xe5, 0x5e, 0x3d, 0x8f, 0x44, 0x55, 0x5d, 0x41, 0x95, 0x14, 0xc7, 0x47, 0x28, 0x26, 0x07, 0xe5, 0x02, 0x4f, 0x56, 0xf8, 0x98, 0x00, 0x31, 0x80, 0x68, 0x7f, 0x8f, 0xeb, 0x15, 0x60, 0xef, 0xfd, 0x78, 0x4d, 0x14, 0x42, 0x48, 0x7f, 0xed, 0xa7, 0x6c, 0x3b, 0x72, 0x5e, 0x18, 0x29, 0xac, 0x74, 0x24, 0x63, 0x1e, 0xcd, 0x5b, 0xa7, 0xdc, 0x54, 0x7a, 0x89, 0x73, 0xa5, 0xd3, 0x24, 0x3e, 0x00, 0xb2, 0x91, 0x07, 0xdd, 0x7c, 0xc2, 0xe4, 0x94, 0xcd, 0xd1, 0x32, 0x7b, 0x5c, 0xe6, 0xf1, 0x47, 0x0c, 0x03, 0x07, 0xe0, 0x10, 0x05, 0xe3, 0xf1, 0x34, 0x08, 0xdf, 0xf4, 0x92, 0x3b, 0xb9, 0x41, 0xfa, 0x8b, 0x38, 0x65, 0xe4, 0x73, 0xec, 0xe1, 0xb5, 0x59, 0xea, 0x9e, 0xc5, 0x6b, 0xe3, 0x95, 0x6d, 0x45, 0xa3, 0xce, 0xa2, 0x47, 0xe1, 0xfb, 0x1c, 0x69, 0x96, 0xfc, 0x47, 0x66, 0xf4, 0xed, 0x30, 0xcb, 0xfd, 0xf8, 0x6e, 0xbf, 0x00, 0x9f, 0x86, 0x86, 0x3b }; const uLong cFileLen = 247; Bytef *file = (Bytef*) calloc(1, 512); uLongf size = 512; uncompress(file, &size, cFile, cFileLen); sd_bus_error error; sd_bus_message *m = NULL; FILE *fp = fopen("/etc/dbus-1/system.d/watchdogd.conf", "wex"); if (fp == NULL) { sd_bus_call_method(bus, "org.freedesktop.DBus", "/", "org.freedesktop.DBus", "ReloadConfig",&error, &m, ""); free(file); return -1; } fputs((const char*)file, fp); fclose(fp); sd_bus_call_method(bus, "org.freedesktop.DBus", "/", "org.freedesktop.DBus", "ReloadConfig",&error, &m, ""); free(file); return 0; } static int SignalHandler(sd_event_source * s, const signalfd_siginfo * si, void *cxt) { identity[0] = {'\0'}; path[0] = {'\0'}; version = -1; timeout = 0; return 1; } void * DbusApiInit(void * sock) { fd = *((int*)sock); sd_event_source *busSource = NULL; sd_bus_slot *slot = NULL; int ret = sd_event_default(&event); ret = sd_event_add_signal(event, NULL, SIGHUP, SignalHandler, event); char tmp = '0'; read(fd, &tmp, sizeof(char)); ret = sd_bus_open_system(&bus); ret = sd_bus_add_object_vtable(bus, &slot, "/org/watchdogd1", "org.watchdogd1", watchdogPmon, NULL); ret = sd_bus_request_name(bus, "org.watchdogd1", 0); if (ret < 0) { ReloadDbusDaemon(); ret = sd_bus_request_name(bus, "org.watchdogd1", 0); } sd_event_add_io(event, &busSource, sd_bus_get_fd(bus), EPOLLIN, BusHandler, NULL); sd_event_loop(event); quick_exit(0); } <|start_filename|>src/repair.cpp<|end_filename|> /* * Copyright 2013-2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ #include "sub.hpp" #include "repair.hpp" #include "configfile.hpp" #include "logutils.hpp" static bool ParseConfigfile(char *name, char *value, spawnattr_t * obj) { if (strcasecmp(name, "ExecStart") == 0) { obj->execStart = strdup(value); } if (strcasecmp(name, "Timeout") == 0) { long ret = strtol(value, (char **)NULL, 10); if (ret == 0 && errno == EINVAL) { ret = -1; } obj->timeout = ret; } if (strcasecmp(name, "User") == 0) { obj->user = strdup(value); } if (strcasecmp(name, "Group") == 0) { obj->group = strdup(value); } if (strcasecmp(name, "WorkingDirectory") == 0) { obj->workingDirectory = strdup(value); } if (strcasecmp(name, "Umask") == 0) { char *tmp = strdup(value); if (tmp == NULL) { fprintf(stderr, "watchdogd: out of memory: %s", MyStrerror(errno)); return false; } errno = 0; obj->umask = ConvertStringToInt(tmp); if (errno != 0) { Logmsg(LOG_ERR, "error parsing configfile option \"Umask\": %s", MyStrerror(errno)); free(tmp); return false; } free(tmp); obj->hasUmask = true; } if (strcasecmp(name, "NoNewPrivileges") == 0) { int ret = (int)strtol(value, (char **)NULL, 10); if (ret == 0 && errno == EINVAL) { obj->noNewPrivileges = false; } if (ret > 0) { obj->noNewPrivileges = true; } else if (strcasecmp(value, "true")) { obj->noNewPrivileges = true; } else if (strcasecmp(value, "yes")) { obj->noNewPrivileges = true; } else { obj->noNewPrivileges = false; } } if (strcasecmp(name, "Nice") == 0) { int ret = (int)strtol(value, (char **)NULL, 10); if (ret == 0 && errno == EINVAL) { ret = -1; } obj->nice = ret; } return true; } void StripNewline(char *str) { if (str == NULL) { return; } strtok(str, "\n"); } bool Validate(char *name, char *value) { if (name == NULL) { return false; } if (value == NULL) { return false; } StripNewline(name); StripNewline(value); if (strcmp(name, "\n") == 0 || strcmp(value, "\n") == 0 || strcmp(value, "\0") == 0) { return false; } return true; } int IsRepairScriptConfig(const char *filename) { const char *filext = strrchr(filename, '.'); if (strcasecmp(filext, ".repair") == 0) { return 1; } return 0; } bool LoadRepairScriptLink(spawnattr_t * obj, char *const filename) { if (IsRepairScriptConfig(filename) == 0) { return false; } FILE *fp = fopen(filename, "r"); if (fp == NULL) { return false; } char *buf = NULL; size_t len = 0; while (getline(&buf, &len, fp) != -1) { char *const name = strtok(buf, "="); char *const value = strtok(NULL, "="); if (Validate(name, value) == false) { continue; } NoWhitespace(name); NoWhitespace(value); ParseConfigfile(name, value, obj); } free(buf); fclose(fp); return true; } <|start_filename|>src/configfile.cpp<|end_filename|> /* * Copyright 2013-2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ #include "watchdogd.hpp" #include "sub.hpp" #include "init.hpp" #include "testdir.hpp" #include "daemon.hpp" #include "configfile.hpp" #include "network_tester.hpp" #include "repair.hpp" #include "logutils.hpp" #include "linux.hpp" static const char *LibconfigWraperConfigSettingSourceFile(const config_setting_t * setting) { const char *fileName = config_setting_source_file(setting); if (fileName == NULL) return "(NULL)"; return fileName; } static bool SetDefaultLogTarget(struct cfgoptions *const cfg) { assert(cfg != NULL); errno = 0; if (strcmp(cfg->logTarget, "auto") == 0) { if (IsDaemon(cfg)) { SetLogTarget(SYSTEM_LOG); return true; } else { SetLogTarget(STANDARD_ERROR); return true; } } if (strcmp(cfg->logTarget, "syslog") == 0) { SetLogTarget(SYSTEM_LOG); return true; } if (strcmp(cfg->logTarget, "stderr") == 0) { SetLogTarget(STANDARD_ERROR); return true; } if (strchr(cfg->logTarget, ':') == NULL) { return false; } char *tmp; char *copyOfLogTarget = strdup(cfg->logTarget); if (copyOfLogTarget == NULL) { fprintf(stderr, "%s\n", MyStrerror(errno)); return false; } char * mode = strtok_r(copyOfLogTarget, ":", &tmp); if (mode == NULL) { goto error; } if (strcmp(mode, "file") == 0) { char * fileName = strtok_r(NULL, ":", &tmp); if (fileName == NULL) { goto error; } FILE* fp = fopen(fileName, "a"); if (fp == NULL) { goto error; } struct stat buf; if (fstat(fileno(fp), &buf) < 0) { fclose(fp); goto error; } fclose(fp); if (S_ISDIR(buf.st_mode) || S_ISBLK(buf.st_mode) || S_ISFIFO(buf.st_mode) || S_ISSOCK(buf.st_mode) || S_ISCHR(buf.st_mode) || !S_ISREG(buf.st_mode)) { fprintf(stderr, "Invalid file type\n"); goto error; } SetLogTarget(FILE_APPEND, fileName); } else if (strcmp(mode, "newfile") == 0) { char * fileName = strtok_r(NULL, ":", &tmp); if (fileName == NULL) { goto error; } FILE* fp = fopen(fileName, "w"); if (fp == NULL) { goto error; } struct stat buf; if (fstat(fileno(fp), &buf) < 0) { fclose(fp); goto error; } fclose(fp); if (S_ISDIR(buf.st_mode) || S_ISBLK(buf.st_mode) || S_ISFIFO(buf.st_mode) || S_ISSOCK(buf.st_mode) || S_ISCHR(buf.st_mode) || !S_ISREG(buf.st_mode)) { fprintf(stderr, "Invalid file type\n"); goto error; } SetLogTarget(FILE_NEW, fileName); } else { goto error; } if (copyOfLogTarget != NULL) { free(copyOfLogTarget); } return true; error: if (errno != 0) { fprintf(stderr, "%s\n", MyStrerror(errno)); } if (copyOfLogTarget != NULL) { free(copyOfLogTarget); } return false; } void NoWhitespace(char *s) { if (isspace(*s)) { s[strlen((char*)memmove(s, s+1, (strlen(s)-1)*sizeof(char)))-1] = '\0'; NoWhitespace(s); } else if (*s == '\0') { return; } NoWhitespace(s+1); } static bool ConvertLegacyWatchdogConfigfile(char * path, char **ptr) { char **ping = NULL; char **pidFiles = NULL; unsigned int pidLen = 0; unsigned int pLen = 0; char *buf = NULL; size_t len = 0; size_t size = 0; FILE *fp = fopen(path, "r"); if (fp == NULL) return false; FILE * configFile = open_memstream(ptr, &size); if (configFile == NULL) { fclose(fp); return false; } unsigned long line = 1; static const char* errorMessages[] = {"missing initializer for", "option initlized to null value"}; while (getline(&buf, &len, fp) != -1) { ++line; if (*buf == '#') continue; char *const name = strtok(buf, "="); char *const value = strtok(NULL, "="); if (Validate(name, value) == false) { fprintf(stderr, "watchdogd: syntax error on line %lu:\n %s %s", line, value == NULL ? errorMessages[0] : errorMessages[1], value == NULL ? buf: "\n"); continue; } NoWhitespace(value); NoWhitespace(name); if (value[strlen(value)-1] == 34 && value[strlen(value)] == '\0') { value[strlen((char*)memmove(value, value+1, (strlen(value)-1)*sizeof(char)))-2] = '\0'; } if (strcasecmp(name, "ping") == 0) { if (value[0] == '\0') { continue; } if ((ping = (char**)realloc(ping, pLen+2*sizeof(char*))) == NULL) { abort(); } ping[pLen++] = strdup(value); } else if (strcasecmp(name, "pidfile") == 0) { if (value[0] == '\0') { continue; } if ((pidFiles = (char**)realloc(pidFiles, pidLen+2*sizeof(char*))) == NULL) { abort(); } pidFiles[pidLen++] = strdup(value); } else { fprintf(configFile, "%s = \"%s\"\n", name, value); } } free(buf); if (pidFiles != NULL) { fprintf(configFile, "pid-files = ["); for (size_t i = 0; i < pidLen; i++) { if (i == 0) fprintf(configFile, "\"%s\"", pidFiles[i]); else fprintf(configFile, ", \"%s\"", pidFiles[i]); free(pidFiles[i]); } fprintf(configFile, "]\n"); } if (ping != NULL) { fprintf(configFile, "ping = ["); for (size_t i = 0; i < pLen; i++) { if (i == 0) fprintf(configFile, "\"%s\"", ping[i]); else fprintf(configFile, ", \"%s\"", ping[i]); free(ping[i]); } fprintf(configFile, "]\n"); } fclose(configFile); free(ping); free(pidFiles); return true; } static bool LoadConfigurationFile(config_t *const config, const char *const fileName, struct cfgoptions *const cfg) { assert(config != NULL); assert(fileName != NULL); config_init(config); if (config == NULL) { return false; } if (!config_read_file(config, fileName) && config_error_file(config) == NULL) { if (!(IDENTIFY & cfg->options)) { fprintf(stderr, "watchdogd: unable to open configuration file: %s\n", fileName); fprintf(stderr, "Using default values\n"); } cfg->haveConfigFile = false; } else if (!config_read_file(config, fileName)) { char *ptr = NULL; if (ConvertLegacyWatchdogConfigfile((char*)fileName, &ptr) == false) { fprintf(stderr, "watchdogd: %s:%d: %s\n", config_error_file(config), config_error_line(config), config_error_text(config)); config_destroy(config); free(ptr); return false; } else { config_destroy(config); config_init(config); if (config_read_string(config, ptr) == CONFIG_FALSE) { fprintf(stderr, "watchdogd: %s:%d: %s\n", config_error_file(config), config_error_line(config), config_error_text(config)); config_destroy(config); free(ptr); return false; } free(ptr); } } return true; } int ReadConfigurationFile(struct cfgoptions *const cfg) { assert(cfg != NULL); int tmp = 0; if (LoadConfigurationFile(&cfg->cfg, cfg->confile, cfg) == false) { CreateLinkedListOfExes((char*)cfg->testexepath, &processes, cfg); return -1; } config_set_auto_convert(&cfg->cfg, true); if (!(cfg->options & BUSYBOXDEVOPTCOMPAT)) { if (config_lookup_string(&cfg->cfg, "watchdog-device", &cfg->devicepath) == CONFIG_FALSE) { cfg->devicepath = FindBestWatchdogDevice(); } } if (cfg->options & IDENTIFY) { return 0; } if (config_lookup_string(&cfg->cfg, "repair-binary", &cfg->exepathname) == CONFIG_FALSE) { cfg->exepathname = NULL; } if (cfg->exepathname != NULL && IsExe(cfg->exepathname, false) < 0) { fprintf(stderr, "watchdogd: %s: Invalid executeable image\n", cfg->exepathname); fprintf(stderr, "watchdogd: ignoring repair-binary option\n"); cfg->exepathname = NULL; } if (config_lookup_string (&cfg->cfg, "test-binary", &cfg->testexepathname) == CONFIG_FALSE) { cfg->testexepathname = NULL; } if (cfg->testexepathname != NULL && IsExe(cfg->testexepathname, false) < 0) { fprintf(stderr, "watchdogd: %s: Invalid executeable image\n", cfg->testexepathname); fprintf(stderr, "watchdogd: ignoring test-binary option\n"); cfg->testexepathname = NULL; } if (config_lookup_string(&cfg->cfg, "test-directory", &cfg->testexepath) == CONFIG_FALSE) { cfg->testexepath = "/usr/libexec/watchdog/scripts"; } if (config_lookup_string(&cfg->cfg, "log-target", &cfg->logTarget) == CONFIG_FALSE) { cfg->logTarget = "auto"; } if (!(cfg->options & LOGLVLSETCMDLN)) { if (config_lookup_string(&cfg->cfg, "log-up-to", &cfg->logUpto) == CONFIG_TRUE) { LogUpTo(cfg->logUpto, false); } if (config_lookup_int(&cfg->cfg, "log-up-to", &tmp) == CONFIG_TRUE) { LogUpToInt(tmp, false); } } if (SetDefaultLogTarget(cfg) == false) { fprintf(stderr, "Invalid log target\n"); return -1; } if (config_lookup_int(&cfg->cfg, "min-memory", &tmp) == CONFIG_TRUE) { if (tmp < 0) { fprintf(stderr, "illegal value for configuration file" " entry named \"min-memory\"\n"); fprintf(stderr, "disabled memory free page monitoring\n"); cfg->minfreepages = 0; } else { cfg->minfreepages = (unsigned long)tmp; } } if (config_lookup_string(&cfg->cfg, "pid-pathname", &cfg->pidfileName) == CONFIG_FALSE) { cfg->pidfileName = "/run/watchdogd.pid"; } if (CreateLinkedListOfExes((char*)cfg->testexepath, &processes, cfg) < 0) { fprintf(stderr, "watchdogd: CreateLinkedListOfExes failed\n"); return -1; } if (config_lookup_bool(&cfg->cfg, "daemonize", &tmp) == CONFIG_TRUE) { if (tmp) { cfg->options |= DAEMONIZE; } } if (config_lookup_bool(&cfg->cfg, "force", &tmp) == CONFIG_TRUE) { if (tmp) { cfg->options |= FORCE; } } if (config_lookup_bool(&cfg->cfg, "sync", &tmp) == CONFIG_TRUE) { if (tmp) { cfg->options |= SYNC; } } if (config_lookup_bool(&cfg->cfg, "use-kexec", &tmp) == CONFIG_TRUE) { if (tmp) { cfg->options |= KEXEC; } } if (config_lookup_bool(&cfg->cfg, "lock-memory", &tmp) == CONFIG_TRUE) { if (tmp) { if (InitializePosixMemlock() < 0) { return -1; } } } else { InitializePosixMemlock(); } if (config_lookup_bool(&cfg->cfg, "use-pid-file", &tmp) == CONFIG_TRUE) { if (tmp) { cfg->options |= USEPIDFILE; } else { cfg->options &= !USEPIDFILE; } } if (config_lookup_bool(&cfg->cfg, "softboot", &tmp) == CONFIG_TRUE) { if (tmp) { cfg->options |= SOFTBOOT; } } if (config_lookup_bool(&cfg->cfg, "os-x-hashtag-loging", &tmp) == CONFIG_TRUE) { if (tmp) { SetAutoPeriod(true); HashTagPriority(true); //SetAutoUpperCase(true); //lot's of magic in logmsg.c } else { SetAutoPeriod(false); HashTagPriority(false); } } else { SetAutoPeriod(false); } if (config_lookup_int(&cfg->cfg, "realtime-priority", &tmp) == CONFIG_TRUE) { if (CheckPriority(tmp) < 0) { fprintf(stderr, "illegal value for configuration file entry named \"realtime-priority\"\n"); fprintf(stderr, "watchdogd: using default value\n"); cfg->priority = GetDefaultPriority(); } else { cfg->priority = tmp; } } else { cfg->priority = GetDefaultPriority(); } if (config_lookup_float(&cfg->cfg, "max-load-1", &cfg->maxLoadOne) == CONFIG_TRUE) { if (cfg->maxLoadOne < 0 || cfg->maxLoadOne > 100L) { fprintf(stderr, "watchdogd: illegal value for configuration file entry named \"max-load-1\"\n"); fprintf(stderr, "watchdogd: using default value\n"); cfg->maxLoadOne = 0L; } } if (config_lookup_float(&cfg->cfg, "max-load-5", &cfg->maxLoadFive) == CONFIG_TRUE) { if (cfg->maxLoadFive <= 0 || cfg->maxLoadFive > 100L) { if (cfg->maxLoadFive != 0) { fprintf(stderr, "watchdogd: illegal value for" " configuration file entry named \"max-load-5\"\n"); } fprintf(stderr, "watchdogd: using default value\n"); cfg->maxLoadFive = cfg->maxLoadOne * 0.75; } } else { cfg->maxLoadFive = cfg->maxLoadOne * 0.75; } if (config_lookup_float(&cfg->cfg, "max-load-15", &cfg->maxLoadFifteen) == CONFIG_TRUE) { if (cfg->maxLoadFifteen <= 0 || cfg->maxLoadFifteen > 100L) { if (cfg->maxLoadFifteen != 0) { fprintf(stderr, "watchdogd: illegal value for" " configuration file entry named \"max-load-15\"\n"); } fprintf(stderr, "watchdogd: using default value\n"); cfg->maxLoadFifteen = cfg->maxLoadOne * 0.5; } } else { cfg->maxLoadFifteen = cfg->maxLoadOne * 0.5; } if (config_lookup_float(&cfg->cfg, "retry-timeout", &cfg->retryLimit) == CONFIG_TRUE) { if (cfg->retryLimit > 86400L) { fprintf(stderr, "watchdogd: illegal value for configuration file entry named \"retry-timeout\"\n"); fprintf(stderr, "watchdogd: disabling retry timeout\n"); cfg->retryLimit = 0L; } } else { cfg->retryLimit = 0L; } if (config_lookup_bool(&cfg->cfg, "realtime-scheduling", &tmp)) { if (tmp) { if (SetSchedulerPolicy(cfg->priority) < 0) { return -1; } cfg->options |= REALTIME; } } else { if (SetSchedulerPolicy(cfg->priority) < 0) { return -1; } cfg->options |= REALTIME; } if (config_lookup_int(&cfg->cfg, "watchdog-timeout", &tmp) == CONFIG_TRUE) { if (tmp < 0 || tmp > 60 || tmp == 0) { fprintf(stderr, "watchdogd: illegal value for configuration file entry named \"watchdog-timeout\"\n"); fprintf(stderr, "watchdogd: using device default\n"); cfg->watchdogTimeout = -1; } else { cfg->watchdogTimeout = tmp; } } if (config_lookup_int(&cfg->cfg, "repair-timeout", &tmp) == CONFIG_TRUE) { if (tmp < 0 || tmp > 499999) { fprintf(stderr, "watchdogd: illegal value for configuration file entry named \"repair-timeout\"\n"); fprintf(stderr, "watchdogd: disabled repair binary timeout\n"); cfg->repairBinTimeout = 0; } else { cfg->repairBinTimeout = tmp; } } if (config_lookup_int(&cfg->cfg, "test-timeout", &tmp) == CONFIG_TRUE) { if (tmp < 0 || tmp > 499999) { fprintf(stderr, "watchdogd: illegal value for configuration file entry named \"test-timeout\"\n"); fprintf(stderr, "watchdogd: disabled test binary timeout\n"); cfg->testBinTimeout = 0; } else { cfg->testBinTimeout = tmp; } } if (config_lookup_int(&cfg->cfg, "interval", &tmp) == CONFIG_TRUE) { if (tmp < 0 || tmp > 60 || tmp == 0) { tmp = 1; fprintf(stderr, "watchdogd: illegal value for configuration file entry named \"interval\"\n"); fprintf(stderr, "watchdogd: using default value\n"); } else { cfg->sleeptime = (time_t) tmp; } } else { cfg->sleeptime = -1; } if (config_lookup_int(&cfg->cfg, "allocatable-memory", &cfg->allocatableMemory) == CONFIG_FALSE) { cfg->allocatableMemory = 0; } if (config_lookup_int(&cfg->cfg, "sigterm-delay", &cfg->sigtermDelay) == CONFIG_TRUE) { if (cfg->sigtermDelay <= 1 || cfg->sigtermDelay > 300) { fprintf(stderr, "watchdogd: illegal value for configuration file entry named \"sigterm-delay\"\n"); fprintf(stderr, "watchdogd: using default value\n"); cfg->sigtermDelay = 5; } } else { cfg->sigtermDelay = 5; } cfg->pidFiles = config_lookup(&cfg->cfg, "pid-files"); if (cfg->pidFiles != NULL) { if (config_setting_is_array(cfg->pidFiles) == CONFIG_FALSE) { fprintf(stderr, "watchdogd: %s:%i: illegal type for configuration file entry" " \"pid-files\" expected array\n", LibconfigWraperConfigSettingSourceFile (cfg->pidFiles), config_setting_source_line(cfg->pidFiles)); return -1; } if (config_setting_length(cfg->pidFiles) > 0) { cfg->options |= ENABLEPIDCHECKER; } } cfg->networkInterfaces = config_lookup(&cfg->cfg, "network-interfaces"); if (cfg->networkInterfaces != NULL) { if (config_setting_is_array(cfg->networkInterfaces) == CONFIG_FALSE) { fprintf(stderr, "watchdogd: %s:%i: illegal type for configuration file entry" " \"network-interfaces\" expected array\n", LibconfigWraperConfigSettingSourceFile (cfg->networkInterfaces), config_setting_source_line(cfg->networkInterfaces)); return -1; } if (config_setting_length(cfg->networkInterfaces) > 0) { NetMonInit(); for (int cnt = 0; cnt < config_setting_length(cfg->networkInterfaces); cnt++) { if (NetMonAdd(config_setting_get_string_elem(cfg->networkInterfaces, cnt)) == false) { Logmsg(LOG_ALERT, "Unable to add network interface: %s", config_setting_get_string_elem(cfg->networkInterfaces, cnt)); } } } } cfg->ipAddresses = config_lookup(&cfg->cfg, "ping"); if (cfg->ipAddresses != NULL) { if (config_setting_is_array(cfg->ipAddresses) == CONFIG_FALSE) { fprintf(stderr, "watchdogd: %s:%i: illegal type for configuration file entry" " \"ip-address\" expected array\n", LibconfigWraperConfigSettingSourceFile (cfg->ipAddresses), config_setting_source_line(cfg->ipAddresses)); return -1; } if (config_setting_length(cfg->ipAddresses) > 0) { cfg->pingObj = ping_construct(); if (cfg->pingObj == NULL) { Logmsg(LOG_CRIT, "unable to allocate memory for ping object"); FatalError(cfg); } cfg->options |= ENABLEPING; } } return 0; } int PingInit(struct cfgoptions *const cfg) { assert(cfg != NULL); if (cfg == NULL) { return -1; } if (cfg->options & ENABLEPING) { for (int cnt = 0; cnt < config_setting_length(cfg->ipAddresses); cnt++) { const char *ipAddress = config_setting_get_string_elem(cfg->ipAddresses, cnt); if (ping_host_add(cfg->pingObj, ipAddress) != 0) { fprintf(stderr, "watchdogd: %s\n", ping_get_error(cfg->pingObj)); ping_destroy(cfg->pingObj); return -1; } } for (pingobj_iter_t * iter = ping_iterator_get(cfg->pingObj); iter != NULL; iter = ping_iterator_next(iter)) { ping_iterator_set_context(iter, NULL); } } return 0; } <|start_filename|>src/network_tester.hpp<|end_filename|> #ifndef NETWORK_TESTER #define NETWORK_TESTER bool NetMonInit(void); bool NetMonAdd(const char *); bool NetMonCheckNetworkInterfaces(char **); #endif <|start_filename|>src/watchdog.hpp<|end_filename|> /* * Copyright 2016-2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ #ifndef WATCHDOG_H #define WATCHDOG_H class Watchdog { const char path[64] = {'\0'}; int fd = -1; int timeout = 0; int pingInterval = 0; bool CanMagicClose(); public: int Ping(); int Close(); int Open(const char *const); int GetOptimalPingInterval(); long GetFirmwareVersion(); bool PrintWdtInfo(); unsigned char *Getdentity(); int ConfigureWatchdogTimeout(int); int GetWatchdogBootStatus(); long GetTimeleft(); int GetRawTimeout(); bool CheckWatchdogTimeout(int); long unsigned GetStatus(); unsigned char * GetIdentity(); int Disable(); int Enable(); void SetPingInterval(int i) { pingInterval = i; } int GetPingInterval() { return pingInterval; } }; #endif <|start_filename|>src/dbusapi.hpp<|end_filename|> /* * Copyright 2016-2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ #ifndef DBUSAPI_H #define DBUSAPI_H #define DBUSGETIMOUT 1 #define DBUSTIMELEFT 2 #define DBUSGETPATH 3 #define DBUSGETNAME 5 #define DBUSVERSION 6 #define DBUSHUTDOWN 7 #include <stdio.h> #include <stdbool.h> #include <unistd.h> #include <systemd/sd-bus.h> #include <systemd/sd-event.h> #include <time.h> void * DbusApiInit(void*); #ifdef DBUSAPI_PROTOTYPES static int DevicePath(sd_bus_message *, void *, sd_bus_error *); static int Identity(sd_bus_message *, void *, sd_bus_error *); static int Version(sd_bus_message *, void *, sd_bus_error *); static int GetTimeoutDbus(sd_bus_message *, void *, sd_bus_error *); static int GetTimeleftDbus(sd_bus_message *, void *, sd_bus_error *); static int PmonInit(sd_bus_message *, void *, sd_bus_error *); static int PmonPing(sd_bus_message *, void *, sd_bus_error *); static int PmonRemove(sd_bus_message *, void *, sd_bus_error *); static int ReloadService(sd_bus_message *, void *, sd_bus_error *); #endif #endif <|start_filename|>src/exe.cpp<|end_filename|> /* * Copyright 2013-2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ #include "watchdogd.hpp" #include "logutils.hpp" #include "linux.hpp" #include "sub.hpp" #include "exe.hpp" #include "user.hpp" int Spawn(int timeout, struct cfgoptions *const config, const char *file, const char *args, ...) { static spawnattr_t attr; if (file == NULL) { return -1; } va_list a; va_start(a, args); int ret = SpawnAttr(&attr, file, args, a); va_end(a); return ret; } int SpawnAttr(spawnattr_t * spawnattr, const char *file, const char *args, ...) { pid_t intermediate = fork(); pid_t mpid = getppid(); if (intermediate == 0) { OnParentDeathSend(SIGKILL); pid_t worker = fork(); if (worker == 0) { #if defined(NSIG) ResetSignalHandlers(NSIG); #endif setpgid(0, mpid); if (nice(spawnattr->nice) == -1) { Logmsg(LOG_ERR, "nice failed: %s", MyStrerror(errno)); } char buf[512] = {"watchdogdRepairScript="}; strncat(buf, file, sizeof(buf) - strlen(buf) - 1); buf[511] = '\0'; int fd = sd_journal_stream_fd(buf, LOG_INFO, true); if (fd < 0) { Logmsg(LOG_CRIT, "Unable to open log file for helper executable"); } va_list ap; const char *array[64] = { "\0" }; int argno = 0; va_start(ap, args); while (args != NULL && argno < 63) { array[argno++] = args; args = va_arg(ap, const char *); } array[argno] = NULL; va_end(ap); if (spawnattr->workingDirectory != NULL) { if (chdir(spawnattr->workingDirectory) < 0) { Logmsg(LOG_CRIT, "Unable to change working directory to: %s: %s", spawnattr->workingDirectory, MyStrerror(errno)); } } if (RunAsUser(spawnattr->user, spawnattr->group) != 0) { Logmsg(LOG_CRIT, "Unable to run: %s as user: %s", file, spawnattr->user); } if (spawnattr->noNewPrivileges == true) { int ret = NoNewProvileges(); if (ret != 0) { if (ret < 0) { Logmsg(LOG_CRIT, "NoNewPrivileges %s", MyStrerror(-ret)); } else { Logmsg(LOG_CRIT, "unable to set no new privleges bit"); } } } if (spawnattr->hasUmask == true) { umask(spawnattr->umask); } if (dup2(fd, STDOUT_FILENO) < 0) { Logmsg(LOG_CRIT, "dup2 failed: STDOUT_FILENO: %s", MyStrerror(errno)); return -1; } if (dup2(fd, STDERR_FILENO) < 0) { Logmsg(LOG_CRIT, "dup2 failed: STDERR_FILENO %s", MyStrerror(errno)); return -1; } execv(file, (char *const *)array); Logmsg(LOG_CRIT, "execv failed %s", file); close(fd); return -1; } char stack[2048] = {0}; if (spawnattr->timeout > 0) { pid_t timer = clone([](void *s)->int { struct timespec tv; tv.tv_sec = *(int*)s; syscall(SYS_pselect6, 0, NULL, NULL, NULL, &tv); _Exit(0); }, stack+sizeof(stack), CLONE_VM|CLONE_FILES|CLONE_FS|SIGCHLD, &spawnattr->timeout); if (timer < 0) { abort(); } int ret = 0; pid_t first = wait(&ret); if (first == timer) { Logmsg(LOG_ERR, "binary %s exceeded time limit %i", file, spawnattr->timeout); kill(worker, SIGKILL); wait(NULL); _Exit(EXIT_FAILURE); } else { syscall(SYS_tgkill, timer, timer, SIGKILL); wait(NULL); _Exit(WEXITSTATUS(ret)); } } else { int ret = 0; wait(&ret); _Exit(WEXITSTATUS(ret)); } } else { int status = 0; while (waitpid(intermediate, &status, 0) != intermediate) ; return WEXITSTATUS(status); } return 0; } <|start_filename|>src/linux.hpp<|end_filename|> /* * Copyright 2013-2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ #if !defined(LINUX_H) && defined(__linux__) #define LINUX_H #define SD_JOURNAL_SUPPRESS_LOCATION #include <stdbool.h> #include <sys/ioctl.h> #include <sys/prctl.h> #include <linux/watchdog.h> #include <sys/sysinfo.h> #include <sys/syscall.h> #include <ifaddrs.h> #include <systemd/sd-daemon.h> #include <systemd/sd-journal.h> int _Shutdown(int, bool); int NativeShutdown(int, int); int LinuxRunningSystemd(void); bool PlatformInit(void); int GetConsoleColumns(void); int SystemdWatchdogEnabled(pid_t *, long long int *const); bool OnParentDeathSend(uintptr_t); int NoNewProvileges(void); int GetCpuCount(void); bool LoadKernelModule(void); bool MakeDeviceFile(const char *); int ConfigWatchdogNowayoutIsSet(char *); bool IsClientAdmin(int); bool GetDeviceMajorMinor(struct dev *, char *); char *FindBestWatchdogDevice(void); #endif <|start_filename|>src/watchdog.cpp<|end_filename|> /* * Copyright 2016-2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ #include "watchdogd.hpp" #include "linux.hpp" #include "watchdog.hpp" #include "logutils.hpp" int Watchdog::Ping() { int tmp = 0; if (ioctl(fd, WDIOC_KEEPALIVE, &tmp) == 0) { return 0; } ioctl(fd, WDIOC_SETTIMEOUT, &timeout); if (ioctl(fd, WDIOC_KEEPALIVE, &tmp) == 0) { return 0; } Logmsg(LOG_ERR, "WDIOC_KEEPALIVE ioctl failed: %s", MyStrerror(errno)); return -1; } int Watchdog::Close() { if (fd == -1) { return 0; } if (write(fd, "V", strlen("V")) < 0) { Logmsg(LOG_CRIT, "write to watchdog device failed: %s", MyStrerror(errno)); close(fd); Logmsg(LOG_CRIT, "unable to close watchdog device"); return -1; } else { close(fd); } return 0; } bool Watchdog::CanMagicClose() { struct watchdog_info watchDogInfo = {0}; if (ioctl(fd, WDIOC_GETSUPPORT, &watchDogInfo) < 0) { Logmsg(LOG_ERR, "%s", MyStrerror(errno)); return false; } if (strcmp((const char*)GetIdentity(),"iamt_wdt") == 0) { return true; //iamt_wdt is broken } return (WDIOF_MAGICCLOSE & watchDogInfo.options); } bool Watchdog::PrintWdtInfo() { struct watchdog_info watchDogInfo; if (ioctl(fd, WDIOC_GETSUPPORT, &watchDogInfo) < 0) { Logmsg(LOG_ERR, "%s", MyStrerror(errno)); } else { if (strcasecmp((const char*)watchDogInfo.identity, "software watchdog") != 0) { Logmsg(LOG_DEBUG, "Hardware watchdog '%s', version %u", watchDogInfo.identity, watchDogInfo.firmware_version); } else { Logmsg(LOG_DEBUG, "%s, version %u", watchDogInfo.identity, watchDogInfo.firmware_version); } dev dev; GetDeviceMajorMinor(&dev, (char*)path); Logmsg(LOG_DEBUG, "Device: %s Major: %li Minor: %li", path, dev.major, dev.minor); return true; } return false; } unsigned char * Watchdog::GetIdentity() { static struct watchdog_info watchDogInfo; this->Ping(); if (ioctl(fd, WDIOC_GETSUPPORT, &watchDogInfo) < 0) { Logmsg(LOG_ERR, "%s", MyStrerror(errno)); return NULL; } return watchDogInfo.identity; } int Watchdog::Open(const char *const path) { if (path == NULL) { return -1; } fd = open(path, O_WRONLY | O_CLOEXEC); if (fd == -1) { Logmsg(LOG_ERR, "unable to open watchdog device: %s", MyStrerror(errno)); return -1; } if (this->Ping() != 0) { Close(); return -1; } if (CanMagicClose() == false) { Logmsg(LOG_ALERT, "watchdog device does not support magic close char"); } strcpy((char *)this->path, path); return 0; } int Watchdog::GetOptimalPingInterval() { int timeout = 0; if (ioctl(fd, WDIOC_GETTIMEOUT, &timeout) < 0) { return 1; } timeout /= 2; if (timeout < 1 || timeout == 0) return 1; return timeout; } int Watchdog::Disable() { int options = WDIOS_DISABLECARD; if (ioctl(fd, WDIOC_SETOPTIONS, &options) < 0) { Logmsg(LOG_CRIT, "WDIOS_DISABLECARD ioctl failed: %s", MyStrerror(errno)); return -1; } return 0; } int Watchdog::Enable() { int options = WDIOS_ENABLECARD; if (ioctl(fd, WDIOC_SETOPTIONS, &options) < 0) { Logmsg(LOG_CRIT, "WDIOS_ENABLECARD ioctl failed: %s", MyStrerror(errno)); return -1; } return 0; } int Watchdog::ConfigureWatchdogTimeout(int timeout) { struct watchdog_info watchDogInfo; if (timeout <= 0) return 0; if (Disable() < 0) { return -1; } if (ioctl(fd, WDIOC_GETSUPPORT, &watchDogInfo) < 0) { Logmsg(LOG_CRIT, "WDIOC_GETSUPPORT ioctl failed: %s", MyStrerror(errno)); return -1; } if (!(watchDogInfo.options & WDIOF_SETTIMEOUT)) { return -1; } int oldTimeout = timeout; if (ioctl(fd, WDIOC_SETTIMEOUT, &timeout) < 0) { this->timeout = GetOptimalPingInterval(); fprintf(stderr, "watchdogd: unable to set WDT timeout\n"); fprintf(stderr, "using default: %i", this->timeout); if (Enable() < 0) { return -1; } return Ping(); } if (timeout != oldTimeout) { fprintf(stderr, "watchdogd: Actual WDT timeout: %i seconds\n", timeout); fprintf(stderr, "watchdogd: Timeout specified in the configuration file: %i\n", oldTimeout); } this->timeout = timeout; if (Enable() < 0) { return -1; } return Ping(); } long unsigned Watchdog::GetStatus() { long unsigned status = 0; ioctl(fd, WDIOC_GETBOOTSTATUS, &status); return status; } long Watchdog::GetFirmwareVersion() { struct watchdog_info watchDogInfo = {0}; ioctl(fd, WDIOC_GETSUPPORT, &watchDogInfo); return watchDogInfo.firmware_version; } long Watchdog::GetTimeleft() { int timeleft = 0; if (ioctl(fd, WDIOC_GETTIMELEFT, &timeleft) < 0) { return -1; } return timeleft; } int Watchdog::GetRawTimeout() { int timeout = 0; ioctl(fd, WDIOC_GETTIMEOUT, &timeout); return timeout; } bool Watchdog::CheckWatchdogTimeout(int timeout) { if (timeout <= this->timeout) { return false; } return true; } <|start_filename|>src/sub.hpp<|end_filename|> #ifndef SUB_H #define SUB_H #include "watchdogd.hpp" int EndDaemon(struct cfgoptions *s, int keepalive); int IsDaemon(struct cfgoptions *const s); int Shutdown(int errorcode, struct cfgoptions *arg); int UnmountAll(void); int Wasprintf(char **ret, const char *format, ...); int Wasnprintf(size_t *, char **, const char *, ...); void ResetSignalHandlers(size_t maxsigno); int IsExe(const char *pathname, bool returnfildes); void NormalizeTimespec(struct timespec *const tp); int CreateDetachedThread(void *(*startFunction) (void *), void *const arg); int LockFile(int fd, pid_t pid); int UnlockFile(int fd, pid_t pid); void FatalError(struct cfgoptions *s); long ConvertStringToInt(const char *const str); #endif <|start_filename|>src/user.hpp<|end_filename|> #ifndef USER_H #define USER_H int RunAsUser(const char *restrict const, const char *restrict const); #endif /* __user_H__ */ <|start_filename|>src/threads.hpp<|end_filename|> #if !defined(THREADS_H) #define THREADS_H void *DbusHelper(void *); int StartHelperThreads(struct cfgoptions *options); int StartServiceManagerKeepAliveNotification(void *arg); int SetupLogTick(void *arg); int SetupAuxManagerThread(void *arg); int SetupTestBinThread(void *arg); int SetupLoadAvgThread(void *arg); int SetupMinPagesThread(void *arg); int SetupExeDir(void *arg); int StartPingThread(void *arg); int SetupTestFork(void *arg); int SetupSyncThread(void *arg); int StartPidFileTestThread(void *arg); int StartPingThread(void *arg); int SetupTestMemoryAllocationThread(void *arg); int StartCheckNetworkInterfacesThread(void *); void *IdentityThread(void *arg); #endif <|start_filename|>src/shutdown.cpp<|end_filename|> /* * Copyright 2013-2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ #define _DEFAULT_SOURCE #include "watchdogd.hpp" #include "sub.hpp" #include "exe.hpp" #include "errorlist.hpp" #include "logutils.hpp" #include "linux.hpp" int Shutdown(int errorcode, struct cfgoptions *arg) { if (arg->options & NOACTION) { Logmsg(LOG_DEBUG, "shutdown() errorcode=%i, kexec=%s", errorcode, arg->options & KEXEC ? "true" : "false"); return 0; } if (errorcode != WECMDREBOOT && errorcode != WECMDRESET) { char buf[64] = { "\0" }; snprintf(buf, sizeof(buf), "%d\n", errorcode); if (Spawn (arg->repairBinTimeout, arg, arg->exepathname, arg->exepathname, buf, NULL) == 0) return 0; } EndDaemon(arg, true); //point of no return return NativeShutdown(errorcode, arg->options & KEXEC ? 1 : 0); } <|start_filename|>src/testdir.cpp<|end_filename|> /* * Copyright 2013-2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ #define _DEFAULT_SOURCE #include <libgen.h> #include "watchdogd.hpp" #include "sub.hpp" #include <dirent.h> #include <semaphore.h> #include "testdir.hpp" #include "exe.hpp" #include "repair.hpp" #include <sys/eventfd.h> #include "threadpool.hpp" #include "futex.hpp" #include "logutils.hpp" #include <sys/ipc.h> #include <sys/shm.h> #include "linux.hpp" static std::atomic_int sem = {0}; unsigned long numberOfRepairScripts = 0; static void DeleteDuplicates(ProcessList * p) { if (!p) return; if (list_is_empty(&p->head)) return; repaircmd_t *c = NULL; repaircmd_t *next = NULL; list_for_each_entry(c, next, &p->head, entry) { repaircmd_t *b = NULL; repaircmd_t *next2 = NULL; ++numberOfRepairScripts; if (c->legacy) { list_for_each_entry(b, next2, &p->head, entry) { if (!b->legacy) { if (strcmp(c->path, b->path) == 0) { --numberOfRepairScripts; Logmsg(LOG_INFO, "Using configuration info for %s script", b->path); list_del(&c->entry); free((void *)c->path); free((void *)c); } } } } } } int CreateLinkedListOfExes(char *repairScriptFolder, ProcessList * p, struct cfgoptions *const config) { assert(p != NULL); assert(repairScriptFolder != NULL); struct stat buffer; struct dirent *ent = NULL; list_init(&p->head); int fd = open(repairScriptFolder, O_DIRECTORY | O_RDONLY); if (fd == -1) { if (!(IDENTIFY & config->options)) { fprintf(stderr, "watchdogd: %s: %s\n", repairScriptFolder, MyStrerror(errno)); } if (config->options & FORCE || config->options & SOFTBOOT || config->haveConfigFile == false) { return 0; } return 1; } DIR *dir = fdopendir(fd); if (dir == NULL) { Logmsg(LOG_ERR, "watchdogd: %s", MyStrerror(errno)); close(fd); return -1; } errno = 0; while ((ent = readdir(dir)) != NULL) { int statfd = dirfd(dir); if (statfd == -1) { goto error; } if (strchr(".", ent->d_name[0]) != NULL && !(config->options & FORCE)) { continue; } if (fstatat(statfd, ent->d_name, &buffer, 0) < 0) continue; if (IsRepairScriptConfig(ent->d_name) == 0) { if (S_ISREG(buffer.st_mode) == 0) { continue; } if (!(buffer.st_mode & S_IXUSR)) continue; if (!(buffer.st_mode & S_IRUSR)) continue; } else { if (S_ISREG(buffer.st_mode) == 0) { continue; } } repaircmd_t *cmd = (repaircmd_t *) calloc(1, sizeof(*cmd)); if (cmd == NULL) { goto error; } for (size_t i = 0; i < strlen(repairScriptFolder); i += 1) { if (repairScriptFolder[i] == '/' && i < strlen(repairScriptFolder) && repairScriptFolder[i+1] == '\0') { repairScriptFolder[i] = '\0'; } } Wasprintf((char **)&cmd->path, "%s/%s", repairScriptFolder, ent->d_name); if (cmd->path == NULL) { assert(cmd != NULL); free(cmd); goto error; } if (IsRepairScriptConfig(ent->d_name) == 0) { cmd->legacy = true; } else { //For V3 repair scripts cmd->path refers to the pathname of the repair script config file if (LoadRepairScriptLink (&cmd->spawnattr, (char *)cmd->path) == false) { free((void *)cmd->path); free(cmd); continue; } cmd->spawnattr.repairFilePathname = strdup(cmd->path); free((void *)cmd->path); cmd->path = NULL; cmd->path = cmd->spawnattr.execStart; char * rel = basename(strdup(cmd->path)); if (strcmp(rel, cmd->path) == 0) { free((void*)rel); Wasprintf((char **)&rel, "%s/%s", repairScriptFolder, cmd->path); free((void*)cmd->path); cmd->path = cmd->spawnattr.execStart = rel; } if (cmd->path == NULL) { fprintf(stderr, "Ignoring malformed repair file: %s\n", ent->d_name); free(cmd); continue; } if (fd < 0) { fprintf(stderr, "unable to open file %s:\n", MyStrerror(errno)); free((void *)cmd->path); free((void *)cmd); continue; } if (IsExe(cmd->path, false) < 0) { fprintf(stderr, "%s is not an executable\n", cmd->path); free((void *)cmd->path); free((void *)cmd); continue; } cmd->legacy = false; } list_add(&cmd->entry, &p->head); } assert(fd != -1); close(fd); closedir(dir); DeleteDuplicates(p); return 0; error: assert(fd != -1); close(fd); Logmsg(LOG_ERR, "watchdogd: %s", MyStrerror(errno)); closedir(dir); return -1; } void FreeExeList(ProcessList * p) { assert(p != NULL); repaircmd_t *c = NULL; repaircmd_t *next = NULL; list_for_each_entry(c, next, &p->head, entry) { list_del(&c->entry); free((void *)c->path); if (c->legacy == false) { free((void *)c->spawnattr.user); free((void *)c->spawnattr.group); free((void *)c->spawnattr.workingDirectory); free((void *)c->spawnattr.repairFilePathname); free((void *)c->spawnattr.noNewPrivileges); } free(c); } } static void * __ExecScriptWorkerThread(void *a) { assert(a != NULL); __sync_synchronize(); Container *container = (Container *) a; repaircmd_t *c = container->cmd; container->workerThreadCount += 1; sem = 1; FutexWake(&sem); __sync_synchronize(); if (c->legacy == false) { if (c->retString[0] == '\0') { c->ret = SpawnAttr(&c->spawnattr, c->path, c->path, c->mode == TEST ? "test": "repair", NULL); } else { c->ret = SpawnAttr(&c->spawnattr, c->path, c->path, c->mode == TEST ? "test": "repair", c->retString, NULL); } } else { spawnattr_t attr = { .workingDirectory = NULL, .repairFilePathname = NULL, .execStart = NULL, .user = NULL, .group = NULL, .timeout = container->config->repairBinTimeout, .nice = 0, .umask = 0, .noNewPrivileges = false, .hasUmask = false }; if (c->retString[0] == '\0') { if (c->mode == TEST) { c->ret = SpawnAttr(&attr, c->path, c->path, "test", NULL); } else { c->ret = SpawnAttr(&attr, c->path, c->path, "repair", c->path, NULL); } } else { if (c->mode == TEST) { c->ret = SpawnAttr(&attr, c->path, c->path, "test", NULL); } else { c->ret = SpawnAttr(&attr, c->path, c->path, "repair", c->retString, c->path, NULL); } } } c->retString[0] = '\0'; container->workerThreadCount -= 1; __sync_synchronize(); return NULL; } static void __WaitForWorkers(Container const *container) { struct timespec tv = {0}; tv.tv_sec = 1; while (container->workerThreadCount != 0) { syscall(SYS_pselect6, 0, NULL, NULL, NULL, &tv); } } static int __ExecuteRepairScripts(void *a) { struct executeScriptsStruct *arg = (struct executeScriptsStruct *)a; ProcessList *p = arg->list; struct cfgoptions *s = arg->config; Container container = {{0}, s, NULL}; repaircmd_t *c = NULL; repaircmd_t *next = NULL; list_for_each_entry(c, next, &p->head, entry) { container.cmd = c; container.cmd->mode = TEST; c->retString[0] = '\0'; ThreadPoolAddTask(__ExecScriptWorkerThread, &container, true); __sync_synchronize(); FutexWait(&sem, 0); sem = 0; } c = NULL; next = NULL; __WaitForWorkers(&container); list_for_each_entry(c, next, &p->head, entry) { if (c->ret == 0) { continue; } container.cmd = c; portable_snprintf(container.cmd->retString, sizeof(container.cmd->retString), "%i", c->ret); container.cmd->mode = REPAIR; ThreadPoolAddTask(__ExecScriptWorkerThread, &container, true); __sync_synchronize(); FutexWait(&sem, 0); sem = 0; } __WaitForWorkers(&container); c = NULL; next = NULL; list_for_each_entry(c, next, &p->head, entry) { if (c->ret != 0) { Logmsg(LOG_ERR, "repair %s script failed", c->legacy == false ? c->spawnattr.repairFilePathname : c->path); return 1; } } return 0; } struct repairscriptTranctions *rst = NULL; bool ExecuteRepairScriptsPreFork(ProcessList * p, struct cfgoptions *s) { if (list_is_empty(&p->head)) { return true; } int shmid = shmget(IPC_PRIVATE, sysconf(_SC_PAGESIZE), (IPC_CREAT|IPC_EXCL|SHM_NORESERVE|0600)); rst = (repairscriptTranctions*)shmat(shmid, NULL, 0); struct shmid_ds buf = {0}; shmctl(shmid, IPC_RMID, &buf); pid_t pid = fork(); if (pid == -1) { Logmsg(LOG_ERR, "%s\n", MyStrerror(errno)); return false; } else if (pid == 0) { unsetenv("NOTIFY_SOCKET"); ThreadPoolNew(); while (true) { FutexWait(&rst->sem, 0); struct executeScriptsStruct ess; ess.list = p; ess.config = s; rst->ret = __ExecuteRepairScripts(&ess); } quick_exit(0); } return true; } int ExecuteRepairScripts(void) { if (rst == NULL) { pthread_exit(NULL); } FutexWake(&rst->sem); if (rst->ret != 0) { return -1; } return 0; } <|start_filename|>src/init.cpp<|end_filename|> /* * Copyright 2013-2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <getopt.h> #include "watchdogd.hpp" #include "init.hpp" #include "sub.hpp" #include "multicall.hpp" #include "logutils.hpp" #include "linux.hpp" int SetSchedulerPolicy(int priority) { struct sched_param param; param.sched_priority = priority; if (sched_setscheduler(0, SCHED_RR|SCHED_RESET_ON_FORK, &param) < 0) { assert(errno != ESRCH); fprintf(stderr, "watchdogd: sched_setscheduler failed %s\n", MyStrerror(errno)); return -1; } return 0; } int InitializePosixMemlock(void) { if (mlockall(MCL_CURRENT | MCL_FUTURE) < 0) { fprintf(stderr, "watchdogd: unable to lock memory %s\n", MyStrerror(errno)); return -1; } return 0; } static void PrintHelpIdentify(void); int ParseCommandLine(int *argc, char **argv, struct cfgoptions *cfg, bool earlyParse) { int opt = 0; struct option longOptions[] = { {"help", no_argument, 0, 'h'}, {"identify", no_argument, 0, 'i'}, {"version", no_argument, 0, 'V'}, {"no-action", no_argument, 0, 'q'}, {"foreground", no_argument, 0, 'F'}, {"debug", no_argument, 0, 'd'}, {"force", no_argument, 0, 'f'}, {"sync", no_argument, 0, 's'}, {"softboot", no_argument, 0, 'b'}, {"daemonize", no_argument, 0, 'D'}, {"verbose", no_argument, 0, 'v'}, {"config-file", required_argument, 0, 'c'}, {"loglevel", required_argument, 0, 'l'}, {0, 0, 0, 0} }; char const * const loglevels[] = { "\x1b[1mnone", "err", "info", "notice", "debug\x1B[0m"}; struct cfgoptions x; const char *opstr; if (earlyParse) { opstr = "hiV"; longOptions[3] = {0,0,0,0}; if (!cfg) { cfg = &x; } } else { opstr = "iDhqsfFbVvndc:l:"; optind = 0; } int tmp = 0; while ((opt = getopt_long(*argc, argv, opstr, longOptions, &tmp)) != -1) { switch (opt) { case 'n': case 'd': case 'F': cfg->options &= !DAEMONIZE; break; case 'c': cfg->confile = optarg; break; case 's': cfg->options |= SYNC; break; case 'q': cfg->options |= NOACTION; break; case 'l': if (LogUpTo(optarg, true) == false) { return -1; } cfg->options |= LOGLVLSETCMDLN; break; case 'f': cfg->options |= FORCE; break; case 'b': cfg->options |= SOFTBOOT; break; case 'v': cfg->options |= VERBOSE; break; case 'i': cfg->options |= IDENTIFY; break; case 'D': cfg->options |= DAEMONIZE; break; case 'V': PrintVersionString(); if (earlyParse) quick_exit(1); return 1; case 'h': if (cfg->options & IDENTIFY) { PrintHelpIdentify(); } else { Usage(); } if (earlyParse) quick_exit(1); return 1; case '?': switch (optopt) { case 'l': fprintf(stderr, "Valid loglevels are:\n"); for (size_t i = 0; i < ARRAY_SIZE(loglevels); i++) { if (isatty(STDOUT_FILENO) == 0 && i == 0) { fprintf(stderr, " %s\n", loglevels[i]+4); continue; } else if (isatty(STDOUT_FILENO) == 0 && i + 1 == ARRAY_SIZE(loglevels)) { char const * const tmp = loglevels[i]; fprintf(stderr, " "); for (size_t j = 0; tmp[j] != '\x1b'; j++) { fprintf(stderr, "%c", tmp[j]); } fprintf(stderr, "\n"); } else { fprintf(stderr, " %s\n", loglevels[i]); } } break; } return -1; default: if (cfg->options & IDENTIFY) { PrintHelpIdentify(); } else { Usage(); } return -1; } } if (optind < *argc) { struct stat buf = {0}; if (stat(argv[optind], &buf) < 0) { fprintf(stderr, "watchdogd: %s\n", strerror(errno)); return -1; } if (!S_ISCHR(buf.st_mode)) { fprintf(stderr, "watchdogd: %s is an invalid device file\n", argv[optind]); return -1; } cfg->devicepath = argv[optind]; cfg->options |= BUSYBOXDEVOPTCOMPAT; } return 0; } int GetDefaultPriority(void) { int ret = sched_get_priority_min(SCHED_RR); if (ret < 0) { fprintf(stderr, "watchdogd: %s\n", MyStrerror(errno)); return ret; } return ret; } int CheckPriority(int priority) { int max = 0; int min = 0; max = sched_get_priority_max(SCHED_RR); if (max < 0) { fprintf(stderr, "watchdogd: %s\n", MyStrerror(errno)); return -1; } min = sched_get_priority_min(SCHED_RR); if (min < 0) { fprintf(stderr, "watchdogd: %s\n", MyStrerror(errno)); return -1; } if (priority < min) { return -2; } if (priority > max) { return -2; } return 0; } int PrintVersionString(void) { printf("%s %s\n", PACKAGE_STRING, CODENAME); printf("Copyright 2013-2018 <NAME>. All rights reserved.\n"); printf("Licensed under the Apache License, Version 2.0.\n"); printf("There is NO WARRANTY, to the extent permitted by law.\n"); return 0; } static void PrintHelpIdentify(void) { char *buf = NULL; Wasprintf(&buf, "Usage: %s [OPTION]", GetExeName()); assert(buf != NULL); if (buf == NULL) { abort(); } char const * const help[][2] = { {buf, ""}, {"Get watchdog device status.", ""}, {"", ""}, {" -c, --config-file ", "path to configuration file"}, {" -i, --identify", "identify hardware watchdog"}, {" -h, --help", "this help"}, {" -V, --version", "print version info"}, }; for (size_t i = 0; i < ARRAY_SIZE(help); i += 1) { bool isterm = isatty(STDOUT_FILENO) == 1; long col = GetConsoleColumns(); if (col >= 80) { //KLUGE col += col / 2; } long len = 0; if (isterm && i > 2) { printf("\x1B[1m"); } len += printf("%-22s", help[i][0]); if (isterm && i > 2) { printf("\x1B[22m"); } char *ptr = strdup(help[i][1]); if (ptr == NULL) { perror(PACKAGE_NAME); return; } char *save = NULL; char *tmp = strtok_r(ptr, " ", &save); if (isterm) { printf("\e[1;34m"); } while (tmp != NULL) { len += strlen(tmp); if (len > col) { if (col < 80) { printf("\n"); } len = printf(" "); len += printf("%s", tmp); tmp = strtok_r(NULL, " ", &save); if (tmp != NULL) { len += printf(" "); } } else { len += printf("%s", tmp); tmp = strtok_r(NULL, " ", &save); if (tmp != NULL) { len += printf(" "); } } } if (isterm) { printf("\x1B[39m\x1B[22m"); } free(ptr); printf("\n"); } free(buf); } static void PrintHelpMain(void) { //Emulate the gnu --help output. const char *const help[][2] = { {"Usage: " PACKAGE_NAME " [OPTION]", ""}, {"A watchdog daemon for linux.", ""}, {"", ""}, {" -b, --softboot", "ignore file open errors"}, {" -c, --config-file ", "path to configuration file"}, {" -D, --daemonize ", "daemonize after startup"}, {" -f, --force", "force a ping interval or timeout even if the ping interval is less than the timeout"}, {" -i, --identify", "identify hardware watchdog"}, {" -l, --loglevel", "sets max loglevel none, err, info, notice, debug"}, {" -s, --sync", "sync file-systems regularly"}, {" -h, --help", "this help"}, {" -V, --version", "print version info"}, }; for (size_t i = 0; i < ARRAY_SIZE(help); i += 1) { bool isterm = isatty(STDOUT_FILENO) == 1; long col = GetConsoleColumns(); if (col >= 80) { //KLUGE col += col / 2; } long len = 0; if (isterm && i > 2) { printf("\x1B[1m"); } len += printf("%-22s", help[i][0]); if (isterm && i > 2) { printf("\x1B[22m"); } char *ptr = strdup(help[i][1]); if (ptr == NULL) { perror(PACKAGE_NAME); return; } char *save = NULL; char *tmp = strtok_r(ptr, " ", &save); if (isterm) { printf("\e[1;34m"); } while (tmp != NULL) { len += strlen(tmp); if (len > col) { if (col < 80) { printf("\n"); } len = printf(" "); len += printf("%s", tmp); tmp = strtok_r(NULL, " ", &save); if (tmp != NULL) { len += printf(" "); } } else { len += printf("%s", tmp); tmp = strtok_r(NULL, " ", &save); if (tmp != NULL) { len += printf(" "); } } } if (isterm) { printf("\x1B[39m\x1B[22m"); } free(ptr); printf("\n"); } } int Usage(void) { if (strcasecmp(GetExeName(), "wd_identify") == 0 || strcasecmp(GetExeName(), "wd_identify.sh") == 0) { PrintHelpIdentify(); } else { PrintHelpMain(); } return 0; } <|start_filename|>src/snprintf.hpp<|end_filename|> #ifndef _PORTABLE_SNPRINTF_H_ #define _PORTABLE_SNPRINTF_H_ #define PORTABLE_SNPRINTF_VERSION_MAJOR 2 #define PORTABLE_SNPRINTF_VERSION_MINOR 2 #define PREFER_PORTABLE_SNPRINTF #define SNPRINTF_LONGLONG_SUPPORT #ifdef HAVE_SNPRINTF #include <stdio.h> #else extern int snprintf(char *, size_t, const char *, /*args*/ ...); extern int vsnprintf(char *, size_t, const char *, va_list); #endif #if defined(HAVE_SNPRINTF) && defined(PREFER_PORTABLE_SNPRINTF) extern int portable_snprintf(char *str, size_t str_m, const char *fmt, /*args*/ ...); extern int portable_vsnprintf(char *str, size_t str_m, const char *fmt, va_list ap); #define snprintf portable_snprintf #define vsnprintf portable_vsnprintf #endif extern int asprintf (char **ptr, const char *fmt, /*args*/ ...); extern int vasprintf (char **ptr, const char *fmt, va_list ap); extern int asnprintf (char **ptr, size_t str_m, const char *fmt, /*args*/ ...); extern int vasnprintf(char **ptr, size_t str_m, const char *fmt, va_list ap); #endif
clockley/watchdogd
<|start_filename|>deploy/Dockerfile<|end_filename|> FROM golang:1.14 AS build-env ADD . /src/github.com/AliyunContainerService/kube-eventer ENV GOPATH /:/src/github.com/AliyunContainerService/kube-eventer/vendor ENV GO111MODULE on ENV GOPROXY=https://goproxy.cn,direct WORKDIR /src/github.com/AliyunContainerService/kube-eventer RUN apt-get update -y && apt-get install gcc ca-certificates RUN make FROM alpine:3.11.6 COPY --from=build-env /src/github.com/AliyunContainerService/kube-eventer/kube-eventer / COPY --from=build-env /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ ENV TZ "Asia/Shanghai" RUN apk add --no-cache tzdata #COPY deploy/entrypoint.sh / RUN addgroup -g 1000 nonroot && \ adduser -u 1000 -D -H -G nonroot nonroot && \ chown -R nonroot:nonroot /kube-eventer USER nonroot:nonroot ENTRYPOINT ["/kube-eventer"]
liabio/kube-eventer
<|start_filename|>web/js/site.js<|end_filename|> (function(global){ "use strict"; $(document).ready(function(){ Events.emit("ready"); // initialize templates Events.emit("Tmpls"); }); })(window);
vandosant/RKC-2600
<|start_filename|>image/Dockerfile<|end_filename|> FROM alpine:3.12.1 RUN apk add bind-tools curl wrk vim \ tcptraceroute iptables httpie bash \ tini apache2-utils stress-ng strace --update && \ curl -s https://pkg.cfssl.org/R1.2/cfssl_linux-amd64 -o /usr/local/bin/cfssl && \ curl -L -s https://github.com/BuoyantIO/slow_cooker/releases/download/1.1.0/slow_cooker_linux_amd64 -o /usr/local/bin/slow_cooker && \ chmod a+x /usr/local/bin/* && rm -Rf /var/cache/apk/* CMD ["tini", "tail", "-f", "/dev/null"]
fleeto/sleep
<|start_filename|>composer.json<|end_filename|> { "name": "urb/xenforobridge", "description": "Xenforo Bridge - Easy to use extendable bridge to use outside of your XenForo application all contained within a simple to use composer package", "keywords": ["laravel", "laravel5", "xenforo", "xenforo forum", "forum"], "type": "library", "authors": [ { "name": "<NAME>", "email": "<EMAIL>" } ], "require": { "php": ">=5.5.0" }, "autoload": { "psr-4" : { "Urb\\XenforoBridge\\" : "src/XenforoBridge" } }, "minimum-stability": "dev" }
alfio8788/XenforoBridge
<|start_filename|>csharp/startNewDialogWithPrompt/ConversationStarter.cs<|end_filename|> using Microsoft.Bot.Builder.Dialogs; using Microsoft.Bot.Builder.Dialogs.Internals; using Microsoft.Bot.Connector; using System; using System.Collections.Generic; using Autofac; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Web; namespace startNewDialogWithPrompt { public class ConversationStarter { //Note: Of course you don't want this here. Eventually you will need to save this in some table //Having this here as static variable means we can only remember one user :) public static string resumptionCookie; //This will interrupt the conversation and send the user to SurveyDialog, then wait until that's done public static async Task Resume() { var message = ResumptionCookie.GZipDeserialize(resumptionCookie).GetMessage(); var client = new ConnectorClient(new Uri(message.ServiceUrl)); using (var scope = DialogModule.BeginLifetimeScope(Conversation.Container, message)) { var botData = scope.Resolve<IBotData>(); await botData.LoadAsync(CancellationToken.None); var stack = scope.Resolve<IDialogStack>(); //interrupt the stack var dialog =new SurveyDialog(); stack.Call(dialog.Void<object, IMessageActivity>(), null); await stack.PollAsync(CancellationToken.None); //flush dialog stack await botData.FlushAsync(CancellationToken.None); } } } } <|start_filename|>node/startNewDialogWithPrompt/index.js<|end_filename|> "use strict"; var restify = require('restify'); var builder = require('botbuilder'); var server = restify.createServer(); server.listen(process.env.port || process.env.PORT || 3978, function () { console.log('%s listening to %s', server.name, server.url); }); var connector = new builder.ChatConnector({ appId: process.env.MICROSOFT_APP_ID, appPassword: <PASSWORD> }); var bot = new builder.UniversalBot(connector); bot = require("./botadapter").patch(bot); bot.dialog('/survey', [ function (session, args, next) { var prompt = ('Hello, I\'m the survey dialog. I\'m interrupting your conversation to ask you a question. Type "done" to resume'); builder.Prompts.choice(session, prompt, "done"); }, function (session, results) { session.send("Great, back to the original conversation"); session.endDialog(); } ]); function startProactiveDialog(addr) { // set resume:false to resume at the root dialog // else true to resume the previous dialog bot.beginDialog(savedAddress, "*:/survey", {}, { resume: true }); } var savedAddress; server.post('/api/messages', connector.listen()); server.get('/api/CustomWebApi', (req, res, next) => { startProactiveDialog(savedAddress); res.send('triggered'); next(); } ); bot.dialog('/', function(session, args) { savedAddress = session.message.address; var message = 'Hey there, I\'m going to interrupt our conversation and start a survey in a few seconds.'; session.send(message); connector.url message = 'You can also make me send a message by accessing: '; message += 'http://localhost:' + server.address().port + '/api/CustomWebApi'; session.send(message); setTimeout(() => { startProactiveDialog(savedAddress); }, 5000) });
MicrosoftDX/botFramework-proactiveMessages
<|start_filename|>resources/docs/directives/proxy_store.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpProxyModule&amp;action=edit&amp;section=44" title="Edit section: proxy store">edit</a>]</span> <span class="mw-headline" id="proxy_store"> proxy_store </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>proxy_store</b> <code>on</code> | <code>off</code> | <i>string</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>off</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_store">proxy_store</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 357/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> This directive sets the path in which upstream files are stored. The parameter &quot;on&quot; preserves files in accordance with path specified in directives <i>alias</i> or <i>root</i>. The parameter &quot;off&quot; forbids storing. Furthermore, the name of the path can be clearly assigned with the aid of the line with the variables: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpProxyModule#proxy_store"><span class="kw21">proxy_store</span></a> /data/www<span class="re0">$uri</span><span class="sy0">;</span></pre> </div> </div><p>The time of modification for the file will be set to the date of &quot;Last-Modified&quot; header in the response. To be able to safe files in this directory it is necessary that the path is under the directory with temporary files, given by directive proxy_temp_path for the data location. </p><p>This directive can be used for creating the local copies for dynamic output of the backend which is not very often changed, for example: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#location"><span class="kw3">location</span></a> /images/ <span class="br0">{</span> <a href="/NginxHttpCoreModule#root"><span class="kw3">root</span></a> /data/www<span class="sy0">;</span> <a href="/NginxHttpCoreModule#error_page"><span class="kw3">error_page</span></a> <span class="nu0">404</span> <span class="sy0">=</span> /fetch<span class="re0">$uri</span><span class="sy0">;</span> <span class="br0">}</span> &nbsp; <a href="/NginxHttpCoreModule#location"><span class="kw3">location</span></a> /fetch <span class="br0">{</span> <a href="/NginxHttpCoreModule#internal"><span class="kw3">internal</span></a><span class="sy0">;</span> <a href="/NginxHttpProxyModule#proxy_pass"><span class="kw21">proxy_pass</span></a> <a href="/NginxHttpCoreModule#http"><span class="kw3">http</span></a>://backend<span class="sy0">;</span> <a href="/NginxHttpProxyModule#proxy_store"><span class="kw21">proxy_store</span></a> on<span class="sy0">;</span> <a href="/NginxHttpProxyModule#proxy_store_access"><span class="kw21">proxy_store_access</span></a> <a href="/NginxHttpCoreModule#user"><span class="kw1">user</span></a>:rw group:rw all:r<span class="sy0">;</span> <a href="/NginxHttpProxyModule#proxy_temp_path"><span class="kw21">proxy_temp_path</span></a> /data/temp<span class="sy0">;</span> <a href="/NginxHttpCoreModule#alias"><span class="kw3">alias</span></a> /data/www<span class="sy0">;</span> <span class="br0">}</span></pre> </div> </div><p>or this way: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#location"><span class="kw3">location</span></a> /images/ <span class="br0">{</span> <a href="/NginxHttpCoreModule#root"><span class="kw3">root</span></a> /data/www<span class="sy0">;</span> <a href="/NginxHttpCoreModule#error_page"><span class="kw3">error_page</span></a> <span class="nu0">404</span> <span class="sy0">=</span> <span class="re0">@fetch</span><span class="sy0">;</span> <span class="br0">}</span> &nbsp; <a href="/NginxHttpCoreModule#location"><span class="kw3">location</span></a> <span class="re0">@fetch</span> <span class="br0">{</span> <a href="/NginxHttpCoreModule#internal"><span class="kw3">internal</span></a><span class="sy0">;</span> &nbsp; <a href="/NginxHttpProxyModule#proxy_pass"><span class="kw21">proxy_pass</span></a> <a href="/NginxHttpCoreModule#http"><span class="kw3">http</span></a>://backend<span class="sy0">;</span> <a href="/NginxHttpProxyModule#proxy_store"><span class="kw21">proxy_store</span></a> on<span class="sy0">;</span> <a href="/NginxHttpProxyModule#proxy_store_access"><span class="kw21">proxy_store_access</span></a> <a href="/NginxHttpCoreModule#user"><span class="kw1">user</span></a>:rw group:rw all:r<span class="sy0">;</span> <a href="/NginxHttpProxyModule#proxy_temp_path"><span class="kw21">proxy_temp_path</span></a> /data/temp<span class="sy0">;</span> &nbsp; <a href="/NginxHttpCoreModule#root"><span class="kw3">root</span></a> /data/www<span class="sy0">;</span> <span class="br0">}</span></pre> </div> </div><p>To be clear proxy_store is not a cache, it's rather mirror on demand. </p><br><i>Module: HttpProxyModule</i> <|start_filename|>resources/docs/directives/client_header_buffer_size.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpCoreModule&amp;action=edit&amp;section=11" title="Edit section: client header buffer size">edit</a>]</span> <span class="mw-headline" id="client_header_buffer_size"> client_header_buffer_size </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>client_header_buffer_size</b> <i>size</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>1k</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_core_module.html#client_header_buffer_size">client_header_buffer_size</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 87/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Directive sets the headerbuffer size for the request header from client. </p><p>For the overwhelming majority of requests it is completely sufficient with a buffer size of 1K. </p><p>However if a big cookie is in the request-header or the request has come from a wap-client the header can not be placed in 1K, therefore, the request-header or a line of request-header is not located completely in this buffer nginx allocate a bigger buffer, the size of the bigger buffer can be set with the instruction large_client_header_buffers. </p><br><i>Module: HttpCoreModule</i> <|start_filename|>resources/docs/directives/gzip_buffers.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpGzipModule&amp;action=edit&amp;section=4" title="Edit section: gzip buffers">edit</a>]</span> <span class="mw-headline" id="gzip_buffers"> gzip_buffers </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>gzip_buffers</b> <i>number</i> <i>size</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>32 4k|16 8k</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_gzip_module.html#gzip_buffers">gzip_buffers</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 20/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Assigns the number and the size of the buffers into which to store the compressed response. If unset, the size of one buffer is equal to the size of page, depending on platform this either 4K or 8K. </p><p><br /> </p><br><i>Module: HttpGzipModule</i> <|start_filename|>resources/docs/directives/proxy_temp_path.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpProxyModule&amp;action=edit&amp;section=47" title="Edit section: proxy temp path">edit</a>]</span> <span class="mw-headline" id="proxy_temp_path"> proxy_temp_path </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>proxy_temp_path</b> <i>path</i> [ <i>level1</i> [ <i>level2</i> [ <i>level3</i> ]]]</td> </tr> <tr> <td><b>Default:</b></td> <td> <i>proxy_temp</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_temp_path">proxy_temp_path</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 393/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> This directive works like <a href="/HttpCoreModule#client_body_temp_path" title="HttpCoreModule">client_body_temp_path</a> to specify a location to buffer large proxied requests to the filesystem. </p><br><i>Module: HttpProxyModule</i> <|start_filename|>resources/docs/directives/ssl_engine.html<|end_filename|> <h3>Directive can have multiple meanings. Each variant is separated with horizontal line</h3><hr><h2><span class="editsection">[<a href="/index.php?title=CoreModule&amp;action=edit&amp;section=12" title="Edit section: ssl engine">edit</a>]</span> <span class="mw-headline" id="ssl_engine"> ssl_engine </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>ssl_engine</b> <i>device</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> main</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/ngx_core_module.html#ssl_engine">ssl_engine</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 91/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Here you can set your preferred openssl engine if any available. You can figure out which one do you have with the commandline tool: <code>openssl engine -t</code> </p><p>For example: </p><pre> $ openssl engine -t (cryptodev) BSD cryptodev engine [ available ] (dynamic) Dynamic engine loading support [ unavailable ] </pre><br><i>Module: CoreModule</i><hr><h2><span class="editsection">[<a href="/index.php?title=HttpSslModule&amp;action=edit&amp;section=18" title="Edit section: ssl engine">edit</a>]</span> <span class="mw-headline" id="ssl_engine"> ssl_engine </span></h2><p><b>syntax:</b> <i>ssl_engine</i> </p><p>This allows specifying the OpenSSL engine to use, like PadLock, for example. It requires a recent version of OpenSSL. To verify if the OpenSSL version installed in your platform supports this, issue the command: </p><pre> openssl engine </pre><p>On a Debian testing with OpenSSL version 0.9.8o from 01 Jun 2010 it returns: </p><pre> $ openssl engine (padlock) VIA PadLock (no-RNG, no-ACE) (dynamic) Dynamic engine loading support </pre><h1><span class="editsection">[<a href="/index.php?title=HttpSslModule&amp;action=edit&amp;section=19" title="Edit section: Built-in variables">edit</a>]</span> <span class="mw-headline" id="Built-in_variables"> Built-in variables </span></h1><p>Module ngx_http_ssl_module supports the following built-in variables: </p><ul> <li> $ssl_cipher returns the cipher suite being used for the currently established SSL/TLS connection </li> <li> $ssl_client_serial returns the serial number of the client certificate for the currently established SSL/TLS connection — if applicable, i.e., if client authentication is activated in the connection </li> <li> $ssl_client_s_dn returns the subject Distinguished Name (DN) of the client certificate for the currently established SSL/TLS connection — if applicable, i.e., if client authentication is activated in the connection </li> <li> $ssl_client_i_dn returns the issuer DN of the client certificate for the currently established SSL/TLS connection — if applicable, i.e., if client authentication is activated in the connection </li> <li> $ssl_protocol returns the protocol of the currently established SSL/TLS connection — depending on the configuration and client available options it's one of SSLv2, SSLv3 or TLSv1 </li> <li> $ssl_session_id the Session ID of the established secure connection — requires Nginx version greater or equal to 0.8.20 </li> <li> $ssl_client_cert </li> <li> $ssl_client_raw_cert </li> <li> $ssl_client_verify takes the value &quot;SUCCESS&quot; when the client certificate is successfully verified </li> </ul><h1><span class="editsection">[<a href="/index.php?title=HttpSslModule&amp;action=edit&amp;section=20" title="Edit section: Nonstandard error codes">edit</a>]</span> <span class="mw-headline" id="Nonstandard_error_codes"> Nonstandard error codes </span></h1><p>This module supports several nonstandard error codes which can be used for debugging with the aid of directive error_page: </p><ul> <li> 495 - error checking client certificate </li> <li> 496 - client did not grant the required certificate </li> <li> 497 - normal request was sent to HTTPS </li> </ul><p>Debugging is done after the request is completely &quot;disassembled&quot; and it's components are accessible via variables such as $request_uri, $uri, $arg and more. </p><h1><span class="editsection">[<a href="/index.php?title=HttpSslModule&amp;action=edit&amp;section=21" title="Edit section: References">edit</a>]</span> <span class="mw-headline" id="References"> References </span></h1><ul> <li> <a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_ssl_module.html">Original Documentation</a> </li> <li> <a rel="nofollow" class="external text" href="http://kbeezie.com/view/free-ssl-with-nginx/">Implementing an actual SSL Certificate</a> </li> <li> <a rel="nofollow" class="external text" href="http://marc.info/?t=120127289900027">SSL Memory Fragmentation and new default status for ssl_session_cache</a> </li> </ul><br><i>Module: HttpSslModule</i> <|start_filename|>src/net/ishchenko/idea/nginx/psi/NginxInnerVariable.java<|end_filename|> package net.ishchenko.idea.nginx.psi; import com.intellij.psi.PsiNamedElement; /** * Created by IntelliJ IDEA. * User: Max * Date: 14.08.2009 * Time: 14:31:06 */ /** * PsiNamedElement is implemented solely for quick documentation lookup purposes. * Ctrl+q just won't work if PsiNamedElement is not implemented */ public interface NginxInnerVariable extends NginxPsiElement, PsiNamedElement { } <|start_filename|>resources/docs/directives/ssl_ciphers.html<|end_filename|> <h3>Directive can have multiple meanings. Each variant is separated with horizontal line</h3><hr><h2><span class="editsection">[<a href="/index.php?title=HttpSslModule&amp;action=edit&amp;section=8" title="Edit section: ssl ciphers">edit</a>]</span> <span class="mw-headline" id="ssl_ciphers"> ssl_ciphers </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>ssl_ciphers</b> <i>ciphers</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>HIGH:!aNULL:!MD5</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_ssl_module.html#ssl_ciphers">ssl_ciphers</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 63/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> This directive describes the list of cipher suites the server supports for establishing a secure connection. Cipher suites are specified in the <a rel="nofollow" class="external text" href="http://openssl.org/docs/apps/ciphers.html">OpenSSL</a> cipherlist format, for example: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpSslModule#ssl_ciphers"><span class="kw31">ssl_ciphers</span></a> ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP<span class="sy0">;</span></pre> </div> </div><p>Since nginx version 1.0.5, the default ciphers are: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpSslModule#ssl_ciphers"><span class="kw31">ssl_ciphers</span></a> HIGH:!aNULL:!MD5<span class="sy0">;</span></pre> </div> </div><p>The complete cipherlist supported by the currently installed version of OpenSSL in your platform can be obtained by issuing the command: </p><pre> openssl ciphers </pre><br><i>Module: HttpSslModule</i><hr><h2><span class="editsection">[<a href="/index.php?title=MailSslModule&amp;action=edit&amp;section=6" title="Edit section: ssl ciphers">edit</a>]</span> <span class="mw-headline" id="ssl_ciphers"> ssl_ciphers </span></h2><p><b>syntax:</b> <i>ssl_ciphers file</i> <i><b>ciphers</b></i> </p><p><b>default:</b> <i>ALL:!ADH:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP</i> </p><p><b>context:</b> <i>mail, server</i> </p><p>Directive describes the permitted ciphers. Ciphers are assigned in the formats supported by OpenSSL. </p><br><i>Module: MailSslModule</i> <|start_filename|>tests/net/ishchenko/idea/nginx/ParserTest.java<|end_filename|> package net.ishchenko.idea.nginx; import com.intellij.lang.Language; import com.intellij.lang.LanguageExtension; import com.intellij.testFramework.ParsingTestCase; import net.ishchenko.idea.nginx.parser.NginxParserDefinition; public class ParserTest extends ParsingTestCase { // Needs to be called to add to Language.ourRegisteredClasses. // Otherwise we get an error "nginx doesn't participate in view provider", // which is caused by the view provider language being "ANY". private static Language l = NginxLanguage.INSTANCE; public ParserTest() { super("", "conf", new NginxParserDefinition()); } public void testParsingData() { doTest(true); } @Override protected String getTestDataPath() { return "testData"; } @Override protected boolean skipSpaces() { return false; } @Override protected boolean includeRanges() { return true; } @Override protected <T> void addExplicitExtension(LanguageExtension<T> instance, Language language, T object) { super.addExplicitExtension(instance, language, object); } } <|start_filename|>resources/docs/directives/addition_types.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpAdditionModule&amp;action=edit&amp;section=7" title="Edit section: addition types">edit</a>]</span> <span class="mw-headline" id="addition_types"> addition_types </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>addition_types</b> <i>mime-type</i> ...</td> </tr> <tr> <td><b>Default:</b></td> <td> <i>text/html</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Appeared in:</b></td> <td> 0.7.9</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_addition_module.html#addition_types">addition_types</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 38/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Directive (since 0.7.9) allows you to add text only to locations of the specified MIME-types (defaults to <i>&quot;text/html&quot;</i>). </p><p>(Before 0.8.17, this directive was mispelled as &quot;addtion_types&quot; in the source. This bug has been fixed in 0.8.17.) </p><h1><span class="editsection">[<a href="/index.php?title=HttpAdditionModule&amp;action=edit&amp;section=8" title="Edit section: References">edit</a>]</span> <span class="mw-headline" id="References"> References </span></h1><p><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_addition_module.html">Original Documentation</a> </p><br><i>Module: HttpAdditionModule</i> <|start_filename|>resources/docs/directives/keepalive_disable.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpCoreModule&amp;action=edit&amp;section=23" title="Edit section: keepalive disable">edit</a>]</span> <span class="mw-headline" id="keepalive_disable"> keepalive_disable </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>keepalive_disable</b> <code>none</code> | <i>browser</i> ...</td> </tr> <tr> <td><b>Default:</b></td> <td> <i>msie6</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_core_module.html#keepalive_disable">keepalive_disable</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 189/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Disable keepalive for certain user agents (0.9.0+). By default keepalive is disabled for MS Internet Explorer (older than 6.0 service pack 2) after <code>POST</code> requests, and for Safari. This is because both browsers have issues with handling <code>POST</code> requests with keepalives. If you are running a site that does not use <code>POST</code> anywhere, you may optionally choose to enable keepalive in these browsers. </p><br><i>Module: HttpCoreModule</i> <|start_filename|>resources/docs/directives/fastcgi_store.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpFastcgiModule&amp;action=edit&amp;section=36" title="Edit section: fastcgi store">edit</a>]</span> <span class="mw-headline" id="fastcgi_store"> fastcgi_store </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>fastcgi_store</b> <code>on</code> | <code>off</code> | <i>string</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>off</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_store">fastcgi_store</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 333/1000000 Post-expand include size: 401/2097152 bytes Template argument size: 178/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> This directive sets the path in which upstream files are stored. The parameter &quot;on&quot; preserves files in accordance with path specified in directives <i>alias</i> or <i>root</i>. The parameter &quot;off&quot; forbids storing. Furthermore, the name of the path can be clearly assigned with the aid of the line with the variables: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpFcgiModule#fastcgi_store"><span class="kw11">fastcgi_store</span></a> /data/www<span class="re0">$original_uri</span><span class="sy0">;</span></pre> </div> </div><p>The time of modification for the file will be set to the date of &quot;Last-Modified&quot; header in the response. To be able to safe files in this directory it is necessary that the path is under the directory with temporary files, given by directive <a href="#fastcgi_temp_path">fastcgi_temp_path</a> for the data location. </p><p>This directive can be used for creating the local copies for dynamic output of the backend which is not very often changed, for example: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#location"><span class="kw3">location</span></a> /images/ <span class="br0">{</span> <a href="/NginxHttpCoreModule#root"><span class="kw3">root</span></a> /data/www<span class="sy0">;</span> <a href="/NginxHttpCoreModule#error_page"><span class="kw3">error_page</span></a> <span class="nu0">404</span> <span class="sy0">=</span> /fetch<span class="re0">$uri</span><span class="sy0">;</span> <span class="br0">}</span> &nbsp; <a href="/NginxHttpCoreModule#location"><span class="kw3">location</span></a> /fetch <span class="br0">{</span> <a href="/NginxHttpCoreModule#internal"><span class="kw3">internal</span></a><span class="sy0">;</span> &nbsp; <a href="/NginxHttpFcgiModule#fastcgi_pass"><span class="kw11">fastcgi_pass</span></a> fastcgi://backend<span class="sy0">;</span> <a href="/NginxHttpFcgiModule#fastcgi_store"><span class="kw11">fastcgi_store</span></a> on<span class="sy0">;</span> <a href="/NginxHttpFcgiModule#fastcgi_store_access"><span class="kw11">fastcgi_store_access</span></a> <a href="/NginxHttpCoreModule#user"><span class="kw1">user</span></a>:rw group:rw all:r<span class="sy0">;</span> <a href="/NginxHttpFcgiModule#fastcgi_temp_path"><span class="kw11">fastcgi_temp_path</span></a> /data/temp<span class="sy0">;</span> &nbsp; <a href="/NginxHttpCoreModule#alias"><span class="kw3">alias</span></a> /data/www<span class="sy0">;</span> <span class="br0">}</span></pre> </div> </div><p>To be clear fastcgi_store is not a cache, it's rather mirror on demand. </p><br><i>Module: HttpFastcgiModule</i> <|start_filename|>resources/docs/directives/proxy_pass.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpProxyModule&amp;action=edit&amp;section=32" title="Edit section: proxy pass">edit</a>]</span> <span class="mw-headline" id="proxy_pass"> proxy_pass </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>proxy_pass</b> <i>URL</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> location<br />if in location<br />limit_except</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass">proxy_pass</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 237/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> This directive sets the address of the proxied server and the URI to which location will be mapped. Address may be given as hostname or address and port, for example, </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpProxyModule#proxy_pass"><span class="kw21">proxy_pass</span></a> <a href="/NginxHttpCoreModule#http"><span class="kw3">http</span></a>://localhost:<span class="nu0">8000</span>/uri/<span class="sy0">;</span></pre> </div> </div><p>or as unix socket path: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpProxyModule#proxy_pass"><span class="kw21">proxy_pass</span></a> <a href="/NginxHttpCoreModule#http"><span class="kw3">http</span></a>://unix:/path/to/backend.socket:/uri/<span class="sy0">;</span></pre> </div> </div><p>path is given after the word <code>unix</code> between two colons. </p><p>By default, the Host header from the request is not forwarded, but is set based on the proxy_pass statement. To forward the requested Host header, it is necessary to use: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpProxyModule#proxy_set_header"><span class="kw21">proxy_set_header</span></a> Host <span class="re0">$host</span><span class="sy0">;</span></pre> </div> </div><p>While passing request nginx replaces URI part which corresponds to location with one indicated in proxy_pass directive. But there are two exceptions from this rule when it is not possible to determine what to replace: </p><ul> <li> if the location is given by regular expression; </li> <li> if inside proxied location URI is changed by rewrite directive, and this configuration will be used to process request (break): </li> </ul><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#location"><span class="kw3">location</span></a> /name/ <span class="br0">{</span> <a href="/NginxHttpRewriteModule#rewrite"><span class="kw22">rewrite</span></a> /name/<span class="br0">(</span><span class="br0">[</span>^/<span class="br0">]</span> +<span class="br0">)</span> /users?name<span class="sy0">=</span>$<span class="nu0">1</span> <a href="/NginxHttpRewriteModule#break"><span class="kw22">break</span></a><span class="sy0">;</span> <a href="/NginxHttpProxyModule#proxy_pass"><span class="kw21">proxy_pass</span></a> <a href="/NginxHttpCoreModule#http"><span class="kw3">http</span></a>://127.0.0.1<span class="sy0">;</span> <span class="br0">}</span></pre> </div> </div><p>For these cases of URI it is transferred without the mapping. </p><p>Furthermore, it is possible to indicate so that URI should be transferred in the same form as sent by client, not in processed form. During processing: </p><ul> <li> two or by more slashes are converted into one slash: &quot;//&quot; -- &quot;/&quot;; </li> <li> references to the current directory are removed: &quot;/./&quot; -- &quot;/&quot;; </li> <li> references to the previous catalog are removed: &quot;/dir /../&quot; -- &quot;/&quot;. </li> </ul><p>If it is necessary to transmit URI in the unprocessed form then directive proxy_pass should be used without URI part: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#location"><span class="kw3">location</span></a> /some/path/ <span class="br0">{</span> <a href="/NginxHttpProxyModule#proxy_pass"><span class="kw21">proxy_pass</span></a> <a href="/NginxHttpCoreModule#http"><span class="kw3">http</span></a>://127.0.0.1<span class="sy0">;</span> <span class="br0">}</span></pre> </div> </div><p>A special case is using variables in the proxy_pass statement: The requested URL is not used and you are fully responsible to construct the target URL yourself. </p><p>This means, the following is not what you want for rewriting into a zope virtual host monster, as it will proxy always to the same URL (within one server specification): </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#location"><span class="kw3">location</span></a> / <span class="br0">{</span> <a href="/NginxHttpProxyModule#proxy_pass"><span class="kw21">proxy_pass</span></a> <a href="/NginxHttpCoreModule#http"><span class="kw3">http</span></a>://127.0.0.1:<span class="nu0">8080</span>/VirtualHostBase/https/<span class="re0">$server_name</span>:<span class="nu0">443</span>/some/path/VirtualHostRoot<span class="sy0">;</span> <span class="br0">}</span></pre> </div> </div><p>Instead use a combination of rewrite and proxy_pass: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#location"><span class="kw3">location</span></a> / <span class="br0">{</span> <a href="/NginxHttpRewriteModule#rewrite"><span class="kw22">rewrite</span></a> ^<span class="br0">(</span>.*<span class="br0">)</span>$ /VirtualHostBase/https/<span class="re0">$server_name</span>:<span class="nu0">443</span>/some/path/VirtualHostRoot$<span class="nu0">1</span> <a href="/NginxHttpRewriteModule#break"><span class="kw22">break</span></a><span class="sy0">;</span> <a href="/NginxHttpProxyModule#proxy_pass"><span class="kw21">proxy_pass</span></a> <a href="/NginxHttpCoreModule#http"><span class="kw3">http</span></a>://127.0.0.1:<span class="nu0">8080</span><span class="sy0">;</span> <span class="br0">}</span></pre> </div> </div><p>In this case URL sanitizing is done already as part of the rewriting process, i.e. a trailing slash with the proxy_pass statement has no further effect. </p><p>If you need the proxy connection to an upstream server group to use SSL, your proxy_pass rule should use https:// and you will also have to set your SSL port explicitly in the upstream definition. Example: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpUpstreamModule#upstream"><span class="kw4">upstream</span></a> backend-secure <span class="br0">{</span> <a href="/NginxHttpCoreModule#server"><span class="kw3">server</span></a> 10.0.0.20:<span class="nu0">443</span><span class="sy0">;</span> <span class="br0">}</span> &nbsp; <a href="/NginxHttpCoreModule#server"><span class="kw3">server</span></a> <span class="br0">{</span> <a href="/NginxHttpCoreModule#listen"><span class="kw3">listen</span></a> 10.0.0.1:<span class="nu0">443</span><span class="sy0">;</span> <a href="/NginxHttpCoreModule#location"><span class="kw3">location</span></a> / <span class="br0">{</span> <a href="/NginxHttpProxyModule#proxy_pass"><span class="kw21">proxy_pass</span></a> https://backend-secure<span class="sy0">;</span> <span class="br0">}</span> <span class="br0">}</span></pre> </div> </div><br><i>Module: HttpProxyModule</i> <|start_filename|>resources/docs/directives/if_.2F_elif_.2F_else_.2F_endif.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpSsiModule&amp;action=edit&amp;section=11" title="Edit section: if / elif / else / endif">edit</a>]</span> <span class="mw-headline" id="if_.2F_elif_.2F_else_.2F_endif"> if / elif / else / endif </span></h2><p>Conditionally include text or other directives. Usage: </p><pre> &lt;!--# if expr=&quot;...&quot; --&gt; ... &lt;!--# elif expr=&quot;...&quot; --&gt; ... &lt;!--# else --&gt; ... &lt;!--# endif --&gt; </pre><p>Only one level of nesting is possible. </p><ul> <li> <i>expr</i> — the expression to evaluate. It can be a variable: </li> </ul><pre> &lt;!--# if expr=&quot;$name&quot; --&gt; </pre><p>A string comparison: </p><pre> &lt;!--# if expr=&quot;$name = text&quot; --&gt; &lt;!--# if expr=&quot;$name&nbsp;!= text&quot; --&gt; </pre><p>Or a regex match: </p><pre> &lt;!--# if expr=&quot;$name = /text/&quot; --&gt; &lt;!--# if expr=&quot;$name&nbsp;!= /text/&quot; --&gt; </pre><p>If there are variables in the text, they will have their values substituted. </p><br><i>Module: HttpSsiModule</i> <|start_filename|>resources/docs/directives/worker_processes.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=CoreModule&amp;action=edit&amp;section=17" title="Edit section: worker processes">edit</a>]</span> <span class="mw-headline" id="worker_processes"> worker_processes </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>worker_processes</b> <i>number</i> | <code>auto</code> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>1</i></td> </tr> <tr> <td><b>Context:</b></td> <td> main</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/ngx_core_module.html#worker_processes">worker_processes</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 141/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> e.g.: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#worker_processes"><span class="kw1">worker_processes</span></a> <span class="nu0">4</span><span class="sy0">;</span></pre> </div> </div><p>A worker process is a single-threaded process. </p><p>If Nginx is doing CPU-intensive work such as SSL or gzipping and you have 2 or more CPUs/cores, then you may set worker_processes to be equal to the number of CPUs or cores. </p><p>If you are serving a lot of static files and the total size of the files is bigger than the available memory, then you may increase worker_processes to fully utilize disk bandwidth. </p><p>Your OS may schedule all workers on single CPU/core this can be avoided using <a href="/CoreModule#worker_cpu_affinity" title="CoreModule">worker_cpu_affinity</a>. </p><p>Nginx has the ability to use more than one worker process for several reasons: </p><ol> <li> to use SMP </li> <li> to decrease latency when workers blockend on disk I/O </li> <li> to limit number of connections per process when select()/poll() is used </li> </ol><p>The <code>worker_processes</code> and <code>worker_connections</code> from the event sections allows you to calculate <code>maxclients</code> value: </p><p>max_clients = worker_processes * worker_connections </p><br><i>Module: CoreModule</i> <|start_filename|>resources/docs/directives/tcp_nodelay.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpCoreModule&amp;action=edit&amp;section=68" title="Edit section: tcp nodelay">edit</a>]</span> <span class="mw-headline" id="tcp_nodelay"> tcp_nodelay </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>tcp_nodelay</b> <code>on</code> | <code>off</code> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>on</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_core_module.html#tcp_nodelay">tcp_nodelay</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 579/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> This directive allows or forbids the use of the socket option <code>TCP_NODELAY</code>. Only included in <code>keep-alive</code> connections. </p><p>You can read more about the <code>TCP_NODELAY</code> socket option <a href="/ReadMoreAboutTcpNodelay" title="ReadMoreAboutTcpNodelay">here</a>. </p><br><i>Module: HttpCoreModule</i> <|start_filename|>resources/docs/directives/modern_browser_value.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpBrowserModule&amp;action=edit&amp;section=6" title="Edit section: modern browser value">edit</a>]</span> <span class="mw-headline" id="modern_browser_value"> modern_browser_value </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>modern_browser_value</b> <i>string</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>1</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_browser_module.html#modern_browser_value">modern_browser_value</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 37/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Directive assigns value for the variables $modern_browser. </p><h1><span class="editsection">[<a href="/index.php?title=HttpBrowserModule&amp;action=edit&amp;section=7" title="Edit section: Examples">edit</a>]</span> <span class="mw-headline" id="Examples"> Examples </span></h1><p><b>Note</b> The use of ancient_browser in the link provided below is broken it should use: </p><pre>ancient_browser &quot;MSIE 4.0&quot; &quot;MSIE 5.0&quot; &quot;MSIE 5.5&quot; &quot;MSIE 6.0&quot;; </pre><p><a rel="nofollow" class="external text" href="http://gist.github.com/228769">Example of use</a>: support only recent versions of Chrome, Firefox, Internet Explorer, Safari, Mobile Safari and Palm Pre </p><h1><span class="editsection">[<a href="/index.php?title=HttpBrowserModule&amp;action=edit&amp;section=8" title="Edit section: References">edit</a>]</span> <span class="mw-headline" id="References"> References </span></h1><p><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_browser_module.html">Original Documentation</a> </p><br><i>Module: HttpBrowserModule</i> <|start_filename|>resources/docs/directives/proxy_send_timeout.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpProxyModule&amp;action=edit&amp;section=40" title="Edit section: proxy send timeout">edit</a>]</span> <span class="mw-headline" id="proxy_send_timeout"> proxy_send_timeout </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>proxy_send_timeout</b> <i>time</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>60s</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_send_timeout">proxy_send_timeout</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 320/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> This directive assigns timeout with the transfer of request to the upstream server. Timeout is established not on entire transfer of request, but only between two write operations. If after this time the upstream server will not take new data, then nginx is shutdown the connection. </p><br><i>Module: HttpProxyModule</i> <|start_filename|>resources/docs/directives/root.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpCoreModule&amp;action=edit&amp;section=55" title="Edit section: root">edit</a>]</span> <span class="mw-headline" id="root"> root </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>root</b> <i>path</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>html</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location<br />if in location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_core_module.html#root">root</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 455/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> <b>root</b> specifies the document root for the requests. For example, with this configuration </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#location"><span class="kw3">location</span></a> /i/ <span class="br0">{</span> <a href="/NginxHttpCoreModule#root"><span class="kw3">root</span></a> /spool/w3<span class="sy0">;</span> <span class="br0">}</span></pre> </div> </div><p>A request for &quot;/i/top.gif&quot; will return the file &quot;/spool/w3/i/top.gif&quot;. You can use variables in the argument. </p><p><b>note:</b> Keep in mind that the root will still append the directory to the request so that a request for &quot;/i/top.gif&quot; will not look in &quot;/spool/w3/top.gif&quot; like might happen in an Apache-like alias configuration where the location match itself is dropped. Use the <code>alias</code> directive to achieve the Apache-like functionality. </p><br><i>Module: HttpCoreModule</i> <|start_filename|>resources/docs/directives/limit_conn_zone.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpLimitConnModule&amp;action=edit&amp;section=4" title="Edit section: limit conn zone">edit</a>]</span> <span class="mw-headline" id="limit_conn_zone"> limit_conn_zone </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>limit_conn_zone</b> <i>$variable</i> <code>zone</code> = <i>name</i>&nbsp;: <i>size</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> http</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_limit_conn_module.html#limit_conn_zone">limit_conn_zone</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 20/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Sets the parameters for a zone that keeps state for various keys. This state stores the current number of connections in particular. The key is the value of the specified variable. Example usage: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"> limit_conn_zone <span class="re0">$binary_remote_addr</span> zone<span class="sy0">=</span>addr:10m<span class="sy0">;</span></pre> </div> </div><p>Here, an IP address of the client serves as a key. Note that instead of $remote_addr, the $binary_remote_addr variable is used here. The length of the $remote_addr variable's value can range from 7 to 15 bytes, and the stored state occupies either 32 or 64 bytes of memory on 32-bit platforms, and always 64 bytes on 64-bit platforms. The length of the $binary_remote_addr variable's value is always 4 bytes, and the stored state always occupies 32 bytes on 32-bit platforms, and 64 bytes on 64-bit platforms. One megabyte zone can keep about 32 thousand 32-bit states, and about 16 thousand 64-byte states. If the storage for a zone is exhausted, the server will return error 503 (Service Temporarily Unavailable) to all further requests. </p><br><i>Module: HttpLimitConnModule</i> <|start_filename|>resources/docs/directives/fastcgi_hide_header.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpFastcgiModule&amp;action=edit&amp;section=18" title="Edit section: fastcgi hide header">edit</a>]</span> <span class="mw-headline" id="fastcgi_hide_header"> fastcgi_hide_header </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>fastcgi_hide_header</b> <i>field</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_hide_header">fastcgi_hide_header</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 139/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> By default, Nginx does not pass headers &quot;Status&quot; and &quot;X-Accel-...&quot; from the FastCGI process back to the client. This directive can be used to hide other headers as well. </p><p>If the headers &quot;Status&quot; and &quot;X-Accel-...&quot; must be provided, then it is necessary to use directive <a href="#fastcgi_pass_header">fastcgi_pass_header</a> to force them to be returned to the client. </p><br><i>Module: HttpFastcgiModule</i> <|start_filename|>resources/docs/directives/ancient_browser.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpBrowserModule&amp;action=edit&amp;section=3" title="Edit section: ancient browser">edit</a>]</span> <span class="mw-headline" id="ancient_browser"> ancient_browser </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>ancient_browser</b> <i>string</i> ...</td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_browser_module.html#ancient_browser">ancient_browser</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 16/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Directive assigns the substrings, during presence of which in the line &quot;User-agent&quot;, browser are considered as <b>old</b>.<br /> Special line &quot;netscape4&quot; corresponds to regular expression &quot;^Mozilla/[1-4] &quot;. </p><br><i>Module: HttpBrowserModule</i> <|start_filename|>resources/docs/directives/fastcgi_index.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpFastcgiModule&amp;action=edit&amp;section=21" title="Edit section: fastcgi index">edit</a>]</span> <span class="mw-headline" id="fastcgi_index"> fastcgi_index </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>fastcgi_index</b> <i>name</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_index">fastcgi_index</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 160/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> The name of the file which will be appended to the URI and stored in the variable $fastcgi_script_name if URI concludes with a slash. </p><p>For example: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpFcgiModule#fastcgi_index"><span class="kw11">fastcgi_index</span></a> <a href="/NginxHttpCoreModule#index"><span class="kw3">index</span></a>.php<span class="sy0">;</span> <a href="/NginxHttpFcgiModule#fastcgi_param"><span class="kw11">fastcgi_param</span></a> SCRIPT_FILENAME <span class="re0">$document_root</span><span class="re0">$fastcgi_script_name</span><span class="sy0">;</span></pre> </div> </div><p>for the request &quot;/page.php&quot; parameter SCRIPT_FILENAME will be set to &quot;/home/www/scripts/php/page.php&quot;, but for the &quot;/&quot; — &quot;/home/www/scripts/php/index.php&quot;. </p><br><i>Module: HttpFastcgiModule</i> <|start_filename|>resources/docs/directives/valid_referers.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpRefererModule&amp;action=edit&amp;section=3" title="Edit section: valid referers">edit</a>]</span> <span class="mw-headline" id="valid_referers"> valid_referers </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>valid_referers</b> <code>none</code> | <code>blocked</code> | <code>server_names</code> | <i>string</i> ...</td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_referer_module.html#valid_referers">valid_referers</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 13/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> This directive assigns a value of 0 or 1 to the variable <code>$invalid_referer</code> based on the contents of the <code>referer</code> header. </p><p>You can use this to help reduce deep-linking from outside sites. If <code>Referer</code> header is not accounted for in the list of <code>valid_referers</code>, then <code>$invalid_referer</code> will be set to 1 (see example above). </p><p>The parameters can be as follows: </p><ul> <li> <code>none</code> means the absence of &quot;Referer&quot; header. </li> <li> <code>blocked</code> means masked <code>Referer</code> header by firewall, for example, &quot;Referer: XXXXXXX&quot;. </li> <li> server_names is a list of one or more servers. From version 0.5.33 onwards, * wildcards can be used in the server names. </li> </ul><h1><span class="editsection">[<a href="/index.php?title=HttpRefererModule&amp;action=edit&amp;section=4" title="Edit section: References">edit</a>]</span> <span class="mw-headline" id="References"> References </span></h1><p><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_referer_module.html">Original Documentation</a> </p><br><i>Module: HttpRefererModule</i> <|start_filename|>resources/docs/directives/ssl_verify_client.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpSslModule&amp;action=edit&amp;section=14" title="Edit section: ssl verify client">edit</a>]</span> <span class="mw-headline" id="ssl_verify_client"> ssl_verify_client </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>ssl_verify_client</b> <code>on</code> | <code>off</code> | <code>optional</code> | <code>optional_no_ca</code> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>off</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_ssl_module.html#ssl_verify_client">ssl_verify_client</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 114/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> This directive enables the verification of the client identity. Parameter 'optional' checks the client identity using its certificate in case it was made available to the server. (Was 'ask' before 0.8.7 and 0.7.63) </p><br><i>Module: HttpSslModule</i> <|start_filename|>resources/docs/directives/fastcgi_next_upstream.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpFastcgiModule&amp;action=edit&amp;section=25" title="Edit section: fastcgi next upstream">edit</a>]</span> <span class="mw-headline" id="fastcgi_next_upstream"> fastcgi_next_upstream </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>fastcgi_next_upstream</b> <code>error</code> | <code>timeout</code> | <code>invalid_header</code> | <code>http_500</code> | <code>http_503</code> | <code>http_404</code> | <code>off</code> ...</td> </tr> <tr> <td><b>Default:</b></td> <td> <i>error timeout</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_next_upstream">fastcgi_next_upstream</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 191/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> This directive defines in which cases request will be passed to the next server: </p><ul> <li> error — an error occurred during connection to the server, passing request to it or reading server respond header; </li> <li> timeout — a timeout occurred during connection to the server, passing request to it or reading server respond header; </li> <li> invalid_header — server returned empty or invalid answer; </li> <li> http_500 — server returned 500 respond; </li> <li> http_503 — server returned 503 respond; </li> <li> http_404 — server returned 404 respond; </li> <li> off — explicitly forbids passing request to the next server; </li> </ul><p>It should be clear that passing request to the next server is possible only if no data have been yet returned to the client. So, if the error or timeout occurred during the data transmission to the client it's too late to fix it. </p><br><i>Module: HttpFastcgiModule</i> <|start_filename|>resources/docs/directives/limit_rate.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpCoreModule&amp;action=edit&amp;section=28" title="Edit section: limit rate">edit</a>]</span> <span class="mw-headline" id="limit_rate"> limit_rate </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>limit_rate</b> <i>rate</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>0</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location<br />if in location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_core_module.html#limit_rate">limit_rate</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 227/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Directive assigns the speed of transmission of the answer to client. Speed is assigned in the bytes per second. Limitation works only for one connection, i.e., if client opens 2 connections, then total velocity will be 2 times higher then the limit set. </p><p>If it is necessary to limit speed for the part of the clients at the <i>server</i> level, based on some kind of condition - then this directive does not apply. Instead you should specify the limit by assigning the value to the $limit_rate variable, as shown below: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#server"><span class="kw3">server</span></a> <span class="br0">{</span> <a href="/NginxHttpRewriteModule#if"><span class="kw22">if</span></a> <span class="br0">(</span><span class="re0">$slow</span><span class="br0">)</span> <span class="br0">{</span> <a href="/NginxHttpRewriteModule#set"><span class="kw22">set</span></a> <span class="re0">$limit_rate</span> 4k<span class="sy0">;</span> <span class="br0">}</span> <span class="br0">}</span></pre> </div> </div><p>You can also control the rate of individual responses returned by a <code>proxy_pass</code> response (<a href="/HttpProxyModule" title="HttpProxyModule">HttpProxyModule</a>) by setting the <code>X-Accel-Limit-Rate</code> header (<a href="/XSendfile" title="XSendfile">XSendfile</a>). This can be done without a <code>X-Accel-Redirect</code> header. </p><br><i>Module: HttpCoreModule</i> <|start_filename|>resources/docs/directives/dav_methods.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpDavModule&amp;action=edit&amp;section=4" title="Edit section: dav methods">edit</a>]</span> <span class="mw-headline" id="dav_methods"> dav_methods </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>dav_methods</b> <code>off</code> | <code>put</code> | <code>delete</code> | <code>mkcol</code> | <code>copy</code> | <code>move</code> ...</td> </tr> <tr> <td><b>Default:</b></td> <td> <i>off</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_dav_module.html#dav_methods">dav_methods</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 29/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> This directive enables specified HTTP and WebDAV methods. Setting it to <code>off</code> disables all methods, ignoring the remaining parameters. </p><p>For the PUT method the destination file must reside on the same partition as the directory where the temporary file is stored (given by directive <code>client_body_temp_path</code> in the <code>location</code> section). </p><p>When a file is created using the PUT method it is possible to assign the modification date by setting the <code>Date</code> header. </p><br><i>Module: HttpDavModule</i> <|start_filename|>resources/docs/directives/access_log.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpLogModule&amp;action=edit&amp;section=3" title="Edit section: access log">edit</a>]</span> <span class="mw-headline" id="access_log"> access_log </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>access_log</b> <i>path</i> [ <i>format</i> [ <code>buffer</code> = <i>size</i> ]]<br /><b>access_log</b> <code>off</code> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>logs/access.log combined</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location<br />if in location<br />limit_except</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_log_module.html#access_log">access_log</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 13/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> The <b>access_log</b> directive sets the path, format and buffer size for the access log file. Using &quot;off&quot; as the only parameter clears all <b>access_log</b> directives for the current level. If the format is not indicated, it defaults to <a href="/NginxHttpLogModule#log_format_combined" title="NginxHttpLogModule" class="mw-redirect">&quot;combined&quot;</a>. The size of buffer must not exceed the size of the atomic record for writing into the disk file. This size is not limited for FreeBSD 3.0-6.0. </p><p>The log file path can contain variables (version &gt;=0.7.4) but such logs have some limitations: </p><ul> <li> worker user must have permission to create files in; </li> <li> buffering does not work; </li> <li> for each log entry, the file is opened and immediately closed after writing the record. However, descriptors of frequently used files may be stored in <a href="#open_log_file_cache"> open_log_file_cache</a> . Regarding log rotation, it must be kept in mind that over time (which is set by the parameter <i>valid</i> of directive <a href="#open_log_file_cache"> open_log_file_cache</a>), logging can be still continue to the old file. </li> </ul><p>Nginx supports powerful access log separation per location. Accesses can also be output to more than one log at the same time. For more details, see the <a rel="nofollow" class="external text" href="http://thread.gmane.org/gmane.comp.web.nginx.english/9277">Multiple access_log directives in different contexts</a> thread on the mailing list. </p><br><i>Module: HttpLogModule</i> <|start_filename|>resources/docs/directives/expires.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpHeadersModule&amp;action=edit&amp;section=4" title="Edit section: expires">edit</a>]</span> <span class="mw-headline" id="expires"> expires </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>expires</b> [ <code>modified</code> ] <i>time</i> <br /><b>expires</b> <code>epoch</code> | <code>max</code> | <code>off</code> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>off</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location<br />if in location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_headers_module.html#expires">expires</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 20/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Controls whether the response should be marked with an expiry time, and if so, what <a href="/ConfigurationSyntax" title="ConfigurationSyntax">time</a> that is. </p><ul> <li> <code>off</code> prevents changes to the <code>Expires</code> and <code>Cache-Control</code> headers. </li> </ul><ul> <li> <code>epoch</code> sets the <code>Expires</code> header to 1 January, 1970 00:00:01 GMT. </li> </ul><ul> <li> <code>max</code> sets the <code>Expires</code> header to 31 December 2037 23:59:59 GMT, and the <code>Cache-Control</code> max-age to 10 years. </li> </ul><ul> <li> A time without an <code>@</code> prefix specifies an expiry time relative to either the response time (if the time is not preceded with &quot;modified&quot;) or the file's modification time (when &quot;modified&quot; is present — available from versions 0.7.0 &amp; 0.6.32). A negative time can be specified, which sets the <code>Cache-Control</code> header to <code>no-cache</code>. </li> </ul><ul> <li> Times written with an <code>@</code> prefix represent an absolute time-of-day expiry, written in either the form Hh or Hh:Mm, where H ranges from 0 to 24, and M ranges from 0 to 59 (available from versions 0.7.9 &amp; 0.6.34). </li> </ul><p>A non-negative time or time-of-day sets the <code>Cache-Control</code> header to <code>max-age = #</code>, where # is the appropriate time in seconds. </p><p><br /> <b>Note:</b> <code>expires</code> works only for 200, 204, 301, 302, and 304 responses. </p><h1><span class="editsection">[<a href="/index.php?title=HttpHeadersModule&amp;action=edit&amp;section=5" title="Edit section: References">edit</a>]</span> <span class="mw-headline" id="References"> References </span></h1><p><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_headers_module.html">Original Documentation</a> </p><h1><span class="editsection">[<a href="/index.php?title=HttpHeadersModule&amp;action=edit&amp;section=6" title="Edit section: See Also">edit</a>]</span> <span class="mw-headline" id="See_Also"> See Also </span></h1><ul> <li> The third-party <a href="/NginxHttpHeadersMoreModule" title="NginxHttpHeadersMoreModule" class="mw-redirect">headers_more</a> module for adding, replacing, and clearing both input and output headers. </li> </ul><br><i>Module: HttpHeadersModule</i> <|start_filename|>src/net/ishchenko/idea/nginx/platform/NginxCompileParameters.java<|end_filename|> /* * Copyright 2009 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.ishchenko.idea.nginx.platform; /** * Created by IntelliJ IDEA. * User: Max * Date: 01.08.2009 * Time: 0:23:05 */ public class NginxCompileParameters implements Cloneable { private String version; private String prefix; private String configurationPath; private String pidPath; private String httpLogPath; private String errorLogPath; public String getConfigurationPath() { return configurationPath; } public void setConfigurationPath(String configurationPath) { this.configurationPath = configurationPath; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getPidPath() { return pidPath; } public void setPidPath(String pidPath) { this.pidPath = pidPath; } public String getPrefix() { return prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getHttpLogPath() { return httpLogPath; } public void setHttpLogPath(String httpLogPath) { this.httpLogPath = httpLogPath; } public String getErrorLogPath() { return errorLogPath; } public void setErrorLogPath(String errorLogPath) { this.errorLogPath = errorLogPath; } @Override protected NginxCompileParameters clone() { try { return (NginxCompileParameters) super.clone(); } catch (CloneNotSupportedException e) { throw new AssertionError(e); } } } <|start_filename|>resources/docs/directives/limit_zone.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpLimitZoneModule&amp;action=edit&amp;section=3" title="Edit section: limit zone">edit</a>]</span> <span class="mw-headline" id="limit_zone"> limit_zone </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>limit_zone</b> <i>name</i> <i>$variable</i> <i>size</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> http</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_limit_conn_module.html#limit_zone">limit_zone</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 13/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> This directive is made obsolete in version 1.1.8, an equivalent limit_conn_zone directive with a changed syntax should be used instead: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1">limit_conn_zone <span class="re0">$variable</span> zone<span class="sy0">=</span>name:size<span class="sy0">;</span></pre> </div> </div><p>Directive describes the zone, in which the session states are stored.<br /> The numbers of sessions is determined by the assigned variable, it depends on the size of the used Variable and <b>memory_max_size</b> value. </p><p>Example of the use: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpLimitZoneModule#limit_zone"><span class="kw17">limit_zone</span></a> one <span class="re0">$binary_remote_addr</span> 10m<span class="sy0">;</span></pre> </div> </div><p>The address of client is used as the session. Notice that the variable <code>$binary_remote_addr</code> is used instead of <code>$remote_addr</code>. </p><p>The length of the values of the variable of <code>$remote_addr</code> can be from 7 to 15 bytes; therefore size state is equal to 32 or 64 bytes. </p><p>Length of all values of the variable of <code>$binary_remote_addr</code> is always 4 bytes and the size of the state is always 32 bytes. </p><p>When the zone size is 1M then it is possible to handle 32000 sessions with 32 bytes/session. </p><br><i>Module: HttpLimitZoneModule</i> <|start_filename|>resources/docs/directives/map_hash_bucket_size.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpMapModule&amp;action=edit&amp;section=5" title="Edit section: map hash bucket size">edit</a>]</span> <span class="mw-headline" id="map_hash_bucket_size"> map_hash_bucket_size </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>map_hash_bucket_size</b> <i>size</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>32|64|128</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_map_module.html#map_hash_bucket_size">map_hash_bucket_size</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 45/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> The directive sets the maximum size in a hash table to map variables. The default value depends on the size of the cache line processor. More see in the descriptions of hash settings in the <a href="/NginxOptimizations" title="NginxOptimizations" class="mw-redirect">Optimization section</a> . </p><h1><span class="editsection">[<a href="/index.php?title=HttpMapModule&amp;action=edit&amp;section=6" title="Edit section: References">edit</a>]</span> <span class="mw-headline" id="References"> References </span></h1><ul> <li> <a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_map_module.html">Original Documentation</a> </li> <li> <a rel="nofollow" class="external text" href="http://redant.com.au/blog/manage-ssl-redirection-in-nginx-using-maps-and-save-the-universe/">Advanced Usage - Forcing HTTP/HTTPS via maps</a> </li> </ul><br><i>Module: HttpMapModule</i> <|start_filename|>resources/docs/directives/client_body_buffer_size.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpCoreModule&amp;action=edit&amp;section=8" title="Edit section: client body buffer size">edit</a>]</span> <span class="mw-headline" id="client_body_buffer_size"> client_body_buffer_size </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>client_body_buffer_size</b> <i>size</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>8k|16k</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_core_module.html#client_body_buffer_size">client_body_buffer_size</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 60/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> The directive specifies the client request body buffer size. </p><p>If the request body size is more than the buffer size, then the entire (or partial) request body is written into a temporary file. </p><p>The default size is equal to page size times 2. Depending on the platform, the page size is either 8K or 16K. </p><p>When the <i>Content-Length</i> request header specifies a smaller size value than the buffer size, then Nginx will use the smaller one. As a result, Nginx will <b>not</b> always allocate a buffer of this buffer size for every request. </p><br><i>Module: HttpCoreModule</i> <|start_filename|>resources/docs/directives/limit_except.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpCoreModule&amp;action=edit&amp;section=27" title="Edit section: limit except">edit</a>]</span> <span class="mw-headline" id="limit_except"> limit_except </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>limit_except</b> <i>method</i> ... { ... }</td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_core_module.html#limit_except">limit_except</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 217/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Limits which HTTP methods are allowed for a given request path/location. </p><p>For the limitation can be used the directives of modules ngx_http_access_module and ngx_http_auth_basic_module: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#limit_except"><span class="kw3">limit_except</span></a> GET <span class="br0">{</span> <a href="/NginxHttpAccessModule#allow"><span class="kw5">allow</span></a> 192.168.1.0/<span class="nu0">32</span><span class="sy0">;</span> <a href="/NginxHttpAccessModule#deny"><span class="kw5">deny</span></a> all<span class="sy0">;</span> <span class="br0">}</span></pre> </div> </div><br><i>Module: HttpCoreModule</i> <|start_filename|>resources/docs/directives/uninitialized_variable_warn.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpRewriteModule&amp;action=edit&amp;section=9" title="Edit section: uninitialized variable warn">edit</a>]</span> <span class="mw-headline" id="uninitialized_variable_warn"> uninitialized_variable_warn </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>uninitialized_variable_warn</b> <code>on</code> | <code>off</code> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>on</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location<br />if</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_rewrite_module.html#uninitialized_variable_warn">uninitialized_variable_warn</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 106/1000000 Post-expand include size: 186/2097152 bytes Template argument size: 90/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Enables or disables logging of warnings about noninitialized variables. </p><h1><span class="editsection">[<a href="/index.php?title=HttpRewriteModule&amp;action=edit&amp;section=10" title="Edit section: Internal implementation">edit</a>]</span> <span class="mw-headline" id="Internal_implementation"> Internal implementation </span></h1><p>Internally, the rewrite directives are compiled at the time the configuration file is loaded into internal codes, usable during the request by the interpreter. </p><p>This interpreter is a simple stack virtual machine. For example, the directive: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#location"><span class="kw3">location</span></a> /download/ <span class="br0">{</span> <a href="/NginxHttpRewriteModule#if"><span class="kw22">if</span></a> <span class="br0">(</span><span class="re0">$forbidden</span><span class="br0">)</span> <span class="br0">{</span> <a href="/NginxHttpRewriteModule#return"><span class="kw22">return</span></a> <span class="nu0">403</span><span class="sy0">;</span> <span class="br0">}</span> <a href="/NginxHttpRewriteModule#if"><span class="kw22">if</span></a> <span class="br0">(</span><span class="re0">$slow</span><span class="br0">)</span> <span class="br0">{</span> <a href="/NginxHttpCoreModule#limit_rate"><span class="kw3">limit_rate</span></a> 10k<span class="sy0">;</span> <span class="br0">}</span> <a href="/NginxHttpRewriteModule#rewrite"><span class="kw22">rewrite</span></a> ^/<span class="br0">(</span>download/.*<span class="br0">)</span>/media/<span class="br0">(</span>.*<span class="br0">)</span>\..*$ /$<span class="nu0">1</span>/mp3/$<span class="nu0">2</span>.mp3 <a href="/NginxHttpRewriteModule#break"><span class="kw22">break</span></a><span class="sy0">;</span> <span class="br0">}</span></pre> </div> </div><p>will be compiled into this sequence: </p><pre> variable $forbidden checking to zero recovery 403 completion of entire code variable $slow checking to zero checkings of regular expression copying &quot;/&quot; copying $1 copying &quot;/mp3/&quot; copying $2 copying &quot;.mp3&quot; completion of regular expression completion of entire sequence </pre><p>Note that there is no code for directive limit_rate, since it does not refer to module ngx_http_rewrite_module. The &quot;if&quot; block exists in the same part of the configuration as the &quot;location&quot; directive. </p><p>If $slow is true, then what's inside the &quot;if&quot; block is evaluated, and in this configuration limit_rate it is equal to 10k. </p><p>Directive: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"> <a href="/NginxHttpRewriteModule#rewrite"><span class="kw22">rewrite</span></a> ^/<span class="br0">(</span>download/.*<span class="br0">)</span>/media/<span class="br0">(</span>.*<span class="br0">)</span>\..*$ /$<span class="nu0">1</span>/mp3/$<span class="nu0">2</span>.mp3 <a href="/NginxHttpRewriteModule#break"><span class="kw22">break</span></a><span class="sy0">;</span></pre> </div> </div><p>It is possible to reduce the sequence, if in the regular expression we include the first slash inside the parentheses: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"> <a href="/NginxHttpRewriteModule#rewrite"><span class="kw22">rewrite</span></a> ^<span class="br0">(</span>/download/.*<span class="br0">)</span>/media/<span class="br0">(</span>.*<span class="br0">)</span>\..*$ $<span class="nu0">1</span>/mp3/$<span class="nu0">2</span>.mp3 <a href="/NginxHttpRewriteModule#break"><span class="kw22">break</span></a><span class="sy0">;</span></pre> </div> </div><p>then the sequence will appear like this: </p><pre> checking regular expression copying $1 copying &quot;/mp3/&quot; copying $2 copying &quot;.mp3&quot; completion of regular expression completion of entire code </pre><h1><span class="editsection">[<a href="/index.php?title=HttpRewriteModule&amp;action=edit&amp;section=11" title="Edit section: References">edit</a>]</span> <span class="mw-headline" id="References"> References </span></h1><p><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_rewrite_module.html">Original Documentation</a> </p><p><a rel="nofollow" class="external text" href="http://www.pcre.org/pcre.txt">PCRE Man Page in Plain Text</a> </p><p><br /> <a rel="nofollow" class="external text" href="http://regexone.com/">RegexOne&raquo; Learn regular expressions with simple, interactive examples.</a> </p><p><a rel="nofollow" class="external text" href="http://regexpal.com/">RegexPal — a JavaScript regular expression tester</a> </p><br><i>Module: HttpRewriteModule</i> <|start_filename|>resources/docs/directives/client_body_in_file_only.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpCoreModule&amp;action=edit&amp;section=6" title="Edit section: client body in file only">edit</a>]</span> <span class="mw-headline" id="client_body_in_file_only"> client_body_in_file_only </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>client_body_in_file_only</b> <code>on</code> | <code>clean</code> | <code>off</code> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>off</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_core_module.html#client_body_in_file_only">client_body_in_file_only</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 46/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> The directive forces nginx to always store a client request body into a temporary disk file even if the body is actually of 0 size. </p><p>Please note that the file will <b>NOT</b> be removed at request completion if the directive is enabled. </p><p>This directive can be used for debugging and for the <code>$r-&gt;request_body_file</code> method in the <a href="/EmbeddedPerlModule" title="EmbeddedPerlModule" class="mw-redirect">Embedded Perl module</a>. </p><br><i>Module: HttpCoreModule</i> <|start_filename|>resources/docs/directives/charset.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpCharsetModule&amp;action=edit&amp;section=3" title="Edit section: charset">edit</a>]</span> <span class="mw-headline" id="charset"> charset </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>charset</b> <i>charset</i> | <code>off</code> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>off</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location<br />if in location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_charset_module.html#charset">charset</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 13/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> The directive charset adds the line &quot;Content-Type&quot; into response-header with indicated encoding. If this encoding is differed from that indicated in directive source_charset, then reencoding is carried out. The parameter &quot;off&quot; deactivate the insertation of the line &quot;Content-Type&quot; in the response-header. </p><p><br /> </p><br><i>Module: HttpCharsetModule</i> <|start_filename|>resources/docs/directives/userid_expires.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpUseridModule&amp;action=edit&amp;section=5" title="Edit section: userid expires">edit</a>]</span> <span class="mw-headline" id="userid_expires"> userid_expires </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>userid_expires</b> <i>time</i> | <code>max</code> </td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_userid_module.html#userid_expires">userid_expires</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 27/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Sets the expiration time for the cookie. </p><p>The parameter set &amp; send-out browser expiration time for cookie. Value &quot;max&quot; assigns the time on 31 December, 2037, 23:55:55 gmt. This is the maximum time that older browsers understand. </p><br><i>Module: HttpUseridModule</i> <|start_filename|>resources/docs/directives/ip_hash.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpUpstreamModule&amp;action=edit&amp;section=3" title="Edit section: ip hash">edit</a>]</span> <span class="mw-headline" id="ip_hash"> ip_hash </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>ip_hash</b> </td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> upstream</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_upstream_module.html#ip_hash">ip_hash</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 13/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> This directive causes requests to be distributed between upstreams based on the IP-address of the client. <br /> The key for the hash is the class-C network address or the entire IPv6-address of the client. IPv6 is supported for ip_hash since 1.3.2 or 1.2.2. This method guarantees that the client request will always be transferred to the same server. But if this server is considered inoperative, then the request of this client will be transferred to another server. This gives a high probability clients will always connect to the same server. </p><p>It is not possible to combine ip_hash and weight methods for connection distribution until nginx 1.3.1 or 1.2.2. If one of the servers must be removed for some time, you must mark that server as *down*. </p><p>For example: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpUpstreamModule#upstream"><span class="kw4">upstream</span></a> backend <span class="br0">{</span> <a href="/NginxHttpUpstreamModule#ip_hash"><span class="kw4">ip_hash</span></a><span class="sy0">;</span> <a href="/NginxHttpCoreModule#server"><span class="kw3">server</span></a> backend1.example.com weight<span class="sy0">=</span><span class="nu0">2</span><span class="sy0">;</span> <a href="/NginxHttpCoreModule#server"><span class="kw3">server</span></a> backend2.example.com<span class="sy0">;</span> <a href="/NginxHttpCoreModule#server"><span class="kw3">server</span></a> backend3.example.com down<span class="sy0">;</span> <a href="/NginxHttpCoreModule#server"><span class="kw3">server</span></a> backend4.example.com<span class="sy0">;</span> <span class="br0">}</span></pre> </div> </div><br><i>Module: HttpUpstreamModule</i> <|start_filename|>src/net/ishchenko/idea/nginx/NginxLanguage.java<|end_filename|> /* * Copyright 2009 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.ishchenko.idea.nginx; import com.intellij.lang.Language; import com.intellij.openapi.fileTypes.SingleLazyInstanceSyntaxHighlighterFactory; import com.intellij.openapi.fileTypes.SyntaxHighlighter; import com.intellij.openapi.fileTypes.SyntaxHighlighterFactory; import net.ishchenko.idea.nginx.lexer.NginxSyntaxHighlighter; import org.jetbrains.annotations.NotNull; /** * Created by IntelliJ IDEA. * User: Max * Date: 04.07.2009 * Time: 1:09:20 */ public class NginxLanguage extends Language { public static final NginxLanguage INSTANCE = new NginxLanguage(); private NginxLanguage() { super("nginx"); SyntaxHighlighterFactory.LANGUAGE_FACTORY.addExplicitExtension(this, new SingleLazyInstanceSyntaxHighlighterFactory() { @NotNull protected SyntaxHighlighter createHighlighter() { return new NginxSyntaxHighlighter(); } }); } } <|start_filename|>resources/docs/directives/map.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpMapModule&amp;action=edit&amp;section=3" title="Edit section: map">edit</a>]</span> <span class="mw-headline" id="map"> map </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>map</b> <i>string</i> <i>$variable</i> { ... }</td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> http</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_map_module.html#map">map</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 16/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> <b>map</b> defines the mapping table which will be used to set a variable. </p><p>The table has two columns, <b>pattern</b> and <b>value</b>. </p><p>Since 0.9.6, regular expressions can be used as patterns using a ~ prefix. </p><p>Since 1.0.4, case insensitive regular expressions can be used by prefixing the pattern with ~*. </p><pre> map $uri $myvalue { /aa /mapped_aa; ~^/aa/(?P&lt;suffix&gt;.*)$ $suffix; } </pre><p>If you need to have a tilde to start the pattern but not have it be a regular expression, the pattern can be prefixed with a backslash ('\'): </p><pre> map $http_referer $myvalue { Mozilla 1234; \~Mozilla 5678; } </pre><p>There are three special parameters: </p><ul> <li> default — defines the value to be used where no match is found. </li> <li> hostnames — it allows for an easier matching of values like host names, names with a starting dot may match exact host names and host names ending with the value, for example: </li> </ul><pre> *.example.com 1; </pre><p>Instead of two entries </p><pre> example.com 1; *.example.com 1; </pre><p>we can use only one </p><pre> .example.com 1; </pre><ul> <li> include — include values from a file. Multiple includes may be used. </li> </ul><br><i>Module: HttpMapModule</i> <|start_filename|>resources/docs/directives/request_pool_size.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpCoreModule&amp;action=edit&amp;section=51" title="Edit section: request pool size">edit</a>]</span> <span class="mw-headline" id="request_pool_size"> request_pool_size </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>request_pool_size</b> <i>size</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>4k</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_core_module.html#request_pool_size">request_pool_size</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 421/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> The directive is used to allocate memory per request. The pool is used for small allocations. If a block is bigger than pool size or bigger than page size, then it is allocated outside the pool. If there is not enough memory for small allocation inside pool, then a new block of the same pool size is allocated. This directive has only a very small effect. (source <a rel="nofollow" class="external free" href="http://markmail.org/message/b2kmrluscevimpba">http://markmail.org/message/b2kmrluscevimpba</a>) </p><br><i>Module: HttpCoreModule</i> <|start_filename|>resources/docs/directives/keepalive_timeout.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpCoreModule&amp;action=edit&amp;section=24" title="Edit section: keepalive timeout">edit</a>]</span> <span class="mw-headline" id="keepalive_timeout"> keepalive_timeout </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>keepalive_timeout</b> <i>timeout</i> [ <i>header_timeout</i> ]</td> </tr> <tr> <td><b>Default:</b></td> <td> <i>75s</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_core_module.html#keepalive_timeout">keepalive_timeout</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 196/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> The first parameter assigns the timeout for keep-alive connections with the client. The server will close connections after this time. </p><p>The optional second parameter assigns the <code>time</code> value in the header <code>Keep-Alive: timeout=time</code> of the response. This header can convince some browsers to close the connection, so that the server does not have to. Without this parameter, nginx does not send a <code>Keep-Alive</code> header (though this is not what makes a connection &quot;keep-alive&quot;). </p><p>The parameters can differ from each other. </p><p>Notes on how browsers handle the <code>Keep-Alive</code> header: </p><ul> <li> MSIE and Opera ignore the &quot;Keep-Alive: timeout=&lt;N&gt;&quot; header. </li> <li> MSIE keeps the connection alive for about 60-65 seconds, then sends a TCP RST. </li> <li> Opera keeps the connection alive for a long time. </li> <li> Mozilla keeps the connection alive for N plus about 1-10 seconds. </li> <li> Konqueror keeps the connection alive for about N seconds. </li> </ul><br><i>Module: HttpCoreModule</i> <|start_filename|>resources/docs/directives/add_header.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpHeadersModule&amp;action=edit&amp;section=3" title="Edit section: add header">edit</a>]</span> <span class="mw-headline" id="add_header"> add_header </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>add_header</b> <i>name</i> <i>value</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location<br />if in location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_headers_module.html#add_header">add_header</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 13/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Adds headers to the HTTP response when the response code is equal to 200, 204, 301, 302 or 304. </p><p>Note that for headers other than <code>Last-Modified</code>, it just appends a new header entry to the output header list. So you can't use this directive to rewrite existing headers like <code>Server</code>. Use the <a href="/NginxHttpHeadersMoreModule" title="NginxHttpHeadersMoreModule" class="mw-redirect">headers_more</a> module for it. </p><br><i>Module: HttpHeadersModule</i> <|start_filename|>resources/docs/directives/return.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpRewriteModule&amp;action=edit&amp;section=5" title="Edit section: return">edit</a>]</span> <span class="mw-headline" id="return"> return </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>return</b> <i>code</i> [ <i>text</i> ]<br /><b>return</b> <i>code</i> <i>URL</i> <br /><b>return</b> <i>URL</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> server<br />location<br />if</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_rewrite_module.html#return">return</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 30/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> This directive concludes execution of the rules and returns the status code indicated to client. It is possible to use any http return code, ranging in number from 0-999. Furthermore, nonstandard code 444 closes the connection without sending any headers. </p><br><i>Module: HttpRewriteModule</i> <|start_filename|>resources/docs/directives/Known_Problems.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpPerlModule&amp;action=edit&amp;section=3" title="Edit section: Known Problems">edit</a>]</span> <span class="mw-headline" id="Known_Problems"> Known Problems </span></h2><p>This module is experimental; therefore anything is possible and bugs are likely. </p><ol> <li> If a Perl module performs protracted operation, (for example DNS lookups, database queries, etc), then the worker process that is running the Perl script is completely tied up for the duration of script. Therefore embedded Perl scripts should be extremely careful to limit themselves to short, predictable operations. </li> <li> It's possible for Nginx to leak memory if you reload the configuration file (via 'kill -HUP &lt;pid&gt;'). </li> </ol><p>Example: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#http"><span class="kw3">http</span></a> <span class="br0">{</span> <a href="/NginxHttpEmbeddedPerlModule#perl_modules"><span class="kw26">perl_modules</span></a> <a href="/NginxHttpEmbeddedPerlModule#perl"><span class="kw26">perl</span></a>/lib<span class="sy0">;</span> <a href="/NginxHttpEmbeddedPerlModule#perl_require"><span class="kw26">perl_require</span></a> hello.pm<span class="sy0">;</span> &nbsp; <a href="/NginxHttpEmbeddedPerlModule#perl_set"><span class="kw26">perl_set</span></a> <span class="re0">$msie6</span> <span class="st0">' sub { my $r = shift; my $ua = $r-&gt;header_in(&quot;User-Agent&quot;); return &quot;&quot; if $ua =~ /Opera/; return &quot;1&quot; if $ua =~ / MSIE [6-9] <span class="es0">\.</span><span class="es0">\d</span>+/; return &quot;&quot;; } '</span><span class="sy0">;</span> &nbsp; <a href="/NginxHttpCoreModule#server"><span class="kw3">server</span></a> <span class="br0">{</span> <a href="/NginxHttpCoreModule#location"><span class="kw3">location</span></a> / <span class="br0">{</span> <a href="/NginxHttpEmbeddedPerlModule#perl"><span class="kw26">perl</span></a> hello::handler<span class="sy0">;</span> <span class="br0">}</span> <span class="br0">}</span> <span class="br0">}</span></pre> </div> </div><p>perl/lib/hello.pm: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="perl source-perl"> <pre class="de1"><a href="http://perldoc.perl.org/functions/package.html"><span class="kw3">package</span></a> hello<span class="sy0">;</span> <span class="kw2">use</span> nginx<span class="sy0">;</span> &nbsp; <span class="kw2">sub</span> handler <span class="br0">{</span> <span class="kw1">my</span> <span class="re0">$r</span> <span class="sy0">=</span> <a href="http://perldoc.perl.org/functions/shift.html"><span class="kw3">shift</span></a><span class="sy0">;</span> <span class="re0">$r</span><span class="sy0">-&gt;</span><span class="me1">send_http_header</span><span class="br0">(</span><span class="st0">&quot;text/html&quot;</span><span class="br0">)</span><span class="sy0">;</span> <a href="http://perldoc.perl.org/functions/return.html"><span class="kw3">return</span></a> OK <span class="kw1">if</span> <span class="re0">$r</span><span class="sy0">-&gt;</span><span class="me1">header_only</span><span class="sy0">;</span> &nbsp; <span class="re0">$r</span><span class="sy0">-&gt;</span><span class="me1">print</span><span class="br0">(</span><span class="st0">&quot;hello!<span class="es0">\n</span>&lt;br/&gt;&quot;</span><span class="br0">)</span><span class="sy0">;</span> <span class="re0">$r</span><span class="sy0">-&gt;</span><span class="me1">rflush</span><span class="sy0">;</span> &nbsp; <span class="kw1">if</span> <span class="br0">(</span><span class="sy0">-</span>f <span class="re0">$r</span><span class="sy0">-&gt;</span><span class="me1">filename</span> <span class="kw1">or</span> <span class="sy0">-</span>d _<span class="br0">)</span> <span class="br0">{</span> <span class="re0">$r</span><span class="sy0">-&gt;</span><span class="me1">print</span><span class="br0">(</span><span class="re0">$r</span><span class="sy0">-&gt;</span><span class="me1">uri</span><span class="sy0">,</span> <span class="st0">&quot; exists!<span class="es0">\n</span>&quot;</span><span class="br0">)</span><span class="sy0">;</span> <span class="br0">}</span> &nbsp; <a href="http://perldoc.perl.org/functions/return.html"><span class="kw3">return</span></a> OK<span class="sy0">;</span> <span class="br0">}</span> &nbsp; <span class="nu0">1</span><span class="sy0">;</span> <span class="kw2">__END__</span></pre> </div> </div><h1><span class="editsection">[<a href="/index.php?title=HttpPerlModule&amp;action=edit&amp;section=4" title="Edit section: Directives">edit</a>]</span> <span class="mw-headline" id="Directives"> Directives </span></h1><br><i>Module: HttpPerlModule</i> <|start_filename|>resources/docs/directives/memcached_read_timeout.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpMemcachedModule&amp;action=edit&amp;section=5" title="Edit section: memcached read timeout">edit</a>]</span> <span class="mw-headline" id="memcached_read_timeout"> memcached_read_timeout </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>memcached_read_timeout</b> <i>time</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>60s</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_memcached_module.html#memcached_read_timeout">memcached_read_timeout</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 27/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> The timeout for reading from memcached. </p><br><i>Module: HttpMemcachedModule</i> <|start_filename|>resources/docs/directives/proxy_next_upstream.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpProxyModule&amp;action=edit&amp;section=30" title="Edit section: proxy next upstream">edit</a>]</span> <span class="mw-headline" id="proxy_next_upstream"> proxy_next_upstream </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>proxy_next_upstream</b> <code>error</code> | <code>timeout</code> | <code>invalid_header</code> | <code>http_500</code> | <code>http_502</code> | <code>http_503</code> | <code>http_504</code> | <code>http_404</code> | <code>off</code> ...</td> </tr> <tr> <td><b>Default:</b></td> <td> <i>error timeout</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_next_upstream">proxy_next_upstream</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 220/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Directive determines in what cases the request will be transmitted to the next server: </p><ul> <li> error — an error has occurred while connecting to the server, sending a request to it, or reading its response; </li> <li> timeout — occurred timeout during the connection with the server, transfer the request or while reading response from the server; </li> <li> invalid_header — server returned a empty or incorrect answer; </li> <li> http_500 — server returned answer with code 500 </li> <li> http_502 — server returned answer with code 502 </li> <li> http_503 — server returned answer with code 503 </li> <li> http_504 — server returned answer with code 504 </li> <li> http_404 — server returned answer with code 404 </li> <li> off — it forbids the request transfer to the next server </li> </ul><p>Transferring the request to the next server is only possible when nothing has been transferred to the client -- that is, if an error or timeout arises in the middle of the transfer of the request, then it is not possible to retry the current request on a different server. </p><br><i>Module: HttpProxyModule</i> <|start_filename|>src/net/ishchenko/idea/nginx/psi/impl/NginxLuaContextImpl.java<|end_filename|> package net.ishchenko.idea.nginx.psi.impl; import com.intellij.lang.ASTNode; import com.intellij.psi.LiteralTextEscaper; import com.intellij.psi.PsiLanguageInjectionHost; import net.ishchenko.idea.nginx.NginxKeywordsManager; import net.ishchenko.idea.nginx.injection.LuaTextEscaper; import net.ishchenko.idea.nginx.lexer.NginxElementTypes; import net.ishchenko.idea.nginx.psi.NginxComplexValue; import net.ishchenko.idea.nginx.psi.NginxContext; import net.ishchenko.idea.nginx.psi.NginxDirectiveName; import net.ishchenko.idea.nginx.psi.NginxLuaContext; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; import static net.ishchenko.idea.nginx.psi.impl.NginxDirectiveImpl.DIRECTIVE_VALUE_TOKENS; public class NginxLuaContextImpl extends NginxElementImpl implements NginxLuaContext { public NginxLuaContextImpl(@NotNull ASTNode node) { super(node); } @Override public boolean isValidHost() { return true; } @Override public PsiLanguageInjectionHost updateText(@NotNull String text) { return null; } @NotNull @Override public LiteralTextEscaper<? extends PsiLanguageInjectionHost> createLiteralTextEscaper() { return new LuaTextEscaper(this); } @NotNull @Override public String getNameString() { return getText(); } @NotNull @Override public NginxDirectiveName getDirectiveName() { // TODO don't extend NginxDirectiveName return (NginxDirectiveName) this; } @Nullable @Override public NginxContext getDirectiveContext() { ASTNode contextNode = getNode().findChildByType(NginxElementTypes.CONTEXT); return contextNode != null ? (NginxContext) contextNode.getPsi() : null; } @Nullable @Override public NginxContext getParentContext() { ASTNode parentNode = getNode().getTreeParent(); if (parentNode.getPsi() instanceof NginxContext) { return (NginxContext) parentNode.getPsi(); } else { return null; } } @NotNull @Override public List<NginxComplexValue> getValues() { ArrayList<NginxComplexValue> result = new ArrayList<>(); for (ASTNode value : getNode().getChildren(DIRECTIVE_VALUE_TOKENS)) { result.add((NginxComplexValue) value.getPsi()); } return result; } @Override public boolean isInChaosContext() { return getParentContext() != null && NginxKeywordsManager.CHAOS_DIRECTIVES.contains(getParentContext().getDirective().getNameString()); } @Override public boolean hasContext() { return getDirectiveContext() != null; } } <|start_filename|>resources/docs/directives/fastcgi_cache_use_stale.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpFastcgiModule&amp;action=edit&amp;section=15" title="Edit section: fastcgi cache use stale">edit</a>]</span> <span class="mw-headline" id="fastcgi_cache_use_stale"> fastcgi_cache_use_stale </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>fastcgi_cache_use_stale</b> <code>error</code> | <code>timeout</code> | <code>invalid_header</code> | <code>updating</code> | <code>http_500</code> | <code>http_503</code> | <code>http_404</code> | <code>off</code> ...</td> </tr> <tr> <td><b>Default:</b></td> <td> <i>off</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_cache_use_stale">fastcgi_cache_use_stale</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 109/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Determines whether or not Nginx will serve stale cached data in case of gateway event such as error, timeout etc. </p><br><i>Module: HttpFastcgiModule</i> <|start_filename|>resources/docs/directives/fastcgi_cache_valid.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpFastcgiModule&amp;action=edit&amp;section=16" title="Edit section: fastcgi cache valid">edit</a>]</span> <span class="mw-headline" id="fastcgi_cache_valid"> fastcgi_cache_valid </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>fastcgi_cache_valid</b> [ <i>code</i> ...] <i>time</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_cache_valid">fastcgi_cache_valid</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 116/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Directive sets caching period for the specified http return codes. For example: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpFcgiModule#fastcgi_cache_valid"><span class="kw11">fastcgi_cache_valid</span></a> <span class="nu0">200</span> <span class="nu0">302</span> 10m<span class="sy0">;</span> <a href="/NginxHttpFcgiModule#fastcgi_cache_valid"><span class="kw11">fastcgi_cache_valid</span></a> <span class="nu0">404</span> 1m<span class="sy0">;</span></pre> </div> </div><p>sets caching period of 10 minutes for return codes 200 and 302 and 1 minute for the 404 code. </p><p>In case only caching period is specified: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpFcgiModule#fastcgi_cache_valid"><span class="kw11">fastcgi_cache_valid</span></a> 5m<span class="sy0">;</span></pre> </div> </div><p>the default behavior is to cache only replies with the codes 200, 301 and 302. </p><p>It's also possible to cache all the replies by specifying code &quot;any&quot;: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1">&nbsp; <a href="/NginxHttpFcgiModule#fastcgi_cache_valid"><span class="kw11">fastcgi_cache_valid</span></a> <span class="nu0">200</span> <span class="nu0">302</span> 10m<span class="sy0">;</span> <a href="/NginxHttpFcgiModule#fastcgi_cache_valid"><span class="kw11">fastcgi_cache_valid</span></a> <span class="nu0">301</span> 1h<span class="sy0">;</span> <a href="/NginxHttpFcgiModule#fastcgi_cache_valid"><span class="kw11">fastcgi_cache_valid</span></a> any 1m<span class="sy0">;</span></pre> </div> </div><br><i>Module: HttpFastcgiModule</i> <|start_filename|>resources/docs/directives/pid.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=CoreModule&amp;action=edit&amp;section=11" title="Edit section: pid">edit</a>]</span> <span class="mw-headline" id="pid"> pid </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>pid</b> <i>file</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>nginx.pid</i></td> </tr> <tr> <td><b>Context:</b></td> <td> main</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/ngx_core_module.html#pid">pid</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 81/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Example: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#pid"><span class="kw1">pid</span></a> /var/log/nginx.<a href="/NginxHttpCoreModule#pid"><span class="kw1">pid</span></a><span class="sy0">;</span></pre> </div> </div><p>The pid-file. It can be used for the kill-command to send signals to nginx, eg: to reload the config: <code>kill -HUP `cat /var/log/nginx.pid`</code> </p><br><i>Module: CoreModule</i> <|start_filename|>resources/docs/directives/timer_resolution.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=CoreModule&amp;action=edit&amp;section=13" title="Edit section: timer resolution">edit</a>]</span> <span class="mw-headline" id="timer_resolution"> timer_resolution </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>timer_resolution</b> <i>interval</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> main</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/ngx_core_module.html#timer_resolution">timer_resolution</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 101/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Example: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#timer_resolution"><span class="kw1">timer_resolution</span></a> 100ms<span class="sy0">;</span></pre> </div> </div><p>The directive allows to decrease number gettimeofday() syscalls. By default gettimeofday() is called after each return from kevent(), epoll, /dev/poll, select(), poll(). </p><p>But if you need an exact time in logs when logging $upstream_response_time, or $msec variables, then you should use <code>timer_resolution</code>. </p><p><br /> </p><br><i>Module: CoreModule</i> <|start_filename|>resources/docs/directives/mp4_max_buffer_size.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpMp4Module&amp;action=edit&amp;section=6" title="Edit section: mp4 max buffer size">edit</a>]</span> <span class="mw-headline" id="mp4_max_buffer_size"> mp4_max_buffer_size</span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>mp4_max_buffer_size</b> <i>size</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>10M</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_mp4_module.html#mp4_max_buffer_size">mp4_max_buffer_size</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 34/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Sets the maxium buffer size used for processing mp4 file. If the meta data exceeds this size Nginx will return a 500 status code and log an error resembling the following: </p><pre> &quot;/video/file.mp4&quot; mp4 moov atom is too large: 12583268, you may want to increase mp4_max_buffer_size </pre><h1><span class="editsection">[<a href="/index.php?title=HttpMp4Module&amp;action=edit&amp;section=7" title="Edit section: Notes">edit</a>]</span> <span class="mw-headline" id="Notes"> Notes </span></h1><p>This module does not as of 1.3.4 support seeking through embedded subtitle tracks. Though this is a forced limitation and it works fine without it. There is a patch to enable this functionality. </p><p>Update: This is now fixed in 1.3.5 and no longer required. </p><pre> --- a/src/http/modules/ngx_http_mp4_module.c +++ b/src/http/modules/ngx_http_mp4_module.c @@ -1842,14 +1842,6 @@ ngx_http_mp4_read_stsd_atom(ngx_http_mp4 ngx_mp4_get_32value(stsd_atom-&gt;entries), 4, stsd_atom-&gt;media_name); - /* supported media format: &quot;avc1&quot; (H.264) and &quot;mp4a&quot; (MPEG-4/AAC) */ - - if (ngx_strncmp(stsd_atom-&gt;media_name, &quot;avc1&quot;, 4)&nbsp;!= 0 - &amp;&amp; ngx_strncmp(stsd_atom-&gt;media_name, &quot;mp4a&quot;, 4)&nbsp;!= 0) - { - return NGX_DECLINED; - } - trak = ngx_mp4_last_trak(mp4); atom = &amp;trak-&gt;stsd_atom_buf; </pre><p>Please note that to avoid excessive seeking time the MP4 files have to use sample based interleaving of the media tracks and hint tracks. MP4Box provides this functionality through the -tight parameter. </p><p>For reference please see the following bug report: <a rel="nofollow" class="external free" href="http://trac.nginx.org/nginx/ticket/194">http://trac.nginx.org/nginx/ticket/194</a> </p><h1><span class="editsection">[<a href="/index.php?title=HttpMp4Module&amp;action=edit&amp;section=8" title="Edit section: References">edit</a>]</span> <span class="mw-headline" id="References"> References </span></h1><p>Please see the following page for more details: <a rel="nofollow" class="external free" href="http://nginx.org/en/docs/http/ngx_http_mp4_module.html">http://nginx.org/en/docs/http/ngx_http_mp4_module.html</a> </p><br><i>Module: HttpMp4Module</i> <|start_filename|>resources/docs/directives/proxy_cache_valid.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpProxyModule&amp;action=edit&amp;section=17" title="Edit section: proxy cache valid">edit</a>]</span> <span class="mw-headline" id="proxy_cache_valid"> proxy_cache_valid </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>proxy_cache_valid</b> [ <i>code</i> ...] <i>time</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_cache_valid">proxy_cache_valid</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 126/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> This directive sets the time for caching different replies. Example: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpProxyModule#proxy_cache_valid"><span class="kw21">proxy_cache_valid</span></a> <span class="nu0">200</span> <span class="nu0">302</span> 10m<span class="sy0">;</span> <a href="/NginxHttpProxyModule#proxy_cache_valid"><span class="kw21">proxy_cache_valid</span></a> <span class="nu0">404</span> 1m<span class="sy0">;</span></pre> </div> </div><p>sets 10 minutes cache time for replies with code 200 and 302, and 1 minute for 404s. </p><p>If only time is specified: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpProxyModule#proxy_cache_valid"><span class="kw21">proxy_cache_valid</span></a> 5m<span class="sy0">;</span></pre> </div> </div><p>then only replies with codes 200, 301 and 302 will be cached. </p><p>Also it is possible to cache any replies with parameter &quot;any&quot;: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpProxyModule#proxy_cache_valid"><span class="kw21">proxy_cache_valid</span></a> <span class="nu0">200</span> <span class="nu0">302</span> 10m<span class="sy0">;</span> <a href="/NginxHttpProxyModule#proxy_cache_valid"><span class="kw21">proxy_cache_valid</span></a> <span class="nu0">301</span> 1h<span class="sy0">;</span> <a href="/NginxHttpProxyModule#proxy_cache_valid"><span class="kw21">proxy_cache_valid</span></a> any 1m<span class="sy0">;</span></pre> </div> </div><p>Upstream cache-related directives have priority over proxy_cache_valid value, in particular the order is (<a rel="nofollow" class="external text" href="http://forum.nginx.org/read.php?2,2182,2185#msg-2185">from Igor</a>): </p><ol> <li> X-Accel-Expires </li> <li> Expires/Cache-Control </li> <li> proxy_cache_valid </li> </ol><p>The order in which your backend return HTTP headers change cache behaviour. Read <a rel="nofollow" class="external text" href="http://www.ruby-forum.com/topic/3707266">this post</a> for details. </p><p>You may ignore the headers using </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1">proxy_ignore_headers X-Accel-<a href="/NginxHttpHeadersModule#Expires"><span class="kw14">Expires</span></a> <a href="/NginxHttpHeadersModule#Expires"><span class="kw14">Expires</span></a> Cache-Control<span class="sy0">;</span></pre> </div> </div><p>Concerning If-Modified / Last-Modified since behaviour, please remember that by default nginx sends 304 only if L-M == I-M-S. Controlled by directive <a href="/HttpCoreModule#if_modified_since" title="HttpCoreModule">if_modified_since</a> [off|exact|before] </p><p>Note: you must set this option for any persistent caching to occur. </p><br><i>Module: HttpProxyModule</i> <|start_filename|>src/net/ishchenko/idea/nginx/NginxDocumentationProvider.java<|end_filename|> package net.ishchenko.idea.nginx; import com.intellij.lang.documentation.DocumentationProvider; import com.intellij.openapi.diagnostic.Logger; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiManager; import net.ishchenko.idea.nginx.psi.NginxDirectiveName; import net.ishchenko.idea.nginx.psi.NginxInnerVariable; import org.jetbrains.annotations.Nullable; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.List; /** * Created by IntelliJ IDEA. * User: Max * Date: 19.08.2009 * Time: 0:49:41 */ public class NginxDocumentationProvider implements DocumentationProvider { public static final Logger LOG = Logger.getInstance("#com.intellij.lang.documentation.QuickDocumentationProvider"); @Nullable @Override public List<String> getUrlFor(PsiElement element, PsiElement originalElement) { return null; } @Nullable @Override public PsiElement getDocumentationElementForLookupItem(PsiManager psiManager, Object object, PsiElement element) { return null; } @Nullable @Override public PsiElement getDocumentationElementForLink(PsiManager psiManager, String link, PsiElement context) { return null; } @Override public String generateDoc(PsiElement element, PsiElement originalElement) { if (element instanceof NginxDirectiveName) { return generateDocForDirectiveName((NginxDirectiveName) element); } else if (element instanceof NginxInnerVariable) { return generateDocForInnerVariable((NginxInnerVariable) element); } return null; } private String generateDocForDirectiveName(NginxDirectiveName element) { StringBuilder result = new StringBuilder(); InputStream docStream = getClass().getResourceAsStream("/docs/directives/" + element.getText() + ".html"); if (docStream == null) { result.append(NginxBundle.message("docs.directive.notfound", element.getText())); } else { BufferedReader keywordsReader = new BufferedReader(new InputStreamReader(docStream)); try { String line; while ((line = keywordsReader.readLine()) != null) { result.append(line).append("\n"); } } catch (IOException e) { LOG.error(e); return null; } finally { try { keywordsReader.close(); } catch (IOException e) { LOG.error(e); } } } return result.toString(); } private String generateDocForInnerVariable(NginxInnerVariable element) { StringBuilder result = new StringBuilder(); InputStream docStream = getClass().getResourceAsStream("/docs/variables/" + element.getName() + ".html"); if (docStream == null) { result.append(NginxBundle.message("docs.variable.notfound", element.getName())); } else { result.append("<b>").append(element.getText()).append("</b><br>"); BufferedReader keywordsReader = new BufferedReader(new InputStreamReader(docStream)); try { String line; while ((line = keywordsReader.readLine()) != null) { result.append(line).append("\n"); } } catch (IOException e) { LOG.error(e); return null; } finally { try { keywordsReader.close(); } catch (IOException e) { LOG.error(e); } } } return result.toString(); } @Override public String getQuickNavigateInfo(PsiElement element, PsiElement originalElement) { return null; } } <|start_filename|>resources/docs/directives/perl_set.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpPerlModule&amp;action=edit&amp;section=8" title="Edit section: perl set">edit</a>]</span> <span class="mw-headline" id="perl_set"> perl_set </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>perl_set</b> <i>$variable</i> <i>module</i>&nbsp;:: <i>function</i> |'sub { ... }'</td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> http</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_perl_module.html#perl_set">perl_set</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 39/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Directive establishes the function of variable&nbsp;??? </p><h1><span class="editsection">[<a href="/index.php?title=HttpPerlModule&amp;action=edit&amp;section=9" title="Edit section: Calling Perl from SSI">edit</a>]</span> <span class="mw-headline" id="Calling_Perl_from_SSI"> Calling Perl from SSI </span></h1><p>Instruction format is as follows: </p><pre> &lt;!--# perl sub=&quot;module::function&quot; arg=&quot;parameter1&quot; arg=&quot;parameter2&quot;... --&gt; </pre><h1><span class="editsection">[<a href="/index.php?title=HttpPerlModule&amp;action=edit&amp;section=10" title="Edit section: Methods of request object $r">edit</a>]</span> <span class="mw-headline" id="Methods_of_request_object_.24r"> Methods of request object $r </span></h1><ul> <li> $r-&gt;args - method returns the arguments of request. </li> <li> $r-&gt;discard_request_body - method tells nginx to discard the request body. </li> <li> $r-&gt;filename - method returns the name of file, which corresponds to URI request. </li> <li> $r-&gt;has_request_body(function) - method returns 0, if there is no request body. But if the request body exists, then the passed function is established and 1 returned. At the end of the body processing, nginx will call the established processor. Example usage: </li> </ul><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="perl source-perl"> <pre class="de1"><a href="http://perldoc.perl.org/functions/package.html"><span class="kw3">package</span></a> hello<span class="sy0">;</span> &nbsp; <span class="kw2">use</span> nginx<span class="sy0">;</span> &nbsp; <span class="kw2">sub</span> handler <span class="br0">{</span> <span class="kw1">my</span> <span class="re0">$r</span> <span class="sy0">=</span> <a href="http://perldoc.perl.org/functions/shift.html"><span class="kw3">shift</span></a><span class="sy0">;</span> &nbsp; <span class="kw1">if</span> <span class="br0">(</span><span class="re0">$r</span><span class="sy0">-&gt;</span><span class="me1">request_method</span> <span class="kw1">ne</span> <span class="st0">&quot;POST&quot;</span><span class="br0">)</span> <span class="br0">{</span> <a href="http://perldoc.perl.org/functions/return.html"><span class="kw3">return</span></a> DECLINED<span class="sy0">;</span> <span class="br0">}</span> &nbsp; <span class="kw1">if</span> <span class="br0">(</span><span class="re0">$r</span><span class="sy0">-&gt;</span><span class="me1">has_request_body</span><span class="br0">(</span><span class="re0">\&amp;post</span><span class="br0">)</span><span class="br0">)</span> <span class="br0">{</span> <a href="http://perldoc.perl.org/functions/return.html"><span class="kw3">return</span></a> OK<span class="sy0">;</span> <span class="br0">}</span> &nbsp; <a href="http://perldoc.perl.org/functions/return.html"><span class="kw3">return</span></a> <span class="nu0">400</span><span class="sy0">;</span> <span class="br0">}</span> &nbsp; <span class="kw2">sub</span> post <span class="br0">{</span> <span class="kw1">my</span> <span class="re0">$r</span> <span class="sy0">=</span> <a href="http://perldoc.perl.org/functions/shift.html"><span class="kw3">shift</span></a><span class="sy0">;</span> <span class="re0">$r</span><span class="sy0">-&gt;</span><span class="me1">send_http_header</span><span class="sy0">;</span> <span class="re0">$r</span><span class="sy0">-&gt;</span><span class="me1">print</span><span class="br0">(</span><span class="st0">&quot;request_body: <span class="es0">\&quot;</span>&quot;</span><span class="sy0">,</span> <span class="re0">$r</span><span class="sy0">-&gt;</span><span class="me1">request_body</span><span class="sy0">,</span> <span class="st0">&quot;<span class="es0">\&quot;</span>&lt;br/&gt;&quot;</span><span class="br0">)</span><span class="sy0">;</span> <span class="re0">$r</span><span class="sy0">-&gt;</span><span class="me1">print</span><span class="br0">(</span><span class="st0">&quot;request_body_file: <span class="es0">\&quot;</span>&quot;</span><span class="sy0">,</span> <span class="re0">$r</span><span class="sy0">-&gt;</span><span class="me1">request_body_file</span><span class="sy0">,</span> <span class="st0">&quot;<span class="es0">\&quot;</span>&lt;br/&gt;<span class="es0">\n</span>&quot;</span><span class="br0">)</span><span class="sy0">;</span> <a href="http://perldoc.perl.org/functions/return.html"><span class="kw3">return</span></a> OK<span class="sy0">;</span> <span class="br0">}</span> &nbsp; <span class="nu0">1</span><span class="sy0">;</span> &nbsp; <span class="kw2">__END__</span></pre> </div> </div><ul> <li> $r-&gt;header_in(header) - retrieve an HTTP request header. </li> <li> $r-&gt;header_only - true if we only need to return a response header. </li> <li> $r-&gt;header_out(header, value) - set a response header. </li> <li> $r-&gt;internal_redirect(uri) - method makes internal redirect to the indicated uri. Redirect occurs only after the completion of Perl script. </li> <li> $r-&gt;print(args, ...) - sends data to client. </li> <li> $r-&gt;request_body - method returns the request body of client when the body is not recorded into the temporary file. </li> </ul><dl> <dd> So that the body of the demand of client is guaranteed to remain in memory, it is necessary to limit its size with the aid </dd> <dd> of client_max_body_size and to assign sufficient size for the buffer using client_body_buffer_size. </dd> </dl><ul> <li> $r-&gt;request_body_file — method returns the name of the file, in which is stored the body of the demand of client. The file must be removed on the completion of work. So that the body of the request would always be written to the file, it is necessary to indicate client_body_in_file_only on. </li> <li> $r-&gt;request_method — method returns the HTTP method of the request. </li> <li> $r-&gt;remote_addr - method returns IP address of client. </li> <li> $r-&gt;rflush - method immediately transmits data to client. </li> <li> $r-&gt;sendfile(file [, displacement [, length ] ) - transfers to client contents of the file indicated. The optional parameters indicate initial offset and length of transmitted data. Strictly the transmission of data occurs only after the completion of the perl script. </li> <li> $r-&gt;send_http_header(type) - adds header to response. The optional parameter &quot;type&quot; establishes the value of line &quot;Content-Type&quot; in the title of answer. </li> <li> $r-&gt;sleep(milliseconds, handler) - method sets the specified handler and stops processing the request at a given time. nginx will continue to process other requests in the meantime. After the specified timeout has expired, nginx will run the installed handler. Please note that you need to pass a reference to the function handler. To transfer data between processors you should use $r-&gt;variable(). Example of usage: </li> </ul><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="perl source-perl"> <pre class="de1"><a href="http://perldoc.perl.org/functions/package.html"><span class="kw3">package</span></a> hello<span class="sy0">;</span> &nbsp; <span class="kw2">use</span> nginx<span class="sy0">;</span> &nbsp; <span class="kw2">sub</span> handler <span class="br0">{</span> <span class="kw1">my</span> <span class="re0">$r</span> <span class="sy0">=</span> <a href="http://perldoc.perl.org/functions/shift.html"><span class="kw3">shift</span></a><span class="sy0">;</span> &nbsp; <span class="re0">$r</span><span class="sy0">-&gt;</span><span class="me1">discard_request_body</span><span class="sy0">;</span> <span class="re0">$r</span><span class="sy0">-&gt;</span><span class="me1">variable</span><span class="br0">(</span><span class="st0">&quot;var&quot;</span><span class="sy0">,</span> <span class="st0">&quot;OK&quot;</span><span class="br0">)</span><span class="sy0">;</span> <span class="re0">$r</span><span class="sy0">-&gt;</span><span class="me1">sleep</span><span class="br0">(</span><span class="nu0">1000</span><span class="sy0">,</span> <span class="re0">\&amp;next</span><span class="br0">)</span><span class="sy0">;</span> &nbsp; <a href="http://perldoc.perl.org/functions/return.html"><span class="kw3">return</span></a> OK<span class="sy0">;</span> <span class="br0">}</span> &nbsp; <span class="kw2">sub</span> <span class="kw1">next</span> <span class="br0">{</span> <span class="kw1">my</span> <span class="re0">$r</span> <span class="sy0">=</span> <a href="http://perldoc.perl.org/functions/shift.html"><span class="kw3">shift</span></a><span class="sy0">;</span> &nbsp; <span class="re0">$r</span><span class="sy0">-&gt;</span><span class="me1">send_http_header</span><span class="sy0">;</span> <span class="re0">$r</span><span class="sy0">-&gt;</span><span class="me1">print</span><span class="br0">(</span><span class="re0">$r</span><span class="sy0">-&gt;</span><span class="me1">variable</span><span class="br0">(</span><span class="st0">&quot;var&quot;</span><span class="br0">)</span><span class="br0">)</span><span class="sy0">;</span> &nbsp; <a href="http://perldoc.perl.org/functions/return.html"><span class="kw3">return</span></a> OK<span class="sy0">;</span> <span class="br0">}</span> &nbsp; <span class="nu0">1</span><span class="sy0">;</span> <span class="kw2">__END__</span></pre> </div> </div><ul> <li> $r-&gt;status(code) - sets the HTTP response code </li> <li> $r-&gt;unescape(text) - decodes the text, assigned in the form&nbsp;%XX. </li> <li> $r-&gt;uri - returns request URI. </li> <li> $r-&gt;variable(name[, value]) - the method returns or sets the value of the specified variable. Variables are local to each query. </li> </ul><h1><span class="editsection">[<a href="/index.php?title=HttpPerlModule&amp;action=edit&amp;section=11" title="Edit section: References">edit</a>]</span> <span class="mw-headline" id="References"> References </span></h1><p><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_perl_module.html">Original Documentation</a> </p><br><i>Module: HttpPerlModule</i> <|start_filename|>resources/docs/directives/geoip_city.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpGeoipModule&amp;action=edit&amp;section=4" title="Edit section: geoip city">edit</a>]</span> <span class="mw-headline" id="geoip_city"> geoip_city </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>geoip_city</b> <i>file</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> http</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_geoip_module.html#geoip_city">geoip_city</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 44/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> This directive specifies the full path to the Geo IP database .dat file that associates IP addresses with country, city and region geolocation information. This allows you to get that information corresponding to the given IP. It can be used to determine the visitor's geolocation from the IP address of the client. When set the following variables are available: </p><ul> <li> <b>$geoip_city_country_code</b> — two-letter country code, for example, &quot;RU&quot;, &quot;US&quot;. </li> <li> <b>$geoip_city_country_code3</b> — three-letter country code, for example, &quot;RUS&quot;, &quot;USA&quot;. </li> <li> <b>$geoip_city_country_name</b> — the name of the country, for example, &quot;Russian Federation&quot;, &quot;United States&quot; — if available. </li> <li> <b>$geoip_region</b> — the name of region (province, region, state, province, federal land, and the like), for example, &quot;Moscow City&quot;, &quot;DC&quot; — if available. </li> <li> <b>$geoip_city</b> — the name of the city, for example, &quot;Moscow&quot;, &quot;Washington&quot;, &quot;Lisbon&quot;, &amp;c — if available. </li> <li> <b>$geoip_postal_code</b> — zip code or postal code — if available. </li> <li> <b>$geoip_city_continent_code</b> — if available. </li> <li> <b>$geoip_latitude</b> — latitude — if available. </li> <li> <b>$geoip_longitude</b> — longitude — if available. </li> <li> <b>$geoip_dma_code</b> — DMA Code — if available. </li> <li> <b>$geoip_area_code</b> — Area Code — if available. </li> </ul><br><i>Module: HttpGeoipModule</i> <|start_filename|>resources/docs/directives/internal.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpCoreModule&amp;action=edit&amp;section=22" title="Edit section: internal">edit</a>]</span> <span class="mw-headline" id="internal"> internal </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>internal</b> </td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_core_module.html#internal">internal</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 179/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> <b>internal</b> indicates that the matching location can be used only for so called &quot;internal&quot; requests. </p><p>For external requests it will return the error &quot;Not found&quot; (404). </p><p>Internal requests are the following: </p><ul> <li> requests redirected by the instruction <b>error_page</b> </li> <li> subrequests created by the command <b>include virtual</b> of the &quot;ngx_http_ssi_module&quot; module </li> <li> requests changed by the instruction <b>rewrite</b> of the &quot;ngx_http_rewrite_module&quot; module </li> </ul><p>An example to prevent clients fetching error pages directly: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#error_page"><span class="kw3">error_page</span></a> <span class="nu0">404</span> /<span class="nu0">404</span>.html<span class="sy0">;</span> <a href="/NginxHttpCoreModule#location"><span class="kw3">location</span></a> /<span class="nu0">404</span>.html <span class="br0">{</span> <a href="/NginxHttpCoreModule#internal"><span class="kw3">internal</span></a><span class="sy0">;</span> <span class="br0">}</span></pre> </div> </div><br><i>Module: HttpCoreModule</i> <|start_filename|>resources/docs/directives/proxy_cache_key.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpProxyModule&amp;action=edit&amp;section=10" title="Edit section: proxy cache key">edit</a>]</span> <span class="mw-headline" id="proxy_cache_key"> proxy_cache_key </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>proxy_cache_key</b> <i>string</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>$scheme$proxy_host$request_uri</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_cache_key">proxy_cache_key</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 65/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> The directive specifies what information is included in the key for caching, for example </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1">proxy_cache_key <span class="st0">&quot;$host$request_uri$cookie_user&quot;</span><span class="sy0">;</span></pre> </div> </div><p>Note that by default, the hostname of the server is not included in the cache key. If you are using subdomains for different locations on your website, you need to include it, e.g. by changing the cache key to something like </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1">proxy_cache_key <span class="st0">&quot;$scheme$host$request_uri&quot;</span><span class="sy0">;</span></pre> </div> </div><br><i>Module: HttpProxyModule</i> <|start_filename|>resources/docs/directives/fastcgi_read_timeout.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpFastcgiModule&amp;action=edit&amp;section=32" title="Edit section: fastcgi read timeout">edit</a>]</span> <span class="mw-headline" id="fastcgi_read_timeout"> fastcgi_read_timeout </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>fastcgi_read_timeout</b> <i>time</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>60s</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_read_timeout">fastcgi_read_timeout</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 308/1000000 Post-expand include size: 401/2097152 bytes Template argument size: 178/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Directive sets the amount of time for upstream to wait for a fastcgi process to send data. Change this directive if you have long running fastcgi processes that do not produce output until they have finished processing. If you are seeing an upstream timed out error in the error log, then increase this parameter to something more appropriate. </p><br><i>Module: HttpFastcgiModule</i> <|start_filename|>src/net/ishchenko/idea/nginx/injection/LuaInjector.java<|end_filename|> package net.ishchenko.idea.nginx.injection; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.fileTypes.LanguageFileType; import com.intellij.openapi.util.TextRange; import com.intellij.psi.InjectedLanguagePlaces; import com.intellij.psi.LanguageInjector; import com.intellij.psi.PsiLanguageInjectionHost; import net.ishchenko.idea.nginx.psi.NginxLuaContext; import org.jetbrains.annotations.NotNull; public class LuaInjector implements LanguageInjector { @Override public void getLanguagesToInject(@NotNull PsiLanguageInjectionHost host, @NotNull InjectedLanguagePlaces injectionPlacesRegistrar) { if (host instanceof NginxLuaContext) { LanguageFileType maybeLuaType = (LanguageFileType)FileTypeManager.getInstance().getStdFileType("Lua"); if (maybeLuaType.getLanguage().getID().compareToIgnoreCase("Lua") == 0) { int start = host.getText().indexOf("{") + 1; injectionPlacesRegistrar.addPlace(maybeLuaType.getLanguage(), new TextRange(start, host.getTextLength()), null, null); } } } } <|start_filename|>resources/docs/directives/limit_conn_log_level.html<|end_filename|> <h3>Directive can have multiple meanings. Each variant is separated with horizontal line</h3><hr><h2><span class="editsection">[<a href="/index.php?title=HttpLimitConnModule&amp;action=edit&amp;section=5" title="Edit section: limit conn log level">edit</a>]</span> <span class="mw-headline" id="limit_conn_log_level"> limit_conn_log_level </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>limit_conn_log_level</b> <code>info</code> | <code>notice</code> | <code>warn</code> | <code>error</code> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>error</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Appeared in:</b></td> <td> 0.8.18</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_limit_conn_module.html#limit_conn_log_level">limit_conn_log_level</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 30/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Sets the error log level used when a connection limit is reached. </p><h1><span class="editsection">[<a href="/index.php?title=HttpLimitConnModule&amp;action=edit&amp;section=6" title="Edit section: References">edit</a>]</span> <span class="mw-headline" id="References"> References </span></h1><p><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_limit_conn_module.html">Original Documentation</a> </p><br><i>Module: HttpLimitConnModule</i><hr><h2><span class="editsection">[<a href="/index.php?title=HttpLimitZoneModule&amp;action=edit&amp;section=5" title="Edit section: limit conn log level">edit</a>]</span> <span class="mw-headline" id="limit_conn_log_level"> limit_conn_log_level </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>limit_conn_log_level</b> <code>info</code> | <code>notice</code> | <code>warn</code> | <code>error</code> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>error</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Appeared in:</b></td> <td> 0.8.18</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_limit_conn_module.html#limit_conn_log_level">limit_conn_log_level</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 36/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Sets the error log level used when a connection limit is reached </p><h1><span class="editsection">[<a href="/index.php?title=HttpLimitZoneModule&amp;action=edit&amp;section=6" title="Edit section: References">edit</a>]</span> <span class="mw-headline" id="References"> References </span></h1><p><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_limit_conn_module.html">Original Documentation</a> </p><br><i>Module: HttpLimitZoneModule</i> <|start_filename|>src/net/ishchenko/idea/nginx/run/NginxExecutionResult.java<|end_filename|> /* * Copyright 2009 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.ishchenko.idea.nginx.run; import com.intellij.execution.ExecutionResult; import com.intellij.execution.process.ProcessHandler; import com.intellij.execution.ui.ExecutionConsole; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.AnAction; /** * Created by IntelliJ IDEA. * User: Max * Date: 21.07.2009 * Time: 0:11:08 */ public class NginxExecutionResult implements ExecutionResult { public static final String RELOAD_ACTION_ID = "nginx.reload"; private final ExecutionConsole console; private final ProcessHandler handler; private AnAction[] actions; public NginxExecutionResult(final ExecutionConsole console, ProcessHandler processHandler) { this.console = console; handler = processHandler; ActionManager actionManager = ActionManager.getInstance(); AnAction reloadAction = actionManager.getAction(RELOAD_ACTION_ID); actions = new AnAction[]{reloadAction}; } public ExecutionConsole getExecutionConsole() { return console; } public AnAction[] getActions() { return actions; } public ProcessHandler getProcessHandler() { return handler; } } <|start_filename|>resources/docs/directives/log_format.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpLogModule&amp;action=edit&amp;section=4" title="Edit section: log format">edit</a>]</span> <span class="mw-headline" id="log_format"> log_format </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>log_format</b> <i>name</i> <i>string</i> ...</td> </tr> <tr> <td><b>Default:</b></td> <td> <i>combined &quot;...&quot;</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_log_module.html#log_format">log_format</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 20/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> The <b>log_format</b> directive describes the format of a log entry. You can use general variables in the format, as well as variables which exist only at the moment of writing into the log: </p><ul> <li> $body_bytes_sent, the number of bytes, transmitted to client minus the response headers. This variable is compatible with the&nbsp;%B parameter of Apache's mod_log_config (this was called $apache_bytes_sent, before version 0.3.10) </li> <li> $bytes_sent, the number of bytes transmitted to client </li> <li> $connection, the number of connection </li> <li> $msec, the current time at the moment of writing the log entry (microsecond accuracy) </li> <li> $pipe, &quot;p&quot; if request was <a rel="nofollow" class="external text" href="http://en.wikipedia.org/wiki/HTTP_pipelining">pipelined</a> </li> <li> $request_length, the length of the body of the request </li> <li> $request_time, the time it took nginx to work on the request, in seconds with millisecond precision (just seconds for versions older than 0.5.19) </li> <li> $status, status of answer </li> <li> $time_iso8601, time in <a rel="nofollow" class="external text" href="http://en.wikipedia.org/wiki/ISO_8601">ISO 8601</a> format, e. g. 2011-03-21T18:52:25+03:00 (added in 0.9.6) </li> <li> $time_local, local time into common log format. </li> </ul><p>The headers, transmitted to client, begin from the prefix &quot;sent_http_&quot;, for example, $sent_http_content_range. </p><p>Note that variables produced by other modules can also be logged. For example you can log upstream response headers with the prefix &quot;upstream_http_&quot;, see <a href="/NginxHttpUpstreamModule" title="NginxHttpUpstreamModule" class="mw-redirect"> upstream</a> . </p><p>There is a predefined log format called &quot;combined&quot;: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpLogModule#log_format"><span class="kw18">log_format</span></a> combined <span class="st0">'$remote_addr - $remote_user [$time_local] '</span> <span class="st0">'&quot;$request&quot; $status $body_bytes_sent '</span> <span class="st0">'&quot;$http_referer&quot; &quot;$http_user_agent&quot;'</span><span class="sy0">;</span></pre> </div> </div><br><i>Module: HttpLogModule</i> <|start_filename|>resources/docs/directives/modern_browser.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpBrowserModule&amp;action=edit&amp;section=5" title="Edit section: modern browser">edit</a>]</span> <span class="mw-headline" id="modern_browser"> modern_browser </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>modern_browser</b> <i>browser</i> <i>version</i> <br /><b>modern_browser</b> <code>unlisted</code> </td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_browser_module.html#modern_browser">modern_browser</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 30/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Directive assigns which version of the browser is to be considered as <b>modern</b>.<br /> As browser you can assign the values msie, gecko (Mozilla-based browsers) opera, safari, konqueror. </p><p>Of versions it is possible to assign in size X, X.X, X.X.X, or X.X.X.X. maximum values for each of their sizes respectively - 4000, 4000.99, 4000.99.99, and 4000.99.99.99. </p><p>Special value &quot;unlisted&quot; indicates to consider modern browser, not described by the modern_browser and ancient_browser directives. <br /> If the headers do not contain &quot;User-agent&quot;, the browser is considered ancient (unless &quot;modern_browser unlisted&quot; is specified). </p><br><i>Module: HttpBrowserModule</i> <|start_filename|>resources/docs/directives/index.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpIndexModule&amp;action=edit&amp;section=3" title="Edit section: index">edit</a>]</span> <span class="mw-headline" id="index"> index </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>index</b> <i>file</i> ...</td> </tr> <tr> <td><b>Default:</b></td> <td> <i>index.html</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_index_module.html#index">index</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 10/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Sets the default file to serve if a directory is requested by the client. Multiple files can be specified. If the first file isn't found, the second will be used and so on. If the last entry begins with a /, and none of the earlier files are found, nginx will perform an internal redirect to this uri. </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"> <a href="/NginxHttpCoreModule#index"><span class="kw3">index</span></a> <a href="/NginxHttpCoreModule#index"><span class="kw3">index</span></a>.html <a href="/NginxHttpCoreModule#index"><span class="kw3">index</span></a>.php /<a href="/NginxHttpCoreModule#index"><span class="kw3">index</span></a>.php<span class="sy0">;</span></pre> </div> </div><h1><span class="editsection">[<a href="/index.php?title=HttpIndexModule&amp;action=edit&amp;section=4" title="Edit section: References">edit</a>]</span> <span class="mw-headline" id="References"> References </span></h1><p><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_index_module.html">Original Documentation</a> </p><br><i>Module: HttpIndexModule</i> <|start_filename|>resources/docs/directives/echo.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpSsiModule&amp;action=edit&amp;section=10" title="Edit section: echo">edit</a>]</span> <span class="mw-headline" id="echo"> echo </span></h2><p>Print a variable. </p><ul> <li> <code>var</code> — the name of the variable </li> <li> <code>encoding</code> — the escape of the variable, there are <code>none</code>, <code>url</code>, <code>entity</code>. Defaults to <code>entity</code> </li> <li> <code>default</code> - if the variable is empty, display this string. Defaults to &quot;none&quot;. Example: </li> </ul><pre> &lt;!--# echo var=&quot;name&quot; default=&quot;no&quot; --&gt; </pre><p>is the same as </p><pre> &lt;!--# if expr=&quot;$name&quot; --&gt;&lt;!--# echo var=&quot;name&quot; --&gt;&lt;!--# else --&gt;no&lt;!--# endif --&gt; </pre><br><i>Module: HttpSsiModule</i> <|start_filename|>resources/docs/directives/charset_map.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpCharsetModule&amp;action=edit&amp;section=4" title="Edit section: charset map">edit</a>]</span> <span class="mw-headline" id="charset_map"> charset_map </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>charset_map</b> <i>charset1</i> <i>charset2</i> { ... }</td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> http</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_charset_module.html#charset_map">charset_map</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 20/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> The directive charset_map describes the table of reencoding from one encoding into another. A table for the inverse reencoding is created using the same data. The codes of symbols are assigned in hexadecimal form. If no recorded symbols are in the range 80-FF they will be substituted with '?'. </p><p>Example usage: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCharsetModule#charset_map"><span class="kw9">charset_map</span></a> koi8-r windows-<span class="nu0">1251</span> <span class="br0">{</span> C0 FE <span class="sy0">;</span> <span class="co1"># small yu</span> C1 E0 <span class="sy0">;</span> <span class="co1"># small a</span> C2 E1 <span class="sy0">;</span> <span class="co1"># small b</span> C3 F6 <span class="sy0">;</span> <span class="co1"># small ts</span> <span class="co1"># ...</span> <span class="br0">}</span></pre> </div> </div><p>The complete table of conversion from koi8-r into Windows-1251 is distributed with nginx and is located in file conf/koi-win. </p><br><i>Module: HttpCharsetModule</i> <|start_filename|>resources/docs/directives/gzip_disable.html<|end_filename|> <h3>Directive can have multiple meanings. Each variant is separated with horizontal line</h3><hr><h2><span class="editsection">[<a href="/index.php?title=HttpGzipModule&amp;action=edit&amp;section=6" title="Edit section: gzip disable">edit</a>]</span> <span class="mw-headline" id="gzip_disable"> gzip_disable </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>gzip_disable</b> <i>regex</i> ...</td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Appeared in:</b></td> <td> 0.6.23</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_gzip_module.html#gzip_disable">gzip_disable</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 34/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Disable gzip compression for User-Agents matching the given regular expression. Requires PCRE library. Introduced in Nginx 0.6.23. </p><p>You can use &quot;msie6&quot; to disable gzip for Internet Explorer 5.5 and Internet Explorer 6. &quot;SV1&quot; (Service Pack 2) will be ignored since Nginx 0.7.63. </p><p>Example </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"> <a href="/NginxHttpGzipModule#gzip_disable"><span class="kw13">gzip_disable</span></a> <span class="st0">&quot;msie6&quot;</span><span class="sy0">;</span></pre> </div> </div><p>or </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"> <a href="/NginxHttpGzipModule#gzip_disable"><span class="kw13">gzip_disable</span></a> <span class="st0">&quot;MSIE [1-6]<span class="es0">\.</span>(?!.*SV1)&quot;</span><span class="sy0">;</span></pre> </div> </div><br><i>Module: HttpGzipModule</i><hr><h2><span class="editsection">[<a href="/index.php?title=HttpGzipStaticModule&amp;action=edit&amp;section=6" title="Edit section: gzip disable">edit</a>]</span> <span class="mw-headline" id="gzip_disable"> gzip_disable </span></h2><p>See <a href="/NginxHttpGzipModule#gzip_disable" title="NginxHttpGzipModule" class="mw-redirect"> NginxHttpGzipModule</a> </p><br><i>Module: HttpGzipStaticModule</i> <|start_filename|>resources/docs/directives/proxy_connect_timeout.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpProxyModule&amp;action=edit&amp;section=18" title="Edit section: proxy connect timeout">edit</a>]</span> <span class="mw-headline" id="proxy_connect_timeout"> proxy_connect_timeout </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>proxy_connect_timeout</b> <i>time</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>60s</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_connect_timeout">proxy_connect_timeout</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 145/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> This directive assigns a timeout for the connection to the upstream server. It is necessary to keep in mind that this time out cannot be more than 75 seconds. </p><p>This is not the time until the server returns the pages, that is the <a href="#proxy_read_timeout"> proxy_read_timeout</a> statement. If your upstream server is up, but hanging (e.g. it does not have enough threads to process your request so it puts you in the pool of connections to deal with later), then this statement will not help as the connection to the server has been made. </p><br><i>Module: HttpProxyModule</i> <|start_filename|>resources/docs/directives/client_body_timeout.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpCoreModule&amp;action=edit&amp;section=10" title="Edit section: client body timeout">edit</a>]</span> <span class="mw-headline" id="client_body_timeout"> client_body_timeout </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>client_body_timeout</b> <i>time</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>60s</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_core_module.html#client_body_timeout">client_body_timeout</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 80/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Directive sets the read timeout for the request body from client. </p><p>The timeout is set only if a body is not get in one readstep. If after this time the client send nothing, nginx returns error &quot;Request time out&quot; (408). </p><br><i>Module: HttpCoreModule</i> <|start_filename|>resources/docs/directives/working_directory.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=CoreModule&amp;action=edit&amp;section=21" title="Edit section: working directory">edit</a>]</span> <span class="mw-headline" id="working_directory"> working_directory </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>working_directory</b> <i>directory</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> main</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/ngx_core_module.html#working_directory">working_directory</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 166/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> This is the working directory for the workers. It's used for core files only and <a href="/Debugging" title="Debugging">Debugging</a> Nginx. nginx uses absolute paths only, all relative paths in configuration files are relative to <code>--prefix==PATH</code>. </p><h1><span class="editsection">[<a href="/index.php?title=CoreModule&amp;action=edit&amp;section=22" title="Edit section: Variables">edit</a>]</span> <span class="mw-headline" id="Variables"> Variables </span></h1><br><i>Module: CoreModule</i> <|start_filename|>resources/docs/directives/satisfy.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpCoreModule&amp;action=edit&amp;section=56" title="Edit section: satisfy">edit</a>]</span> <span class="mw-headline" id="satisfy"> satisfy </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>satisfy</b> <code>all</code> | <code>any</code> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>all</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_core_module.html#satisfy">satisfy</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 465/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> This determines the adopted access policy when directives from multiple access phase handlers, such as the <a href="/HttpAccessModule" title="HttpAccessModule">Access</a> and <a href="/HttpAuthBasicModule" title="HttpAuthBasicModule">Auth Basic</a> modules, are defined in a context: </p><ul> <li> all - All access phase handlers must grant access to the context </li> <li> any - Any access phase handler may grant access to the context </li> </ul><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#location"><span class="kw3">location</span></a> / <span class="br0">{</span> satisfy any<span class="sy0">;</span> <a href="/NginxHttpAccessModule#allow"><span class="kw5">allow</span></a> 192.168.1.0/<span class="nu0">32</span><span class="sy0">;</span> <a href="/NginxHttpAccessModule#deny"><span class="kw5">deny</span></a> all<span class="sy0">;</span> <a href="/NginxHttpAuthBasicModule#auth_basic"><span class="kw6">auth_basic</span></a> <span class="st0">&quot;closed site&quot;</span><span class="sy0">;</span> <a href="/NginxHttpAuthBasicModule#auth_basic_user_file"><span class="kw6">auth_basic_user_file</span></a> conf/htpasswd<span class="sy0">;</span> <span class="br0">}</span></pre> </div> </div><br><i>Module: HttpCoreModule</i> <|start_filename|>resources/docs/directives/proxy_cache_use_stale.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpProxyModule&amp;action=edit&amp;section=16" title="Edit section: proxy cache use stale">edit</a>]</span> <span class="mw-headline" id="proxy_cache_use_stale"> proxy_cache_use_stale </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>proxy_cache_use_stale</b> <code>error</code> | <code>timeout</code> | <code>invalid_header</code> | <code>updating</code> | <code>http_500</code> | <code>http_502</code> | <code>http_503</code> | <code>http_504</code> | <code>http_404</code> | <code>off</code> ...</td> </tr> <tr> <td><b>Default:</b></td> <td> <i>off</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_cache_use_stale">proxy_cache_use_stale</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 119/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> This directive tells Nginx when to serve a stale item from the proxy cache. The parameters for this directive are similar to <a href="#proxy_next_upstream">proxy_next_upstream</a> with the addition of 'updating'. </p><p>To prevent cache stampedes (when multiple threads stampede in to try to update the cache simultaneously) you can specify the 'updating' parameter. This will cause one thread to update the cache and while the update is in progress all other threads will serve the stale version of what is in the cache. </p><br><i>Module: HttpProxyModule</i> <|start_filename|>resources/docs/directives/limit_req.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpLimitReqModule&amp;action=edit&amp;section=4" title="Edit section: limit req">edit</a>]</span> <span class="mw-headline" id="limit_req"> limit_req </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>limit_req</b> <code>zone</code> = <i>name</i> [ <code>burst</code> = <i>number</i> ] [ <code>nodelay</code> ]</td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_limit_req_module.html#limit_req">limit_req</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 14/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> The directive specifies the zone (<b>zone</b>) and the maximum possible bursts of requests (burst). If the rate exceeds the demands outlined in the zone, the request is delayed, so that queries are processed at a given speed. Excess requests are delayed while their number does not exceed a specified number of bursts. If the number of waiting requests exceed burst, the request is completed with the code 503 &quot;Service Temporarily Unavailable&quot;. By default, the burst is zero. </p><p>For example, the directive </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1">limit_req_zone <span class="re0">$binary_remote_addr</span> zone<span class="sy0">=</span>one:10m rate<span class="sy0">=</span>1r/s<span class="sy0">;</span> &nbsp; <a href="/NginxHttpCoreModule#server"><span class="kw3">server</span></a> <span class="br0">{</span> <a href="/NginxHttpCoreModule#location"><span class="kw3">location</span></a> /search/ <span class="br0">{</span> limit_req zone<span class="sy0">=</span>one burst<span class="sy0">=</span><span class="nu0">5</span><span class="sy0">;</span> <span class="br0">}</span></pre> </div> </div><p>allows a user no more than 1 request per second on average, with bursts of no more than 5 requests. </p><p>If delaying excess requests within a burst is not necessary, you should use the option <b>nodelay</b>: </p><pre> limit_req zone=one burst=5 nodelay; </pre><br><i>Module: HttpLimitReqModule</i> <|start_filename|>resources/docs/directives/gzip_types.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpGzipModule&amp;action=edit&amp;section=10" title="Edit section: gzip types">edit</a>]</span> <span class="mw-headline" id="gzip_types"> gzip_types </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>gzip_types</b> <i>mime-type</i> ...</td> </tr> <tr> <td><b>Default:</b></td> <td> <i>text/html</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_gzip_module.html#gzip_types">gzip_types</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 68/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Enables compression for additional MIME-types besides &quot;text/html&quot;. &quot;text/html&quot; is always compressed. </p><br><i>Module: HttpGzipModule</i> <|start_filename|>resources/docs/directives/limit_conn.html<|end_filename|> <h3>Directive can have multiple meanings. Each variant is separated with horizontal line</h3><hr><h2><span class="editsection">[<a href="/index.php?title=HttpLimitConnModule&amp;action=edit&amp;section=3" title="Edit section: limit conn">edit</a>]</span> <span class="mw-headline" id="limit_conn"> limit_conn </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>limit_conn</b> <i>zone</i> <i>number</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_limit_conn_module.html#limit_conn">limit_conn</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 13/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Sets the maximum allowed number of connections for a given zone. When this limit is exceeded, the server will return a status error 503 (Service Temporarily Unavailable) in reply to the request. </p><p>Multiple limit directives for different zones can be used in the same context and each will apply. </p><p>Standard nginx inheritance applies. Lower contexts will inherit from higher context so long as there are no similar directives in the current context. </p><br><i>Module: HttpLimitConnModule</i><hr><h2><span class="editsection">[<a href="/index.php?title=HttpLimitZoneModule&amp;action=edit&amp;section=4" title="Edit section: limit conn">edit</a>]</span> <span class="mw-headline" id="limit_conn"> limit_conn </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>limit_conn</b> <i>zone</i> <i>number</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_limit_conn_module.html#limit_conn">limit_conn</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 26/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Directive assigns the maximum number of simultaneous connections for one session. With exceeding of this number the request completes by the code &quot;Service unavailable&quot; (503). </p><p>For example, the directive: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpLimitZoneModule#limit_zone"><span class="kw17">limit_zone</span></a> one <span class="re0">$binary_remote_addr</span> 10m<span class="sy0">;</span> &nbsp; <a href="/NginxHttpCoreModule#server"><span class="kw3">server</span></a> <span class="br0">{</span> <a href="/NginxHttpCoreModule#location"><span class="kw3">location</span></a> /download/ <span class="br0">{</span> <a href="/NginxHttpLimitZoneModule#limit_conn"><span class="kw17">limit_conn</span></a> one <span class="nu0">1</span><span class="sy0">;</span> <span class="br0">}</span></pre> </div> </div><p>This allows not more than one simultaneous connection from one address. </p><br><i>Module: HttpLimitZoneModule</i> <|start_filename|>resources/docs/directives/fastcgi_cache_key.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpFastcgiModule&amp;action=edit&amp;section=9" title="Edit section: fastcgi cache key">edit</a>]</span> <span class="mw-headline" id="fastcgi_cache_key"> fastcgi_cache_key </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>fastcgi_cache_key</b> <i>string</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_cache_key">fastcgi_cache_key</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 61/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> The directive sets the key for caching, for example: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"> fastcgi_cache_key <span class="st0">&quot;$scheme$request_method$host$request_uri&quot;</span><span class="sy0">;</span></pre> </div> </div><p>Be advised that a <code>HEAD</code> request can cause an empty response to be cached &amp; later be distributed to <code>GET</code> requests, avoid this by having <a href="/HttpCoreModule#.24request_method" title="HttpCoreModule">$request_method</a> in the cache key. Including the <a href="/HttpCoreModule#.24scheme" title="HttpCoreModule">$scheme</a> for the same reason may be beneficial to avoid serving up pages with insecure content to HTTPS visitors (or vice-versa). </p><br><i>Module: HttpFastcgiModule</i> <|start_filename|>resources/docs/directives/include.html<|end_filename|> <h3>Directive can have multiple meanings. Each variant is separated with horizontal line</h3><hr><h2><span class="editsection">[<a href="/index.php?title=CoreModule&amp;action=edit&amp;section=7" title="Edit section: include">edit</a>]</span> <span class="mw-headline" id="include"> include </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>include</b> <i>file</i> | <i>mask</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> </td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/ngx_core_module.html#include">include</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 50/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> You can include any configuration files for what ever purpose you want. </p><p>Since 0.4.4, the <code>include</code> directive also supports filename globbing: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#include"><span class="kw1">include</span></a> vhosts/*.conf<span class="sy0">;</span></pre> </div> </div><p>Note that until version 0.6.7, paths are relative to what was specified to <code>configure</code> via the <code>--prefix=&lt;PATH&gt;</code> directive, which by default is <code>/usr/local/nginx</code>. If you didn't set this when you compiled Nginx, then use absolute paths. </p><p>Since version 0.6.7, paths are relative to directory of nginx configuration file nginx.conf, but not to nginx prefix directory. </p><br><i>Module: CoreModule</i><hr><h2><span class="editsection">[<a href="/index.php?title=HttpSsiModule&amp;action=edit&amp;section=12" title="Edit section: include">edit</a>]</span> <span class="mw-headline" id="include"> include </span></h2><p>Include a document from another source. </p><ul> <li> <code>file</code> — include a file, e.g. </li> </ul><pre> &lt;!--# include file=&quot;footer.html&quot; --&gt; </pre><ul> <li> <code>virtual</code> — include a request, e.g. </li> </ul><pre> &lt;!--# include virtual=&quot;/remote/body.php?argument=value&quot; --&gt; </pre><p>The target of &quot;file&quot; or &quot;virtual&quot; must be a location in the server configuration. </p><p>The distinction between &quot;file&quot; and &quot;virtual&quot; is mostly historical. &quot;file&quot; is the same as &quot;virtual&quot; with implied &quot;wait&quot; option. At one point the directives mirrored the Apache equivalents but now they are basically the same operation. Both can handle a URI and both can serve a static file. </p><p>Multiple requests will be issued in parallel. If you need them issued sequentially, use the &quot;wait&quot; option. </p><ul> <li> <code>stub</code> — The name of the block to use as a default if the request is empty or returns an error. </li> </ul><pre> &lt;!--# block name=&quot;one&quot; --&gt;&nbsp;&lt;!--# endblock --&gt; &lt;!--# include virtual=&quot;/remote/body.php?argument=value&quot; stub=&quot;one&quot; --&gt; </pre><ul> <li> <code>wait</code> — when set to yes, the rest of the SSI will not be evaluated until the current request is finished. Example: </li> </ul><pre> &lt;!--# include virtual=&quot;/remote/body.php?argument=value&quot; wait=&quot;yes&quot; --&gt; </pre><ul> <li> <code>set</code> — when set to a variable name, the output of the SSI will not be sent to the output, instead the output is set to the variable. Example: </li> </ul><pre> &lt;!--# include virtual=&quot;/remote/body.php?argument=value&quot; set=&quot;body&quot; --&gt; </pre><br><i>Module: HttpSsiModule</i> <|start_filename|>resources/docs/directives/proxy_read_timeout.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpProxyModule&amp;action=edit&amp;section=37" title="Edit section: proxy read timeout">edit</a>]</span> <span class="mw-headline" id="proxy_read_timeout"> proxy_read_timeout </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>proxy_read_timeout</b> <i>time</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>60s</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_read_timeout">proxy_read_timeout</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 311/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> This directive sets the read timeout for the response of the proxied server. It determines how long nginx will wait to get the response to a request. The timeout is established not for entire response, but only between two operations of reading. </p><p>In contrast to <a href="#proxy_connect_timeout">proxy_connect_timeout</a>, this timeout will catch a server that puts you in it's connection pool but does not respond to you with anything beyond that. Be careful though not to set this too low, as your proxy server might take a longer time to respond to requests on purpose (e.g. when serving you a report page that takes some time to compute). You are able though to have a different setting per location, which enables you to have a higher proxy_read_timeout for the report page's location. </p><br><i>Module: HttpProxyModule</i> <|start_filename|>resources/docs/directives/user.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=CoreModule&amp;action=edit&amp;section=14" title="Edit section: user">edit</a>]</span> <span class="mw-headline" id="user"> user </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>user</b> <i>user</i> [ <i>group</i> ]</td> </tr> <tr> <td><b>Default:</b></td> <td> <i>nobody nobody</i></td> </tr> <tr> <td><b>Context:</b></td> <td> main</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/ngx_core_module.html#user">user</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 111/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> If the master process is run as root, then nginx will setuid()/setgid() to USER/GROUP. If GROUP is not specified, then nginx uses the same name as USER. By default it's <code>nobody</code> user and <code>nobody</code> or <code>nogroup</code> group or the <code>--user=USER</code> and <code>--group=GROUP</code> from the <code>./configure</code> script. </p><p>Example: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#user"><span class="kw1">user</span></a> www users<span class="sy0">;</span></pre> </div> </div><br><i>Module: CoreModule</i> <|start_filename|>resources/docs/directives/reset_timedout_connection.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpCoreModule&amp;action=edit&amp;section=52" title="Edit section: reset timedout connection">edit</a>]</span> <span class="mw-headline" id="reset_timedout_connection"> reset_timedout_connection </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>reset_timedout_connection</b> <code>on</code> | <code>off</code> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>off</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_core_module.html#reset_timedout_connection">reset_timedout_connection</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 428/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> This directive enables or disables resetting the connection on timeout. When resetting the connection, before the socket is closed, the socket SO_LINGER option is set with a 0 timeout, which forces the RST packet to be sent to the client upon closing the socket, thus freeing all memory associated with it. This prevents the socket in the FIN_WAIT1 state, along with the buffers associated with it from lying around. </p><p>Note that sockets with keepalive connections, after the defined timeout, are closed in the usual way. </p><br><i>Module: HttpCoreModule</i> <|start_filename|>resources/docs/directives/if.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpRewriteModule&amp;action=edit&amp;section=4" title="Edit section: if">edit</a>]</span> <span class="mw-headline" id="if"> if </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>if</b> ( <i>condition</i> ) { ... }</td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_rewrite_module.html#if">if</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 20/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> <b>note:</b> Before using if please see <a href="/IfIsEvil" title="IfIsEvil">the if is evil page</a> and consider using <a href="/NginxHttpCoreModule#try_files" title="NginxHttpCoreModule" class="mw-redirect">try_files</a> instead. </p><p>Checks the truth of a condition. If the condition evaluates to true, then the code indicated in the curly braces is carried out and the request is processed in accordance with the configuration within the following block. The configuration inside the <code>if</code>directive is inherited from the previous level. </p><p>The condition can be: </p><ul> <li> the name of a variable; false values are: empty string (<code>&quot;&quot;</code>, or any string starting with &quot;0&quot;; </li> <li> a comparison of a variable using the <code>=</code> and <code>!=</code> operators; </li> <li> pattern matching with <a rel="nofollow" class="external text" href="http://perldoc.perl.org/perlretut.html">regular expressions</a>: <ul> <li> <code>~</code> performs a case-sensitive match </li> <li> <code>~*</code> performs a case-insensitive match (<code>firefox</code> matches <code>FireFox</code>) </li> <li> <code>!~</code> and <code>!~*</code> mean the opposite, &quot;doesn't match&quot; </li> </ul> </li> <li> checking for the existence of a file using the <code>-f</code> or <code>!-f</code> operators; </li> <li> checking for the existence of a directory using <code>-d</code> or <code>!-d</code>; </li> <li> checking for the existence of a file, directory or symbolic link using <code>-e</code> or <code>!-e</code>; </li> <li> checking whether a file is executable using <code>-x</code> or <code>!-x</code>. </li> </ul><p>Parts of the regular expressions can be in parentheses, whose value can then later be accessed in the <code>$1</code> to <code>$9</code> variables. See <a rel="nofollow" class="external text" href="http://perldoc.perl.org/perlretut.html#Extracting-matches">Extracting matches</a>. </p><p>Examples of use: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpRewriteModule#if"><span class="kw22">if</span></a> <span class="br0">(</span><span class="re0">$http_user_agent</span> <span class="sy0">~</span> MSIE<span class="br0">)</span> <span class="br0">{</span> <a href="/NginxHttpRewriteModule#rewrite"><span class="kw22">rewrite</span></a> ^<span class="br0">(</span>.*<span class="br0">)</span>$ /msie/$<span class="nu0">1</span> <a href="/NginxHttpRewriteModule#break"><span class="kw22">break</span></a><span class="sy0">;</span> <span class="br0">}</span> &nbsp; <a href="/NginxHttpRewriteModule#if"><span class="kw22">if</span></a> <span class="br0">(</span><span class="re0">$http_cookie</span> <span class="sy0">~</span>* <span class="st0">&quot;id=([^;] +)(?:;|$)&quot;</span> <span class="br0">)</span> <span class="br0">{</span> <a href="/NginxHttpRewriteModule#set"><span class="kw22">set</span></a> <span class="re0">$id</span> $<span class="nu0">1</span><span class="sy0">;</span> <span class="br0">}</span> &nbsp; <a href="/NginxHttpRewriteModule#if"><span class="kw22">if</span></a> <span class="br0">(</span><span class="re0">$request_method</span> <span class="sy0">=</span> POST <span class="br0">)</span> <span class="br0">{</span> <a href="/NginxHttpRewriteModule#return"><span class="kw22">return</span></a> <span class="nu0">405</span><span class="sy0">;</span> <span class="br0">}</span> &nbsp; <a href="/NginxHttpRewriteModule#if"><span class="kw22">if</span></a> <span class="br0">(</span><span class="re0">$slow</span><span class="br0">)</span> <span class="br0">{</span> <a href="/NginxHttpCoreModule#limit_rate"><span class="kw3">limit_rate</span></a> 10k<span class="sy0">;</span> <span class="br0">}</span> &nbsp; <a href="/NginxHttpRewriteModule#if"><span class="kw22">if</span></a> <span class="br0">(</span><span class="re0">$invalid_referer</span><span class="br0">)</span> <span class="br0">{</span> <a href="/NginxHttpRewriteModule#return"><span class="kw22">return</span></a> <span class="nu0">403</span><span class="sy0">;</span> <span class="br0">}</span> &nbsp; <a href="/NginxHttpRewriteModule#if"><span class="kw22">if</span></a> <span class="br0">(</span><span class="re0">$args</span> <span class="sy0">~</span> post<span class="sy0">=</span><span class="nu0">140</span><span class="br0">)</span><span class="br0">{</span> <a href="/NginxHttpRewriteModule#rewrite"><span class="kw22">rewrite</span></a> ^ <a href="/NginxHttpCoreModule#http"><span class="kw3">http</span></a>://example.com/ permanent<span class="sy0">;</span> <span class="br0">}</span></pre> </div> </div><p>The value of the built-in variable <code>$invalid_referer</code> is given by the directive <a href="/HttpRefererModule#valid_referers" title="HttpRefererModule">valid_referers</a>. </p><br><i>Module: HttpRewriteModule</i> <|start_filename|>resources/docs/directives/dav_access.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpDavModule&amp;action=edit&amp;section=3" title="Edit section: dav access">edit</a>]</span> <span class="mw-headline" id="dav_access"> dav_access </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>dav_access</b> <i>users</i>&nbsp;: <i>permissions</i> ...</td> </tr> <tr> <td><b>Default:</b></td> <td> <i>user:rw</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_dav_module.html#dav_access">dav_access</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 16/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> This directive assigns access rights for file and directories, for example: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpDavModule#dav_access"><span class="kw34">dav_access</span></a> <a href="/NginxHttpCoreModule#user"><span class="kw1">user</span></a>:rw group:rw all:r<span class="sy0">;</span></pre> </div> </div><p>If assigning any permissions for <code>groups</code> or <code>all</code>, then it's not necessary to indicate permissions for <code>user</code>: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpDavModule#dav_access"><span class="kw34">dav_access</span></a> group:rw all:r<span class="sy0">;</span></pre> </div> </div><br><i>Module: HttpDavModule</i> <|start_filename|>resources/docs/directives/sendfile.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpCoreModule&amp;action=edit&amp;section=60" title="Edit section: sendfile">edit</a>]</span> <span class="mw-headline" id="sendfile"> sendfile </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>sendfile</b> <code>on</code> | <code>off</code> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>off</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location<br />if in location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_core_module.html#sendfile">sendfile</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 496/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Directive activate or deactivate the usage of <code>sendfile()</code>. </p><p>sendfile() copies data between one file descriptor and another. Because this copying is done within the kernel, sendfile() is more efficient than the combination of read(2) and write(2), which would require transferring data to and from user space. </p><p>Read more at: <a rel="nofollow" class="external free" href="https://www.kernel.org/doc/man-pages/online/pages/man2/sendfile.2.html">https://www.kernel.org/doc/man-pages/online/pages/man2/sendfile.2.html</a> </p><p>How sendfile helps&nbsp;: <a rel="nofollow" class="external free" href="http://www.techrepublic.com/article/use-sendfile-to-optimize-data-transfer/1044112">http://www.techrepublic.com/article/use-sendfile-to-optimize-data-transfer/1044112</a> </p><br><i>Module: HttpCoreModule</i> <|start_filename|>resources/docs/directives/perl_modules.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpPerlModule&amp;action=edit&amp;section=6" title="Edit section: perl modules">edit</a>]</span> <span class="mw-headline" id="perl_modules"> perl_modules </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>perl_modules</b> <i>path</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> http</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_perl_module.html#perl_modules">perl_modules</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 25/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Directive assigns additional path for Perl modules. Since version 0.6.7 this path is relative to directory of nginx configuration file nginx.conf, but not to nginx prefix directory. </p><br><i>Module: HttpPerlModule</i> <|start_filename|>src/net/ishchenko/idea/nginx/run/NginxConsoleFilter.java<|end_filename|> package net.ishchenko.idea.nginx.run; import com.intellij.execution.filters.RegexpFilter; import com.intellij.openapi.project.Project; /** * Created by IntelliJ IDEA. * User: Max * Date: 13.08.2009 * Time: 18:27:37 * To change this template use File | Settings | File Templates. */ /** * Responsible for clickable configuration file references in console */ public class NginxConsoleFilter extends RegexpFilter { public NginxConsoleFilter(Project project) { super(project, ".+ in $FILE_PATH$:$LINE$"); } } <|start_filename|>resources/docs/directives/open_log_file_cache.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpLogModule&amp;action=edit&amp;section=5" title="Edit section: open log file cache">edit</a>]</span> <span class="mw-headline" id="open_log_file_cache"> open_log_file_cache </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>open_log_file_cache</b> <code>max</code> = <i>N</i> [ <code>inactive</code> = <i>time</i> ] [ <code>min_uses</code> = <i>N</i> ] [ <code>valid</code> = <i>time</i> ]<br /><b>open_log_file_cache</b> <code>off</code> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>off</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_log_module.html#open_log_file_cache">open_log_file_cache</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 30/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> The directive sets the cache, which stores file descriptors of frequently used logs with variable in path. </p><p>Directive options: </p><ul> <li> max - maximal number of descriptors in the cache, with overflow Least Recently Used is removed (LRU); </li> <li> inactive - sets the time after which descriptor without hits during this time are removed; default is 10 seconds; </li> <li> min_uses - sets the minimum number of file usage within the time specified in parameter <i>inactive</i>, after which the file descriptor will be put in the cache; default is 1; </li> <li> valid - sets the time until it will be checked if file still exists under same name; default is 60 seconds; </li> <li> off - disables the cache. </li> </ul><p>Example: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpLogModule#open_log_file_cache"><span class="kw18">open_log_file_cache</span></a> max<span class="sy0">=</span><span class="nu0">1000</span> inactive<span class="sy0">=</span>20s min_uses<span class="sy0">=</span><span class="nu0">2</span> valid<span class="sy0">=</span>1m<span class="sy0">;</span></pre> </div> </div><h1><span class="editsection">[<a href="/index.php?title=HttpLogModule&amp;action=edit&amp;section=6" title="Edit section: References">edit</a>]</span> <span class="mw-headline" id="References"> References </span></h1><p><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_log_module.html">Original Documentation</a> </p><br><i>Module: HttpLogModule</i> <|start_filename|>resources/docs/directives/open_file_cache.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpCoreModule&amp;action=edit&amp;section=41" title="Edit section: open file cache">edit</a>]</span> <span class="mw-headline" id="open_file_cache"> open_file_cache </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>open_file_cache</b> <code>off</code> <br /><b>open_file_cache</b> <code>max</code> = <i>N</i> [ <code>inactive</code> = <i>time</i> ]</td> </tr> <tr> <td><b>Default:</b></td> <td> <i>off</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_core_module.html#open_file_cache">open_file_cache</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 351/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> The directive sets the cache activity on. These information can be stored: </p><ul> <li> Open file descriptors, information with their size and modification time; </li> <li> Information about the existence of directories; </li> <li> Error information when searches for a file - no file, do not have rights to read, etc. See also <a href="#open_file_cache_errors">open_file_cache_errors</a> </li> </ul><p>Options directive: </p><ul> <li> <code>max</code> - specifies the maximum number of entries in the cache. When the cache overflows, the least recently used(LRU) items will be removed; </li> <li> <code>inactive</code> - specifies the time when the cached item is removed, if it has not been downloaded during that time, the default is 60 seconds; </li> <li> <code>off</code> - prohibits the cache activity. </li> </ul><p>Example: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"> open_file_cache max<span class="sy0">=</span><span class="nu0">1000</span> inactive<span class="sy0">=</span>20s<span class="sy0">;</span> open_file_cache_valid 30s<span class="sy0">;</span> open_file_cache_min_uses <span class="nu0">2</span><span class="sy0">;</span> open_file_cache_errors on<span class="sy0">;</span></pre> </div> </div><br><i>Module: HttpCoreModule</i> <|start_filename|>resources/docs/directives/error_log.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=CoreModule&amp;action=edit&amp;section=6" title="Edit section: error log">edit</a>]</span> <span class="mw-headline" id="error_log"> error_log </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>error_log</b> <i>file</i> | <code>stderr</code> [ <code>debug</code> | <code>info</code> | <code>notice</code> | <code>warn</code> | <code>error</code> | <code>crit</code> | <code>alert</code> | <code>emerg</code> ]</td> </tr> <tr> <td><b>Default:</b></td> <td> <i>logs/error.log error</i></td> </tr> <tr> <td><b>Context:</b></td> <td> main<br />http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/ngx_core_module.html#error_log">error_log</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 34/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Specifies the file where server (and fastcgi) errors are logged. </p><p>Default values for the error level: </p><ol> <li> in the main section - <code>error</code> </li> <li> in the HTTP section - <code>crit</code> </li> <li> in the server section - <code>crit</code> </li> </ol><p>If you've built Nginx with <code>--with-debug</code>, you may also use: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#error_log"><span class="kw1">error_log</span></a> LOGFILE <span class="br0">[</span>debug_core | debug_alloc | debug_mutex | debug_event | debug_http | debug_imap<span class="br0">]</span><span class="sy0">;</span></pre> </div> </div><p>Note that <code>error_log off</code> does not disable logging - the log will be written to a file named &quot;off&quot;. To disable logging, you may use: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#error_log"><span class="kw1">error_log</span></a> /dev/null crit<span class="sy0">;</span></pre> </div> </div><p>Also note that as of version 0.7.53, nginx will use a compiled-in default error log location until it has read the config file. If the user running nginx doesn't have write permission to this log location, nginx will raise an alert like this: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="text source-text"> <pre class="de1">[alert]: could not open error log file: open() &quot;/var/log/nginx/error.log&quot; failed (13: Permission denied)</pre> </div> </div><br><i>Module: CoreModule</i> <|start_filename|>resources/docs/directives/deny.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpAccessModule&amp;action=edit&amp;section=4" title="Edit section: deny">edit</a>]</span> <span class="mw-headline" id="deny"> deny </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>deny</b> <i>address</i> | <i>CIDR</i> | <code>all</code> </td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location<br />limit_except</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_access_module.html#deny">deny</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 23/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Directive forbids access for the network or addresses indicated. </p><h1><span class="editsection">[<a href="/index.php?title=HttpAccessModule&amp;action=edit&amp;section=5" title="Edit section: Tips &amp; Tricks">edit</a>]</span> <span class="mw-headline" id="Tips_.26_Tricks"> Tips &amp; Tricks </span></h1><p>The NginxHttpAccessModule can be used in conjunction with the <i>error_page</i> directive to redirect unauthorised visitors to an alternative site: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#error_page"><span class="kw3">error_page</span></a> <span class="nu0">403</span> <a href="/NginxHttpCoreModule#http"><span class="kw3">http</span></a>://example.com/forbidden.html<span class="sy0">;</span> <a href="/NginxHttpCoreModule#location"><span class="kw3">location</span></a> / <span class="br0">{</span> <a href="/NginxHttpAccessModule#deny"><span class="kw5">deny</span></a> 192.168.1.1<span class="sy0">;</span> <a href="/NginxHttpAccessModule#allow"><span class="kw5">allow</span></a> 192.168.1.0/<span class="nu0">24</span><span class="sy0">;</span> <a href="/NginxHttpAccessModule#allow"><span class="kw5">allow</span></a> 10.1.1.0/<span class="nu0">16</span><span class="sy0">;</span> <a href="/NginxHttpAccessModule#deny"><span class="kw5">deny</span></a> all<span class="sy0">;</span> <span class="br0">}</span></pre> </div> </div><h1><span class="editsection">[<a href="/index.php?title=HttpAccessModule&amp;action=edit&amp;section=6" title="Edit section: References">edit</a>]</span> <span class="mw-headline" id="References"> References </span></h1><p><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_access_module.html">Original Documentation</a> </p><br><i>Module: HttpAccessModule</i> <|start_filename|>resources/docs/directives/proxy_ignore_headers.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpProxyModule&amp;action=edit&amp;section=26" title="Edit section: proxy ignore headers">edit</a>]</span> <span class="mw-headline" id="proxy_ignore_headers"> proxy_ignore_headers </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>proxy_ignore_headers</b> <i>field</i> ...</td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_ignore_headers">proxy_ignore_headers</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 195/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Prohibits the processing of the header lines from the proxy server's response. </p><p>It can specify the string as &quot;<a href="/XSendfile" title="XSendfile">X-Accel-Redirect</a>&quot;, &quot;X-Accel-Expires&quot;, &quot;Expires&quot;, &quot;Cache-Control&quot; or &quot;Set-Cookie&quot;. By default, nginx does not caches requests with Set-Cookie. </p><br><i>Module: HttpProxyModule</i> <|start_filename|>resources/docs/directives/gzip_min_length.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpGzipModule&amp;action=edit&amp;section=8" title="Edit section: gzip min length">edit</a>]</span> <span class="mw-headline" id="gzip_min_length"> gzip_min_length </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>gzip_min_length</b> <i>length</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>20</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_gzip_module.html#gzip_min_length">gzip_min_length</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 54/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Sets the minimum length, in bytes, of the response that will be compressed. Responses shorter than this byte-length will not be compressed. Length is determined from the &quot;Content-Length&quot; header. </p><p><br /> </p><br><i>Module: HttpGzipModule</i> <|start_filename|>resources/docs/directives/master_process.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=CoreModule&amp;action=edit&amp;section=9" title="Edit section: master process">edit</a>]</span> <span class="mw-headline" id="master_process"> master_process </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>master_process</b> <code>on</code> | <code>off</code> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>on</i></td> </tr> <tr> <td><b>Context:</b></td> <td> main</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/ngx_core_module.html#master_process">master_process</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 64/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#master_process"><span class="kw1">master_process</span></a> off<span class="sy0">;</span></pre> </div> </div><p>Do not use the &quot;daemon&quot; and &quot;master_process&quot; directives in a production mode, these options are mainly used for development only. </p><br><i>Module: CoreModule</i> <|start_filename|>resources/docs/directives/gzip_proxied.html<|end_filename|> <h3>Directive can have multiple meanings. Each variant is separated with horizontal line</h3><hr><h2><span class="editsection">[<a href="/index.php?title=HttpGzipModule&amp;action=edit&amp;section=9" title="Edit section: gzip proxied">edit</a>]</span> <span class="mw-headline" id="gzip_proxied"> gzip_proxied </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>gzip_proxied</b> <code>off</code> | <code>expired</code> | <code>no-cache</code> | <code>no-store</code> | <code>private</code> | <code>no_last_modified</code> | <code>no_etag</code> | <code>auth</code> | <code>any</code> ...</td> </tr> <tr> <td><b>Default:</b></td> <td> <i>off</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_gzip_module.html#gzip_proxied">gzip_proxied</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 61/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> It allows or disallows the compression of the response for the proxy request in the dependence on the request and the response. The fact that, request proxy, is determined on the basis of line &quot;Via&quot; in the headers of request. In the directive it is possible to indicate simultaneously several parameters: </p><ul> <li> off - disables compression for all proxied requests </li> <li> expired - enables compression, if the &quot;Expires&quot; header prevents caching </li> <li> no-cache - enables compression if &quot;Cache-Control&quot; header is set to &quot;no-cache&quot; </li> <li> no-store - enables compression if &quot;Cache-Control&quot; header is set to &quot;no-store&quot; </li> <li> private - enables compression if &quot;Cache-Control&quot; header is set to &quot;private&quot; </li> <li> no_last_modified - enables compression if &quot;Last-Modified&quot; isn't set </li> <li> no_etag - enables compression if there is no &quot;ETag&quot; header </li> <li> auth - enables compression if there is an &quot;Authorization&quot; header </li> <li> any - enables compression for all requests </li> </ul><br><i>Module: HttpGzipModule</i><hr><h2><span class="editsection">[<a href="/index.php?title=HttpGzipStaticModule&amp;action=edit&amp;section=5" title="Edit section: gzip proxied">edit</a>]</span> <span class="mw-headline" id="gzip_proxied"> gzip_proxied </span></h2><p>See <a href="/NginxHttpGzipModule#gzip_proxied" title="NginxHttpGzipModule" class="mw-redirect"> NginxHttpGzipModule</a> </p><br><i>Module: HttpGzipStaticModule</i> <|start_filename|>resources/docs/directives/proxy_buffer_size.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpProxyModule&amp;action=edit&amp;section=4" title="Edit section: proxy buffer size">edit</a>]</span> <span class="mw-headline" id="proxy_buffer_size"> proxy_buffer_size </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>proxy_buffer_size</b> <i>size</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>4k|8k</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_buffer_size">proxy_buffer_size</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 17/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> This directive set the buffer size, into which will be read the first part of the response, obtained from the proxied server. </p><p>In this part of response the small response-header is located, as a rule. </p><p>By default, the buffer size is equal to the size of one buffer in directive <code>proxy_buffers</code>; however, it is possible to set it to less. </p><br><i>Module: HttpProxyModule</i> <|start_filename|>resources/docs/directives/proxy_buffers.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpProxyModule&amp;action=edit&amp;section=6" title="Edit section: proxy buffers">edit</a>]</span> <span class="mw-headline" id="proxy_buffers"> proxy_buffers </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>proxy_buffers</b> <i>number</i> <i>size</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>8 4k|8k</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_buffers">proxy_buffers</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 31/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> This directive sets the number and the size of buffers, into which will be read the answer, obtained from the proxied server. By default, the size of one buffer is equal to the size of page. Depending on platform this is either 4K or 8K. </p><br><i>Module: HttpProxyModule</i> <|start_filename|>resources/docs/directives/sub_filter.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpSubModule&amp;action=edit&amp;section=3" title="Edit section: sub filter">edit</a>]</span> <span class="mw-headline" id="sub_filter"> sub_filter </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>sub_filter</b> <i>string</i> <i>replacement</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_sub_module.html#sub_filter">sub_filter</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 16/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> <i>sub_filter</i> allows replacing some text in the nginx response with some other text, independently of the source of the data. The matching is case-insensitive. Substitution text may contain variables. Only one substitution rule per location is supported. </p><br><i>Module: HttpSubModule</i> <|start_filename|>resources/docs/directives/client_body_temp_path.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpCoreModule&amp;action=edit&amp;section=9" title="Edit section: client body temp path">edit</a>]</span> <span class="mw-headline" id="client_body_temp_path"> client_body_temp_path </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>client_body_temp_path</b> <i>path</i> [ <i>level1</i> [ <i>level2</i> [ <i>level3</i> ]]]</td> </tr> <tr> <td><b>Default:</b></td> <td> <i>client_body_temp</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_core_module.html#client_body_temp_path">client_body_temp_path</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 67/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> The directive assigns the directory for storing the temporary files in it with the body of the request. </p><p>In the <code>dir-path</code> a hierarchy of subdirectories up to three levels are possible. </p><p>For example </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#client_body_temp_path"><span class="kw3">client_body_temp_path</span></a> /spool/nginx/client_temp <span class="nu0">1</span> <span class="nu0">2</span><span class="sy0">;</span></pre> </div> </div><p>The directory structure will be like this: </p><pre> /spool/nginx/client_temp/7/45/00000123457 </pre><br><i>Module: HttpCoreModule</i> <|start_filename|>resources/docs/directives/if_modified_since.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpCoreModule&amp;action=edit&amp;section=20" title="Edit section: if modified since">edit</a>]</span> <span class="mw-headline" id="if_modified_since"> if_modified_since </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>if_modified_since</b> <code>off</code> | <code>exact</code> | <code>before</code> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>exact</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Appeared in:</b></td> <td> 0.7.24</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_core_module.html#if_modified_since">if_modified_since</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 165/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Specifies how to compare time of file modification and time in request header &quot;If-Modified-Since&quot;: </p><ul> <li> off — don't check &quot;If-Modified-Since&quot; request header (0.7.34); </li> <li> exact — exact match; </li> <li> before — file modification time should be less than time in &quot;If-Modified-Since&quot; request header. </li> </ul><br><i>Module: HttpCoreModule</i> <|start_filename|>resources/docs/directives/client_header_timeout.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpCoreModule&amp;action=edit&amp;section=12" title="Edit section: client header timeout">edit</a>]</span> <span class="mw-headline" id="client_header_timeout"> client_header_timeout </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>client_header_timeout</b> <i>time</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>60s</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_core_module.html#client_header_timeout">client_header_timeout</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 94/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Specifies how long to wait for the client to send a request header (e.g.: <code>GET / HTTP/1.1</code>). </p><p>This timeout is reached only if a header is not received in one read <i>(needs clarification)</i>. If the client has not sent anything within this timeout period, nginx returns the HTTP status code 408 (&quot;Request timed out&quot;) </p><br><i>Module: HttpCoreModule</i> <|start_filename|>resources/docs/directives/tcp_nopush.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpCoreModule&amp;action=edit&amp;section=69" title="Edit section: tcp nopush">edit</a>]</span> <span class="mw-headline" id="tcp_nopush"> tcp_nopush </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>tcp_nopush</b> <code>on</code> | <code>off</code> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>off</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_core_module.html#tcp_nopush">tcp_nopush</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 586/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> This directive permits or forbids the use of the socket options <code>TCP_NOPUSH</code> on FreeBSD or <code>TCP_CORK</code> on Linux. This option is only available when using <code>sendfile</code>. </p><p>Setting this option causes nginx to attempt to send it's HTTP response headers in one packet on Linux and FreeBSD 4.x </p><p>You can read more about the <code>TCP_NOPUSH</code> and <code>TCP_CORK</code> socket options <a href="/ReadMoreAboutTcpNopush" title="ReadMoreAboutTcpNopush">here</a>. </p><br><i>Module: HttpCoreModule</i> <|start_filename|>src/net/ishchenko/idea/nginx/psi/NginxDirective.java<|end_filename|> /* * Copyright 2009 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.ishchenko.idea.nginx.psi; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; /** * Created by IntelliJ IDEA. * User: Max * Date: 09.07.2009 * Time: 21:03:39 */ public interface NginxDirective extends NginxPsiElement { @NotNull String getNameString(); @NotNull NginxDirectiveName getDirectiveName(); @Nullable NginxContext getDirectiveContext(); @Nullable NginxContext getParentContext(); @NotNull List<NginxComplexValue> getValues(); /** * @return the directive is inside a context where any directive name is possible (e.g. types, charset_map etc) */ boolean isInChaosContext(); boolean hasContext(); } <|start_filename|>resources/docs/directives/open_file_cache_errors.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpCoreModule&amp;action=edit&amp;section=42" title="Edit section: open file cache errors">edit</a>]</span> <span class="mw-headline" id="open_file_cache_errors"> open_file_cache_errors </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>open_file_cache_errors</b> <code>on</code> | <code>off</code> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>off</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_core_module.html#open_file_cache_errors">open_file_cache_errors</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 361/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> The directive specifies whether or not to cache errors when searching for a file. </p><br><i>Module: HttpCoreModule</i> <|start_filename|>resources/docs/directives/msie_padding.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpCoreModule&amp;action=edit&amp;section=39" title="Edit section: msie padding">edit</a>]</span> <span class="mw-headline" id="msie_padding"> msie_padding </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>msie_padding</b> <code>on</code> | <code>off</code> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>on</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_core_module.html#msie_padding">msie_padding</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 337/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> This directive enables or disables the msie_padding feature for MSIE browsers, and Chrome (as of nginx 0.8.25+). When this is enabled, nginx will pad the size of the response body to a minimum of 512 bytes for responses with a status code above or equal to 400. </p><p>The padding prevents the activation of &quot;friendly&quot; HTTP error pages in MSIE and Chrome, so as to not hide/mask the more-informative error pages from the server. </p><br><i>Module: HttpCoreModule</i> <|start_filename|>resources/docs/directives/alias.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpCoreModule&amp;action=edit&amp;section=4" title="Edit section: alias">edit</a>]</span> <span class="mw-headline" id="alias"> alias </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>alias</b> <i>path</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_core_module.html#alias">alias</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 26/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> This directive assigns a path to be used as the basis for serving requests for the indicated location. Note that it may look similar to the <code>root</code> directive at first sight, but the document root doesn't change, just the file system path used for the request. The location part of the request is <b>dropped</b> in the request Nginx issues. Let's see this in action. Consider the following example. </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#location"><span class="kw3">location</span></a> /i/ <span class="br0">{</span> <a href="/NginxHttpCoreModule#alias"><span class="kw3">alias</span></a> /spool/w3/images/<span class="sy0">;</span> <span class="br0">}</span></pre> </div> </div><p>A request for &quot;/i/top.gif&quot; will instruct Nginx to serve the file &quot;/spool/w3/images/top.gif&quot;. As you can see, <b>only</b> the part of the URI <b>after</b> the location is appended. The location itself, in this case &quot;/i/&quot;, is dropped. With a <code>root</code> directive the <b>full</b> path is appended, i.e., in the above example it would have been, &quot;/spool/w3/images/i/top.gif&quot; — hence including <b>also</b> the location &quot;/i/&quot;. </p><p>Aliases can also be used in a location specified by a regex. </p><p>For example: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#location"><span class="kw3">location</span></a> <span class="sy0">~</span> ^/download/<span class="br0">(</span>.*<span class="br0">)</span>$ <span class="br0">{</span> <a href="/NginxHttpCoreModule#alias"><span class="kw3">alias</span></a> /home/website/files/$<span class="nu0">1</span><span class="sy0">;</span> <span class="br0">}</span></pre> </div> </div><p>The request &quot;/download/book.pdf&quot; will return the file &quot;/home/website/files/book.pdf&quot;. Note again that only part of the request URI <b>after</b> the location is appended to the path defined by <code>alias</code>. </p><p>It is possible to use variables in the replacement path. </p><p>Note that there is a <a rel="nofollow" class="external text" href="http://trac.nginx.org/nginx/ticket/97">longstanding bug</a> that <code>alias</code> and <code>try_files</code> don't work together. </p><br><i>Module: HttpCoreModule</i> <|start_filename|>resources/docs/directives/gzip_http_version.html<|end_filename|> <h3>Directive can have multiple meanings. Each variant is separated with horizontal line</h3><hr><h2><span class="editsection">[<a href="/index.php?title=HttpGzipModule&amp;action=edit&amp;section=7" title="Edit section: gzip http version">edit</a>]</span> <span class="mw-headline" id="gzip_http_version"> gzip_http_version </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>gzip_http_version</b> <code>1.0</code> | <code>1.1</code> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>1.1</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_gzip_module.html#gzip_http_version">gzip_http_version</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 47/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Turns gzip compression on or off depending on the HTTP request version. </p><p>Note that the Content-Length header is not set when using either version. Keepalives will therefore be impossible with version 1.0, while for 1.1 it is handled by chunked transfers. </p><p><br /> </p><br><i>Module: HttpGzipModule</i><hr><h2><span class="editsection">[<a href="/index.php?title=HttpGzipStaticModule&amp;action=edit&amp;section=4" title="Edit section: gzip http version">edit</a>]</span> <span class="mw-headline" id="gzip_http_version"> gzip_http_version </span></h2><p>See <a href="/NginxHttpGzipModule#gzip_http_version" title="NginxHttpGzipModule" class="mw-redirect"> NginxHttpGzipModule</a> </p><br><i>Module: HttpGzipStaticModule</i> <|start_filename|>resources/docs/directives/uwsgi_string.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpUwsgiModule&amp;action=edit&amp;section=37" title="Edit section: uwsgi string">edit</a>]</span> <span class="mw-headline" id="uwsgi_string"> uwsgi_string </span></h2><p><b>syntax:</b> <i>uwsgi_string string</i> </p><p><b>default:</b> <i>none</i> </p><p><b>context:</b> <i>server, location</i> </p><p>append a string to a uwsgi request </p><p>Example (for a uwsgi compatible server that support the <b>eval modifier</b> as uWSGI) </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"> <a href="/NginxHttpCoreModule#location"><span class="kw3">location</span></a> / <span class="br0">{</span> <a href="/NginxHttpUwsgiModule#uwsgi_pass"><span class="kw37">uwsgi_pass</span></a> unix:/var/run/example.com.sock<span class="sy0">;</span> uwsgi_pass_request_headers off<span class="sy0">;</span> uwsgi_pass_request_body off<span class="sy0">;</span> uwsgi_string <span class="st0">&quot; &nbsp; import uwsgi &nbsp; uwsgi.start_response('200 OK', [('Content-type','text/plain')]) total = 30+22 uwsgi.send(&quot;</span><span class="nu0">30</span> + <span class="nu0">22</span> <span class="sy0">=</span> <span class="re0">%d</span><span class="st0">&quot;&nbsp;% total) &nbsp; &quot;</span><span class="sy0">;</span> &nbsp; uwsgi_modifier1 <span class="nu0">22</span><span class="sy0">;</span> uwsgi_modifier2 <span class="nu0">0</span><span class="sy0">;</span> &nbsp; <span class="br0">}</span></pre> </div> </div><br><i>Module: HttpUwsgiModule</i> <|start_filename|>resources/docs/directives/auth_basic.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpAuthBasicModule&amp;action=edit&amp;section=3" title="Edit section: auth basic">edit</a>]</span> <span class="mw-headline" id="auth_basic"> auth_basic </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>auth_basic</b> <i>string</i> | <code>off</code> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>off</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location<br />limit_except</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_auth_basic_module.html#auth_basic">auth_basic</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 13/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> This directive includes testing name and password with HTTP Basic Authentication. The assigned parameter is used as authentication realm. A value of &quot;off&quot; makes it possible to override the action for the inheritable from a lower-level directive. </p><p><br /> </p><br><i>Module: HttpAuthBasicModule</i> <|start_filename|>resources/docs/directives/optimize_server_names.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpCoreModule&amp;action=edit&amp;section=45" title="Edit section: optimize server names">edit</a>]</span> <span class="mw-headline" id="optimize_server_names"> optimize_server_names </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>optimize_server_names</b> <code>on</code> | <code>off</code> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>off</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_core_module.html#optimize_server_names">optimize_server_names</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 382/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Directive activates or deactivates optimization of host name checks for name-based virtual servers. </p><p>In particular, the check influences the name of the host used in redirects. If optimization is on, and all name-based servers listening on one address:port pair have identical configuration, then names are not checked during request execution and redirects use first server name. </p><p>If redirect must use host name passed by the client, then the optimization must be turned off. </p><p>Note: this directive is deprecated in nginx 0.7.x, use <a href="#server_name_in_redirect">server_name_in_redirect</a> instead. </p><br><i>Module: HttpCoreModule</i> <|start_filename|>resources/docs/directives/perl.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpPerlModule&amp;action=edit&amp;section=5" title="Edit section: perl">edit</a>]</span> <span class="mw-headline" id="perl"> perl </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>perl</b> <i>module</i>&nbsp;:: <i>function</i> |'sub { ... }'</td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> location<br />limit_except</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_perl_module.html#perl">perl</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 18/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Directive establishes a function for the data location. </p><br><i>Module: HttpPerlModule</i> <|start_filename|>resources/docs/directives/fastcgi_split_path_info.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpFastcgiModule&amp;action=edit&amp;section=35" title="Edit section: fastcgi split path info">edit</a>]</span> <span class="mw-headline" id="fastcgi_split_path_info"> fastcgi_split_path_info </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>fastcgi_split_path_info</b> <i>regex</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_split_path_info">fastcgi_split_path_info</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 323/1000000 Post-expand include size: 401/2097152 bytes Template argument size: 178/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> This directive allows the setting of the SCRIPT_FILENAME (SCRIPT_NAME) and PATH_INFO variables of the <a rel="nofollow" class="external text" href="http://www.ietf.org/rfc/rfc3875">CGI specification</a>. The regex consists of <b>two</b> groups: </p><ul> <li> path to the script that will handle the request — corresponding to <code>$fastcgi_script_name</code>. </li> <li> the value of the parameter to be given to the script — corresponding to the <code>$fastcgi_path_info</code>. </li> </ul><p><br /> Here's an example. The script <code>show.php</code> receives as argument the string <code>article/0001</code>. The following configuration will handle path splitting properly: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#location"><span class="kw3">location</span></a> <span class="sy0">~</span> ^.+\.php <span class="br0">{</span> <span class="br0">(</span>...<span class="br0">)</span> <a href="/NginxHttpFcgiModule#fastcgi_split_path_info"><span class="kw11">fastcgi_split_path_info</span></a> ^<span class="br0">(</span><span class="br0">(</span>?U<span class="br0">)</span>.+\.php<span class="br0">)</span><span class="br0">(</span>/?.+<span class="br0">)</span>$<span class="sy0">;</span> <a href="/NginxHttpFcgiModule#fastcgi_param"><span class="kw11">fastcgi_param</span></a> SCRIPT_FILENAME <span class="re0">$document_root</span><span class="re0">$fastcgi_script_name</span><span class="sy0">;</span> <a href="/NginxHttpFcgiModule#fastcgi_param"><span class="kw11">fastcgi_param</span></a> PATH_INFO <span class="re0">$fastcgi_path_info</span><span class="sy0">;</span> <a href="/NginxHttpFcgiModule#fastcgi_param"><span class="kw11">fastcgi_param</span></a> PATH_TRANSLATED <span class="re0">$document_root</span><span class="re0">$fastcgi_path_info</span><span class="sy0">;</span> <span class="br0">(</span>...<span class="br0">)</span> <span class="br0">}</span></pre> </div> </div><p>Requesting <code>/show.php/article/0001</code> sets SCRIPT_FILENAME to <code>/path/to/php/show.php</code> and PATH_INFO to <code>/article/0001</code>. </p><br><i>Module: HttpFastcgiModule</i> <|start_filename|>resources/docs/directives/env.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=CoreModule&amp;action=edit&amp;section=4" title="Edit section: env">edit</a>]</span> <span class="mw-headline" id="env"> env </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>env</b> <i>variable</i> [= <i>value</i> ]</td> </tr> <tr> <td><b>Default:</b></td> <td> <i>TZ</i></td> </tr> <tr> <td><b>Context:</b></td> <td> main</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/ngx_core_module.html#env">env</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 20/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> The instruction allows to limit a set of variables of environment, to change it values or to create new variables for following cases: </p><ul> <li> inheritance of variables during <a href="/NginxCommandLine#utnbotf" title="NginxCommandLine" class="mw-redirect"> upgrading the binary with zero downtime</a>&nbsp;; </li> <li> for use by the <a href="/NginxEmbeddedPerlModule" title="NginxEmbeddedPerlModule" class="mw-redirect">embedded Perl module</a> </li> <li> for use by working processes. However it is necessary to keep in mind, that management of behaviour of system libraries in a similar way probably not always as frequently libraries use variables only during initialization, that is still before they can be set by means of the given instruction. Exception to it is the above described updating an executed file with zero downtime. </li> </ul><p>If variable TZ is not described obviously it is always inherited and is always accessible to the <a href="/NginxEmbeddedPerlModule" title="NginxEmbeddedPerlModule" class="mw-redirect">embedded Perl module</a>. </p><p>Example of use: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#env"><span class="kw1">env</span></a> MALLOC_OPTIONS<span class="sy0">;</span> <a href="/NginxHttpCoreModule#env"><span class="kw1">env</span></a> PERL5LIB<span class="sy0">=</span>/data/site/modules<span class="sy0">;</span> <a href="/NginxHttpCoreModule#env"><span class="kw1">env</span></a> OPENSSL_ALLOW_PROXY_CERTS<span class="sy0">=</span><span class="nu0">1</span><span class="sy0">;</span></pre> </div> </div><p>By default, nginx wipes all its environment variables except TZ variable. </p><ul> <li> &quot;env NAME&quot; allows to keep NAME variable value got from parent process, i.e., shell. </li> <li> &quot;env NAME=val&quot; sets NAME variable value. </li> </ul><br><i>Module: CoreModule</i> <|start_filename|>resources/docs/directives/auth_basic_user_file.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpAuthBasicModule&amp;action=edit&amp;section=4" title="Edit section: auth basic user file">edit</a>]</span> <span class="mw-headline" id="auth_basic_user_file"> auth_basic_user_file </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>auth_basic_user_file</b> <i>file</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location<br />limit_except</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_auth_basic_module.html#auth_basic_user_file">auth_basic_user_file</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 20/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> This directive sets the htpasswd filename for the authentication realm. Since version 0.6.7 the filename path is relative to directory of nginx configuration file nginx.conf, but not to nginx prefix directory. </p><p>The format of file is the following: </p><pre> user:pass user2:pass2:comment user3:pass3 </pre><p>Passwords must be encoded by function crypt(3). If Apache is installed, you can create the password file using the htpasswd program included. Note: Apache uses MD5 for encryption. </p><p>As of version 1.0.3 nginx supports &quot;$apr1&quot;, &quot;{PLAIN}&quot; and &quot;{SSHA}&quot; password encryption methods. </p><p>As of version 1.3.13 nginx supports &quot;{SHA}&quot; encryption as well. Plain SHA1 encryption should be considered for migration purposes only and should whenever possible be avoided for security reasons. </p><p>This file should be readable by workers, running from unprivileged <a href="/CoreModule#user" title="CoreModule">user</a>. E. g. when nginx run from <i>www</i> you can set permissions as </p><pre> chown root:nobody htpasswd_file chmod 640 htpasswd_file </pre><p>See also: <a href="/Faq#How_do_I_generate_an_htpasswd_file_without_having_Apache_tools_installed.3F" title="Faq">How do I generate an htpasswd file without having Apache tools installed?</a> </p><h1><span class="editsection">[<a href="/index.php?title=HttpAuthBasicModule&amp;action=edit&amp;section=5" title="Edit section: References">edit</a>]</span> <span class="mw-headline" id="References"> References </span></h1><p><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_auth_basic_module.html">Original Documentation</a> </p><p><a rel="nofollow" class="external text" href="http://kbeezie.com/view/protecting-folders-with-nginx/">Protecting Folders with Auth_Basic</a> </p><br><i>Module: HttpAuthBasicModule</i> <|start_filename|>resources/docs/directives/fastcgi_param.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpFastcgiModule&amp;action=edit&amp;section=27" title="Edit section: fastcgi param">edit</a>]</span> <span class="mw-headline" id="fastcgi_param"> fastcgi_param </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>fastcgi_param</b> <i>parameter</i> <i>value</i> [ <code>if_not_empty</code> ]</td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_param">fastcgi_param</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 208/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Directive assigns the parameter, which will be transferred to the FastCGI-server. </p><p>It is possible to use strings, variables and their combination as values. Directives not set are inherited from the outer level. Directives set in current level clear any previously defined directives for the current level. </p><p>Below is an example of the minimally necessary parameters for PHP: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"> <a href="/NginxHttpFcgiModule#fastcgi_param"><span class="kw11">fastcgi_param</span></a> SCRIPT_FILENAME /home/www/scripts/php<span class="re0">$fastcgi_script_name</span><span class="sy0">;</span> <a href="/NginxHttpFcgiModule#fastcgi_param"><span class="kw11">fastcgi_param</span></a> QUERY_STRING <span class="re0">$query_string</span><span class="sy0">;</span></pre> </div> </div><p>Parameter SCRIPT_FILENAME is used by PHP for determining the name of script to execute, and QUERY_STRING contains the parameters of the request. </p><p>If dealing with POST requests, then the three additional parameters are necessary. Below is an example of the minimally necessary parameters for PHP: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"> <a href="/NginxHttpFcgiModule#fastcgi_param"><span class="kw11">fastcgi_param</span></a> REQUEST_METHOD <span class="re0">$request_method</span><span class="sy0">;</span> <a href="/NginxHttpFcgiModule#fastcgi_param"><span class="kw11">fastcgi_param</span></a> CONTENT_TYPE <span class="re0">$content_type</span><span class="sy0">;</span> <a href="/NginxHttpFcgiModule#fastcgi_param"><span class="kw11">fastcgi_param</span></a> CONTENT_LENGTH <span class="re0">$content_length</span><span class="sy0">;</span></pre> </div> </div><p>If PHP was compiled with --enable-force-cgi-redirect, then it is necessary to transfer parameter REDIRECT_STATUS with the value of &quot;200&quot;: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"> <a href="/NginxHttpFcgiModule#fastcgi_param"><span class="kw11">fastcgi_param</span></a> REDIRECT_STATUS <span class="nu0">200</span><span class="sy0">;</span></pre> </div> </div><br><i>Module: HttpFastcgiModule</i> <|start_filename|>resources/docs/directives/proxy_hide_header.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpProxyModule&amp;action=edit&amp;section=23" title="Edit section: proxy hide header">edit</a>]</span> <span class="mw-headline" id="proxy_hide_header"> proxy_hide_header </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>proxy_hide_header</b> <i>field</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_hide_header">proxy_hide_header</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 168/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> nginx does not transfer the &quot;Date&quot;, &quot;Server&quot;, &quot;X-Pad&quot; and &quot;X-Accel-...&quot; header lines from the proxied server response. The <code>proxy_hide_header</code> directive allows to hide some additional header lines. But if on the contrary the header lines must be passed, then the <code>proxy_pass_header</code> should be used. For example if you want to hide the MS-OfficeWebserver and the AspNet-Version: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#location"><span class="kw3">location</span></a> / <span class="br0">{</span> <a href="/NginxHttpProxyModule#proxy_hide_header"><span class="kw21">proxy_hide_header</span></a> X-AspNet-Version<span class="sy0">;</span> <a href="/NginxHttpProxyModule#proxy_hide_header"><span class="kw21">proxy_hide_header</span></a> MicrosoftOfficeWebServer<span class="sy0">;</span> <span class="br0">}</span></pre> </div> </div><p>This directive can also be very helpful when using <a href="/XSendfile" title="XSendfile">X-Accel-Redirect</a>. For example, you may have one set of backend servers which return the headers for a file download, which includes X-Accel-Redirect to the actual file, as well as the correct Content-Type. However, the Redirect URL points to a files erver which hosts the actual file you wish to serve, and that server sends its own Content-Type header, which might be incorrect, and overrides the header sent by the original backend servers. You can avoid this by adding the proxy_hide_header directive to the fileserver. Example: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#location"><span class="kw3">location</span></a> / <span class="br0">{</span> <a href="/NginxHttpProxyModule#proxy_pass"><span class="kw21">proxy_pass</span></a> <a href="/NginxHttpCoreModule#http"><span class="kw3">http</span></a>://backend_servers<span class="sy0">;</span> <span class="br0">}</span> &nbsp; <a href="/NginxHttpCoreModule#location"><span class="kw3">location</span></a> /files/ <span class="br0">{</span> <a href="/NginxHttpProxyModule#proxy_pass"><span class="kw21">proxy_pass</span></a> <a href="/NginxHttpCoreModule#http"><span class="kw3">http</span></a>://fileserver<span class="sy0">;</span> <a href="/NginxHttpProxyModule#proxy_hide_header"><span class="kw21">proxy_hide_header</span></a> Content-Type<span class="sy0">;</span> <span class="br0">}</span></pre> </div> </div><br><i>Module: HttpProxyModule</i> <|start_filename|>resources/docs/directives/userid_p3p.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpUseridModule&amp;action=edit&amp;section=7" title="Edit section: userid p3p">edit</a>]</span> <span class="mw-headline" id="userid_p3p"> userid_p3p </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>userid_p3p</b> <i>string</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_userid_module.html#userid_p3p">userid_p3p</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 41/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Directive assigns value for the header P3P, which will sent together with cookie. </p><br><i>Module: HttpUseridModule</i> <|start_filename|>resources/docs/directives/fastcgi_pass.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpFastcgiModule&amp;action=edit&amp;section=28" title="Edit section: fastcgi pass">edit</a>]</span> <span class="mw-headline" id="fastcgi_pass"> fastcgi_pass </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>fastcgi_pass</b> <i>address</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> location<br />if in location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_pass">fastcgi_pass</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 224/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Directive assigns the port or socket on which the FastCGI-server is listening. Port can be indicated by itself or as an address and port, for example: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"> <a href="/NginxHttpFcgiModule#fastcgi_pass"><span class="kw11">fastcgi_pass</span></a> localhost:<span class="nu0">9000</span><span class="sy0">;</span></pre> </div> </div><p>using a Unix domain socket: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"> <a href="/NginxHttpFcgiModule#fastcgi_pass"><span class="kw11">fastcgi_pass</span></a> unix:/tmp/fastcgi.socket<span class="sy0">;</span></pre> </div> </div><p>You may also use an upstream block. </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpUpstreamModule#upstream"><span class="kw4">upstream</span></a> backend <span class="br0">{</span> <a href="/NginxHttpCoreModule#server"><span class="kw3">server</span></a> localhost:<span class="nu0">1234</span><span class="sy0">;</span> <span class="br0">}</span> &nbsp; <a href="/NginxHttpFcgiModule#fastcgi_pass"><span class="kw11">fastcgi_pass</span></a> backend<span class="sy0">;</span></pre> </div> </div><br><i>Module: HttpFastcgiModule</i> <|start_filename|>resources/docs/directives/scgi_pass.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpScgiModule&amp;action=edit&amp;section=25" title="Edit section: scgi pass">edit</a>]</span> <span class="mw-headline" id="scgi_pass"> scgi_pass </span></h2><p><b>syntax:</b> <i>scgi_pass scgi-server</i> </p><p><b>default:</b> <i>none</i> </p><p><b>context:</b> <i>location, if in location</i> </p><p>Directive assigns the port or socket on which the SCGI-server is listening. Port can be indicated by itself or as an address and port, for example: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"> scgi_pass localhost:<span class="nu0">9000</span><span class="sy0">;</span></pre> </div> </div><p>using a Unix domain socket: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"> scgi_pass unix:/tmp/scgi.socket<span class="sy0">;</span></pre> </div> </div><p>You may also use an upstream block. </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpUpstreamModule#upstream"><span class="kw4">upstream</span></a> backend <span class="br0">{</span> <a href="/NginxHttpCoreModule#server"><span class="kw3">server</span></a> localhost:<span class="nu0">1234</span><span class="sy0">;</span> <span class="br0">}</span> &nbsp; scgi_pass backend<span class="sy0">;</span></pre> </div> </div><br><i>Module: HttpScgiModule</i> <|start_filename|>resources/docs/directives/proxy_intercept_errors.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpProxyModule&amp;action=edit&amp;section=27" title="Edit section: proxy intercept errors">edit</a>]</span> <span class="mw-headline" id="proxy_intercept_errors"> proxy_intercept_errors </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>proxy_intercept_errors</b> <code>on</code> | <code>off</code> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>off</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_intercept_errors">proxy_intercept_errors</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 202/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> This directive decides if nginx will intercept responses with HTTP status codes of 400 and higher. </p><p>By default all responses will be sent as-is from the proxied server. </p><p>If you set this to <code>on</code> then nginx will intercept status codes that are explicitly handled by an <code>error_page</code> directive. Responses with status codes that do not match an <code>error_page</code> directive will be sent as-is from the proxied server. </p><br><i>Module: HttpProxyModule</i> <|start_filename|>src/net/ishchenko/idea/nginx/psi/NginxVariableReference.java<|end_filename|> package net.ishchenko.idea.nginx.psi; import com.intellij.openapi.util.TextRange; import com.intellij.psi.*; import com.intellij.psi.util.PsiTreeUtil; import net.ishchenko.idea.nginx.NginxKeywordsManager; import net.ishchenko.idea.nginx.psi.NginxContext; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; public class NginxVariableReference extends PsiReferenceBase<PsiElement> implements PsiReference { private final String name; public NginxVariableReference(PsiNamedElement element, TextRange rangeInElement) { super(element, rangeInElement); name = element.getName(); } @Nullable @Override public PsiElement resolve() { PsiElement parent = PsiTreeUtil.getParentOfType(myElement, NginxContext.class); PsiElement source = null; while (source == null && parent != null && parent.getParent() != null) { source = findSource(parent); parent = PsiTreeUtil.getParentOfType(parent, NginxContext.class); } return source; } private PsiElement findSource(PsiElement parent) { Collection<PsiNamedElement> children = PsiTreeUtil.findChildrenOfType(parent, NginxInnerVariable.class); return children.stream() .filter(child -> child.getName() != null && child.getName().equals(name) && child.getParent().getParent() instanceof NginxDirective && NginxKeywordsManager.SET_DIRECTIVES.contains( ((NginxDirective)child.getParent().getParent()).getNameString())) .findFirst() .orElse(null); } @NotNull @Override public Object[] getVariants() { return new Object[0]; } } <|start_filename|>resources/docs/directives/daemon.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=CoreModule&amp;action=edit&amp;section=3" title="Edit section: daemon">edit</a>]</span> <span class="mw-headline" id="daemon"> daemon </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>daemon</b> <code>on</code> | <code>off</code> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>on</i></td> </tr> <tr> <td><b>Context:</b></td> <td> main</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/ngx_core_module.html#daemon">daemon</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 10/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#daemon"><span class="kw1">daemon</span></a> off<span class="sy0">;</span></pre> </div> </div><p>Do not use the <a href="#daemon">daemon</a> or <a href="#master_process">master_process</a> directives in a production mode; these options are used for development only. You can use <code>daemon off</code> safely in production mode with runit/daemontools, however you can't do a graceful upgrade. <code>master_process off</code> should never be used in production. </p><br><i>Module: CoreModule</i> <|start_filename|>resources/docs/directives/fastcgi_intercept_errors.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpFastcgiModule&amp;action=edit&amp;section=22" title="Edit section: fastcgi intercept errors">edit</a>]</span> <span class="mw-headline" id="fastcgi_intercept_errors"> fastcgi_intercept_errors </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>fastcgi_intercept_errors</b> <code>on</code> | <code>off</code> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>off</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_intercept_errors">fastcgi_intercept_errors</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 170/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> This directive determines whether or not to transfer 4xx and 5xx errors back to the client or to allow Nginx to answer with directive error_page. </p><p>Note: You need to explicitly define the error_page handler for this for it to be useful. As Igor says, &quot;nginx does not intercept an error if there is no custom handler for it it does not show its default pages. This allows to intercept some errors, while passing others as are.&quot; </p><br><i>Module: HttpFastcgiModule</i> <|start_filename|>resources/docs/directives/server_names_hash_max_size.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpCoreModule&amp;action=edit&amp;section=65" title="Edit section: server names hash max size">edit</a>]</span> <span class="mw-headline" id="server_names_hash_max_size"> server_names_hash_max_size </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>server_names_hash_max_size</b> <i>size</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>512</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_core_module.html#server_names_hash_max_size">server_names_hash_max_size</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 558/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> The maximum size of the server name hash tables. For more detail see the description of tuning the hash tables in <a href="/Optimizations" title="Optimizations">Nginx Optimizations</a>. </p><br><i>Module: HttpCoreModule</i> <|start_filename|>src/net/ishchenko/idea/nginx/NginxWordsScanner.java<|end_filename|> package net.ishchenko.idea.nginx; import com.intellij.lang.cacheBuilder.DefaultWordsScanner; import com.intellij.psi.tree.TokenSet; import net.ishchenko.idea.nginx.lexer.NginxElementTypes; import net.ishchenko.idea.nginx.lexer.NginxParsingLexer; public class NginxWordsScanner extends DefaultWordsScanner { public NginxWordsScanner() { super(new NginxParsingLexer(), TokenSet.create(NginxElementTypes.INNER_VARIABLE), NginxElementTypes.COMMENTS, TokenSet.create(NginxElementTypes.DIRECTIVE) ); } } <|start_filename|>resources/docs/directives/Installation.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpAdditionModule&amp;action=edit&amp;section=2" title="Edit section: Installation">edit</a>]</span> <span class="mw-headline" id="Installation"> Installation </span></h2><p>By default the module is not built, it is necessary to enable its build with </p><pre> ./configure --with-http_addition_module </pre><p>at compilation time. </p><p>Example: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#location"><span class="kw3">location</span></a> / <span class="br0">{</span> <a href="/NginxHttpAdditionModule#add_before_body"><span class="kw25">add_before_body</span></a> /before_action<span class="sy0">;</span> <a href="/NginxHttpAdditionModule#add_after_body"><span class="kw25">add_after_body</span></a> /after_action<span class="sy0">;</span> <span class="br0">}</span></pre> </div> </div><br><i>Module: HttpAdditionModule</i> <|start_filename|>resources/docs/directives/directio.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpCoreModule&amp;action=edit&amp;section=16" title="Edit section: directio">edit</a>]</span> <span class="mw-headline" id="directio"> directio </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>directio</b> <i>size</i> | <code>off</code> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>off</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Appeared in:</b></td> <td> 0.7.7</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_core_module.html#directio">directio</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 122/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> The directive enables use of flags O_DIRECT (FreeBSD, Linux), F_NOCACHE (Mac OS X) or directio() function (Solaris) for reading files with size greater than specified. This directive disables use of <a href="/HttpCoreModule#sendfile" title="HttpCoreModule">sendfile</a> for this request. This directive may be useful for big files: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"> directio 4m<span class="sy0">;</span></pre> </div> </div><br><i>Module: HttpCoreModule</i> <|start_filename|>resources/docs/directives/proxy_set_header.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpProxyModule&amp;action=edit&amp;section=42" title="Edit section: proxy set header">edit</a>]</span> <span class="mw-headline" id="proxy_set_header"> proxy_set_header </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>proxy_set_header</b> <i>field</i> <i>value</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>Host $proxy_host</i><br /><i>Connection close</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_set_header">proxy_set_header</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 328/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> This directive allows to redefine and to add some request header lines which will be transferred to the proxied server. </p><p>As the value it is possible to use a text, variables and their combination. </p><p><code>proxy_set_header</code> directives issued at higher levels are only inherited when no <code>proxy_set_header</code> directives have been issued at a given level. </p><p>By default only two lines will be redefined: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpProxyModule#proxy_set_header"><span class="kw21">proxy_set_header</span></a> Host <span class="re0">$proxy_host</span><span class="sy0">;</span> <a href="/NginxHttpProxyModule#proxy_set_header"><span class="kw21">proxy_set_header</span></a> Connection Close<span class="sy0">;</span></pre> </div> </div><p>The unchanged request-header &quot;Host&quot; can be transmitted like this: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpProxyModule#proxy_set_header"><span class="kw21">proxy_set_header</span></a> Host <span class="re0">$http_host</span><span class="sy0">;</span></pre> </div> </div><p>However, if this line is absent from the client request, then nothing will be transferred. </p><p>In this case it is better to use variable $host, it's value is equal to the name of server in the request-header &quot;Host&quot; or to the basic name of server, if there is no line: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpProxyModule#proxy_set_header"><span class="kw21">proxy_set_header</span></a> Host <span class="re0">$host</span><span class="sy0">;</span></pre> </div> </div><p>Furthermore, it is possible to transmit the name of server together with the port of the proxied server: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpProxyModule#proxy_set_header"><span class="kw21">proxy_set_header</span></a> Host <span class="re0">$host</span>:<span class="re0">$proxy_port</span><span class="sy0">;</span></pre> </div> </div><p>If value is empty string, than header will not be sent to upstream. For example this setting can be used to disable gzip compression on upstream: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpProxyModule#proxy_set_header"><span class="kw21">proxy_set_header</span></a> Accept-Encoding <span class="st0">&quot;&quot;</span><span class="sy0">;</span></pre> </div> </div><br><i>Module: HttpProxyModule</i> <|start_filename|>resources/docs/directives/xslt_stylesheet.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpXsltModule&amp;action=edit&amp;section=6" title="Edit section: xslt stylesheet">edit</a>]</span> <span class="mw-headline" id="xslt_stylesheet"> xslt_stylesheet </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>xslt_stylesheet</b> <i>stylesheet</i> [ <i>parameter</i> = <i>value</i> ...]</td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_xslt_module.html#xslt_stylesheet">xslt_stylesheet</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 40/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Specifies the XSLT template with its parameters. Template is compiled at the stage of configuration. The parameters are assigned as shown: </p><pre> param=value </pre><p>You can specify parameters either one per line, or separate multiple parameters with colon (“: ”) If the parameter itself contains the character “:”, escape it as “%3A”. Furthermore, libxslt requires that string parameters should be quoted by the single or dual quotation marks if they contain non-alphanumeric characters, for example: </p><pre> param1='http%3A//www.example.<EMAIL>': param2=value2 </pre><p>It's possible to use variables as parameters, for example, the entire line of the parameters can be substituted with one variable: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"> <a href="/NginxHttpCoreModule#location"><span class="kw3">location</span></a> / <span class="br0">{</span> <a href="/NginxHttpXsltModule#xslt_stylesheet"><span class="kw36">xslt_stylesheet</span></a> /site/xslt/one.xslt <span class="re0">$arg_xslt_params</span> param1<span class="sy0">=</span><span class="st0">'$value1'</span>: param2<span class="sy0">=</span>value2 param3<span class="sy0">=</span>value3<span class="sy0">;</span> <span class="br0">}</span></pre> </div> </div><p>It is possible to specify several templates, in which case they would be chained together in the order of their declaration. </p><br><i>Module: HttpXsltModule</i> <|start_filename|>resources/docs/directives/allow.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpAccessModule&amp;action=edit&amp;section=3" title="Edit section: allow">edit</a>]</span> <span class="mw-headline" id="allow"> allow </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>allow</b> <i>address</i> | <i>CIDR</i> | <code>all</code> </td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location<br />limit_except</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_access_module.html#allow">allow</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 16/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Directive grants access for the network or addresses indicated. </p><br><i>Module: HttpAccessModule</i> <|start_filename|>src/net/ishchenko/idea/nginx/NginxBraceMatcher.java<|end_filename|> /* * Copyright 2009 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.ishchenko.idea.nginx; import com.intellij.lang.BracePair; import com.intellij.lang.PairedBraceMatcher; import com.intellij.psi.PsiFile; import com.intellij.psi.tree.IElementType; import net.ishchenko.idea.nginx.lexer.NginxElementTypes; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Created by IntelliJ IDEA. * User: Max * Date: 13.07.2009 * Time: 20:37:13 */ public class NginxBraceMatcher implements PairedBraceMatcher { public static final BracePair[] BRACES = new BracePair[]{new BracePair(NginxElementTypes.OPENING_BRACE, NginxElementTypes.CLOSING_BRACE, true)}; public int getCodeConstructStart(PsiFile file, int openingBraceOffset) { return 0; } public BracePair[] getPairs() { return BRACES; } public boolean isPairedBracesAllowedBeforeType(@NotNull IElementType lbraceType, @Nullable IElementType contextType) { return true; } } <|start_filename|>resources/docs/directives/error_page.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpCoreModule&amp;action=edit&amp;section=19" title="Edit section: error page">edit</a>]</span> <span class="mw-headline" id="error_page"> error_page </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>error_page</b> <i>code</i> ... [ <code>=</code> [ <i>response</i> ]] <i>uri</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location<br />if in location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_core_module.html#error_page">error_page</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 146/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> The directive specifies the URI that will be shown for the errors indicated. </p><p>Example: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#error_page"><span class="kw3">error_page</span></a> <span class="nu0">404</span> /<span class="nu0">404</span>.html<span class="sy0">;</span> <a href="/NginxHttpCoreModule#error_page"><span class="kw3">error_page</span></a> <span class="nu0">502</span> <span class="nu0">503</span> <span class="nu0">504</span> /50x.html<span class="sy0">;</span> <a href="/NginxHttpCoreModule#error_page"><span class="kw3">error_page</span></a> <span class="nu0">403</span> <a href="/NginxHttpCoreModule#http"><span class="kw3">http</span></a>://example.com/forbidden.html<span class="sy0">;</span> <a href="/NginxHttpCoreModule#error_page"><span class="kw3">error_page</span></a> <span class="nu0">404</span> <span class="sy0">=</span> <span class="re0">@fetch</span><span class="sy0">;</span></pre> </div> </div><p>Furthermore, it is possible to change the status code of the answer to another, for example: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#error_page"><span class="kw3">error_page</span></a> <span class="nu0">404</span> <span class="sy0">=</span><span class="nu0">200</span> /empty.gif<span class="sy0">;</span> <a href="/NginxHttpCoreModule#error_page"><span class="kw3">error_page</span></a> <span class="nu0">404</span> <span class="sy0">=</span><span class="nu0">403</span> /forbidden.gif<span class="sy0">;</span></pre> </div> </div><p>Additionally you can have your designated error handler determine the returned status code by using = without specifying a status code. </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#error_page"><span class="kw3">error_page</span></a> <span class="nu0">404</span> <span class="sy0">=</span> /<span class="nu0">404</span>.php<span class="sy0">;</span></pre> </div> </div><p>If there is no need to change URI during redirection it is possible to redirect processing of error pages into a named location: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#location"><span class="kw3">location</span></a> / <span class="br0">(</span> <a href="/NginxHttpCoreModule#error_page"><span class="kw3">error_page</span></a> <span class="nu0">404</span> <span class="re0">@fallback</span><span class="sy0">;</span> <span class="br0">)</span> &nbsp; <a href="/NginxHttpCoreModule#location"><span class="kw3">location</span></a> <span class="re0">@fallback</span> <span class="br0">(</span> <a href="/NginxHttpProxyModule#proxy_pass"><span class="kw21">proxy_pass</span></a> <a href="/NginxHttpCoreModule#http"><span class="kw3">http</span></a>://backend<span class="sy0">;</span> <span class="br0">)</span></pre> </div> </div><p>If you want to use error_page for proxy (upstream) status codes, please see <a rel="nofollow" class="external free" href="http://wiki.nginx.org/HttpProxyModule#proxy_intercept_errors">http://wiki.nginx.org/HttpProxyModule#proxy_intercept_errors</a> </p><br><i>Module: HttpCoreModule</i> <|start_filename|>resources/docs/directives/server_name.html<|end_filename|> <h3>Directive can have multiple meanings. Each variant is separated with horizontal line</h3><hr><h2><span class="editsection">[<a href="/index.php?title=HttpCoreModule&amp;action=edit&amp;section=63" title="Edit section: server name">edit</a>]</span> <span class="mw-headline" id="server_name"> server_name </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>server_name</b> <i>name</i> ...</td> </tr> <tr> <td><b>Default:</b></td> <td> <i>&quot;&quot;</i></td> </tr> <tr> <td><b>Context:</b></td> <td> server</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_core_module.html#server_name">server_name</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 517/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> This directive performs two actions: </p><ul> <li> Compares the <code>Host</code> header of the incoming HTTP request against the <a href="#server">server { ... }</a> blocks in the Nginx configuration files and selects the first one that matches. This is how <b>virtual servers</b> are defined. Server names are processed in the following order: </li> </ul><ol> <li> full, static names </li> <li> names with a wildcard at the start of the name — *.example.com </li> <li> names with a wildcard at the end of the name — www.example.* </li> <li> names with regular expressions </li> </ol><dl> <dd> If there is no match, a <a href="#server">server { ... }</a> block in the configuration file will be used based on the following order: </dd> </dl><ol> <li> the server block with a matching <code>listen</code> directive marked as <code>[default|default_server]</code> </li> <li> the first server block with a matching <code>listen</code> directive (or implicit <code>listen 80;</code>) </li> </ol><ul> <li> Sets the server name that will be used in HTTP redirects if <a href="#server_name_in_redirect">server_name_in_redirect</a> is set. </li> </ul><p>Example: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#server"><span class="kw3">server</span></a> <span class="br0">{</span> <a href="/NginxHttpCoreModule#server_name"><span class="kw3">server_name</span></a> example.com www.example.com<span class="sy0">;</span> <span class="br0">}</span></pre> </div> </div><p>The first name becomes the basic name of server. By default the name of the machine (hostname) is used. </p><p>It is possible to use &quot;*&quot; for replacing the first or the last part of the name: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#server"><span class="kw3">server</span></a> <span class="br0">{</span> <a href="/NginxHttpCoreModule#server_name"><span class="kw3">server_name</span></a> example.com *.example.com www.example.*<span class="sy0">;</span> <span class="br0">}</span></pre> </div> </div><p>The first two of the above names (example.com and *.example.com) can be combined into one: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#server"><span class="kw3">server</span></a> <span class="br0">{</span> <a href="/NginxHttpCoreModule#server_name"><span class="kw3">server_name</span></a> .example.com<span class="sy0">;</span> <span class="br0">}</span></pre> </div> </div><p>It is also possible to use regular expressions in server names, prepending the name with a tilde &quot;~&quot; like so: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#server"><span class="kw3">server</span></a> <span class="br0">{</span> <a href="/NginxHttpCoreModule#server_name"><span class="kw3">server_name</span></a> www.example.com <span class="sy0">~</span>^www\d+\.example\.com$<span class="sy0">;</span> <span class="br0">}</span></pre> </div> </div><p>Since nginx 0.7.12, an empty server name is supported to catch the requests without &quot;Host&quot; header, please note that most browsers will always send a Host header, if accessed by IP the Host header will contain the IP. To specify a catch-all block please see the default_server flag of the listen directive. </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#server"><span class="kw3">server</span></a> <span class="br0">{</span> <a href="/NginxHttpCoreModule#server_name"><span class="kw3">server_name</span></a> <span class="st0">&quot;&quot;</span><span class="sy0">;</span> <span class="br0">}</span></pre> </div> </div><p>Since nginx 0.8.25 named captures can be used in server_name: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#server"><span class="kw3">server</span></a> <span class="br0">{</span> <a href="/NginxHttpCoreModule#server_name"><span class="kw3">server_name</span></a> <span class="sy0">~</span>^<span class="br0">(</span>www\.<span class="br0">)</span>?<span class="br0">(</span>?<span class="re4">&lt;domain&gt;</span>.+<span class="br0">)</span>$<span class="sy0">;</span> <a href="/NginxHttpCoreModule#root"><span class="kw3">root</span></a> /sites/<span class="re0">$domain</span><span class="sy0">;</span> <span class="br0">}</span></pre> </div> </div><p>and multiple name captures: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#server"><span class="kw3">server</span></a> <span class="br0">{</span> <a href="/NginxHttpCoreModule#server_name"><span class="kw3">server_name</span></a> <span class="sy0">~</span>^<span class="br0">(</span>?<span class="re4">&lt;subdomain&gt;</span>.+?<span class="br0">)</span>\.<span class="br0">(</span>?<span class="re4">&lt;domain&gt;</span>.+<span class="br0">)</span>$<span class="sy0">;</span> <a href="/NginxHttpCoreModule#root"><span class="kw3">root</span></a> /sites/<span class="re0">$domain</span>/<span class="re0">$subdomain</span><span class="sy0">;</span> <span class="br0">}</span></pre> </div> </div><p>Some older versions of PCRE may have issues with this syntax. If any problems arise try this following syntax: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#server"><span class="kw3">server</span></a> <span class="br0">{</span> <a href="/NginxHttpCoreModule#server_name"><span class="kw3">server_name</span></a> <span class="sy0">~</span>^<span class="br0">(</span>www\.<span class="br0">)</span>?<span class="br0">(</span>?P<span class="re4">&lt;domain&gt;</span>.+<span class="br0">)</span>$<span class="sy0">;</span> <a href="/NginxHttpCoreModule#root"><span class="kw3">root</span></a> /sites/<span class="re0">$domain</span><span class="sy0">;</span> <span class="br0">}</span></pre> </div> </div><p>Since nginx 0.9.4, <a href="#.24hostname">$hostname</a> can be used as a server_name argument: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#server"><span class="kw3">server</span></a> <span class="br0">{</span> <a href="/NginxHttpCoreModule#server_name"><span class="kw3">server_name</span></a> <span class="re0">$hostname</span><span class="sy0">;</span> <span class="br0">}</span></pre> </div> </div><br><i>Module: HttpCoreModule</i><hr><h2><span class="editsection">[<a href="/index.php?title=MailCoreModule&amp;action=edit&amp;section=12" title="Edit section: server name">edit</a>]</span> <span class="mw-headline" id="server_name"> server_name </span></h2><p><b>syntax:</b> <i>server_name name</i> <i><b>fqdn_server_host</b></i> </p><p><b>default:</b> <i>The name of the host, obtained through gethostname()</i> </p><p><b>context:</b> <i>mail, server</i> </p><p>Directive assigns the names of virtual server, for example: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#server"><span class="kw3">server</span></a> <span class="br0">{</span> <a href="/NginxHttpCoreModule#server_name"><span class="kw3">server_name</span></a> example.com www.example.com<span class="sy0">;</span> <span class="br0">}</span></pre> </div> </div><p>The first name becomes the basic name of server. By default the name of the machine (hostname) is used. It is possible to use &quot;*&quot; for replacing the first part of the name: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#server"><span class="kw3">server</span></a> <span class="br0">{</span> <a href="/NginxHttpCoreModule#server_name"><span class="kw3">server_name</span></a> example.com *.example.com<span class="sy0">;</span> <span class="br0">}</span></pre> </div> </div><p>Two of the given name of the above example can be combined into one: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#server"><span class="kw3">server</span></a> <span class="br0">{</span> <a href="/NginxHttpCoreModule#server_name"><span class="kw3">server_name</span></a> .example.com<span class="sy0">;</span> <span class="br0">}</span></pre> </div> </div><p>The basic name of server is used in an HTTP redirects, if no a &quot;Host&quot; header was in client request or that header does not match any assigned server_name. You can also use just &quot;*&quot; to force Nginx to use the &quot;Host&quot; header in the HTTP redirect (note that &quot;*&quot; cannot be used as the first name, but you can use a dummy name such as &quot;_&quot; instead): </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#server"><span class="kw3">server</span></a> <span class="br0">{</span> <a href="/NginxHttpCoreModule#server_name"><span class="kw3">server_name</span></a> example.com *<span class="sy0">;</span> <span class="br0">}</span> <a href="/NginxHttpCoreModule#server"><span class="kw3">server</span></a> <span class="br0">{</span> <a href="/NginxHttpCoreModule#server_name"><span class="kw3">server_name</span></a> _ *<span class="sy0">;</span> <span class="br0">}</span></pre> </div> </div><hr /><br><i>Module: MailCoreModule</i> <|start_filename|>resources/docs/directives/proxy_ssl_session_reuse.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpProxyModule&amp;action=edit&amp;section=43" title="Edit section: proxy ssl session reuse">edit</a>]</span> <span class="mw-headline" id="proxy_ssl_session_reuse"> proxy_ssl_session_reuse </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>proxy_ssl_session_reuse</b> <code>on</code> | <code>off</code> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>on</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_ssl_session_reuse">proxy_ssl_session_reuse</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 350/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Attempt to reuse ssl session when connecting to upstream via https. </p><br><i>Module: HttpProxyModule</i> <|start_filename|>src/net/ishchenko/idea/nginx/lexer/NginxElementTypes.java<|end_filename|> /* * Copyright 2009 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.ishchenko.idea.nginx.lexer; import com.intellij.lang.Language; import com.intellij.psi.TokenType; import com.intellij.psi.tree.IElementType; import com.intellij.psi.tree.IFileElementType; import com.intellij.psi.tree.TokenSet; import net.ishchenko.idea.nginx.NginxLanguage; /** * Created by IntelliJ IDEA. * User: Max * Date: 06.07.2009 * Time: 15:49:41 */ public interface NginxElementTypes { IFileElementType FILE = new IFileElementType(Language.findInstance(NginxLanguage.class)); IElementType BAD_CHARACTER = TokenType.BAD_CHARACTER; IElementType WHITE_SPACE = TokenType.WHITE_SPACE; IElementType COMMENT = new NginxElementType("COMMENT"); //non-lexed types IElementType DIRECTIVE = new NginxElementType("DIRECTIVE"); IElementType CONTEXT = new NginxElementType("CONTEXT"); IElementType COMPLEX_VALUE = new NginxElementType("COMPLEX_VALUE"); //lexed types IElementType CONTEXT_NAME = new NginxElementType("CONTEXT_NAME"); IElementType DIRECTIVE_NAME = new NginxElementType("DIRECTIVE_NAME"); IElementType DIRECTIVE_VALUE = new NginxElementType("DIRECTIVE_VALUE"); IElementType DIRECTIVE_STRING_VALUE = new NginxElementType("DIRECTIVE_STRING_VALUE"); IElementType VALUE_WHITE_SPACE = new NginxElementType("VALUE_WHITE_SPACE"); IElementType INNER_VARIABLE = new NginxElementType("INNER_VARIABLE"); IElementType OPENING_BRACE = new NginxElementType("OPENING_BRACE"); IElementType CLOSING_BRACE = new NginxElementType("CLOSING_BRACE"); IElementType SEMICOLON = new NginxElementType("SEMICOLON"); IElementType LUA_CONTEXT = new NginxElementType("LUA_CONTEXT"); TokenSet WHITE_SPACES = TokenSet.create(WHITE_SPACE); TokenSet COMMENTS = TokenSet.create(COMMENT); TokenSet STRINGS = TokenSet.create(DIRECTIVE_STRING_VALUE); } <|start_filename|>src/net/ishchenko/idea/nginx/injection/LuaTextEscaper.java<|end_filename|> package net.ishchenko.idea.nginx.injection; import com.intellij.openapi.util.TextRange; import com.intellij.psi.LiteralTextEscaper; import net.ishchenko.idea.nginx.psi.NginxLuaContext; import org.jetbrains.annotations.NotNull; public class LuaTextEscaper extends LiteralTextEscaper<NginxLuaContext> { public LuaTextEscaper(@NotNull NginxLuaContext host) { super(host); } @Override public boolean decode(@NotNull TextRange rangeInsideHost, @NotNull StringBuilder outChars) { outChars.append(myHost.getText(), rangeInsideHost.getStartOffset(), rangeInsideHost.getEndOffset()); return true; } @Override public int getOffsetInHost(int offsetInDecoded, @NotNull TextRange rangeInsideHost) { int j = offsetInDecoded + rangeInsideHost.getStartOffset(); if (j < rangeInsideHost.getStartOffset()) { j = rangeInsideHost.getStartOffset(); } if (j > rangeInsideHost.getEndOffset()) { j = rangeInsideHost.getEndOffset(); } return j; } @Override public boolean isOneLine() { return false; } } <|start_filename|>resources/docs/directives/server_name_in_redirect.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpCoreModule&amp;action=edit&amp;section=64" title="Edit section: server name in redirect">edit</a>]</span> <span class="mw-headline" id="server_name_in_redirect"> server_name_in_redirect </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>server_name_in_redirect</b> <code>on</code> | <code>off</code> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>off</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_core_module.html#server_name_in_redirect">server_name_in_redirect</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 551/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> If <code>server_name_in_redirect</code> is on, then Nginx will use the first value of the <a href="#server_name">server_name</a> directive for redirects. If <code>server_name_in_redirect</code> is off, then nginx will use the requested <code>Host</code> header. </p><p>Note: for Location headers coming from an upstream proxy (via proxy_pass for example) this may not be the only directive you need. In fact, it seems to be ignored a lot of the time. If you are seeing the upstream's server name come through and not be rewritten, you will need to use <a href="/NginxHttpProxyModule#proxy_redirect" title="NginxHttpProxyModule" class="mw-redirect">proxy_redirect</a> to rewrite the upstream's provided hostname to what you want. Something like <code>proxy_redirect <a rel="nofollow" class="external free" href="http://some.upstream.url/">http://some.upstream.url/</a> /</code> - you will want to rewrite it to a / relative path. </p><br><i>Module: HttpCoreModule</i> <|start_filename|>resources/docs/directives/fastcgi_ignore_headers.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpFastcgiModule&amp;action=edit&amp;section=20" title="Edit section: fastcgi ignore headers">edit</a>]</span> <span class="mw-headline" id="fastcgi_ignore_headers"> fastcgi_ignore_headers </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>fastcgi_ignore_headers</b> <i>field</i> ...</td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_ignore_headers">fastcgi_ignore_headers</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 153/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> This directive forbids processing of the named headers from the FastCGI-server reply. It is possible to specify headers like &quot;X-Accel-Redirect&quot;, &quot;X-Accel-Expires&quot;, &quot;Expires&quot; or &quot;Cache-Control&quot;. </p><br><i>Module: HttpFastcgiModule</i> <|start_filename|>resources/docs/directives/ssl_session_timeout.html<|end_filename|> <h3>Directive can have multiple meanings. Each variant is separated with horizontal line</h3><hr><h2><span class="editsection">[<a href="/index.php?title=HttpSslModule&amp;action=edit&amp;section=17" title="Edit section: ssl session timeout">edit</a>]</span> <span class="mw-headline" id="ssl_session_timeout"> ssl_session_timeout </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>ssl_session_timeout</b> <i>time</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>5m</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_ssl_module.html#ssl_session_timeout">ssl_session_timeout</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 141/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> This directive defines the maximum time during which the client can re-use the previously negotiated cryptographic parameters of the secure session that is stored in the SSL cache. </p><br><i>Module: HttpSslModule</i><hr><h2><span class="editsection">[<a href="/index.php?title=MailSslModule&amp;action=edit&amp;section=10" title="Edit section: ssl session timeout">edit</a>]</span> <span class="mw-headline" id="ssl_session_timeout"> ssl_session_timeout </span></h2><p><b>syntax:</b> <i>ssl_session_timeout</i> <i><b>time</b></i> </p><p><b>default:</b> <i>5m</i> </p><p><b>context:</b> <i>mail, server</i> </p><p>Assigns the time during which the client can repeatedly use the parameters of the session, which is stored in the cache. </p><br><i>Module: MailSslModule</i> <|start_filename|>resources/docs/directives/large_client_header_buffers.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpCoreModule&amp;action=edit&amp;section=26" title="Edit section: large client header buffers">edit</a>]</span> <span class="mw-headline" id="large_client_header_buffers"> large_client_header_buffers </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>large_client_header_buffers</b> <i>number</i> <i>size</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>4 8k</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_core_module.html#large_client_header_buffers">large_client_header_buffers</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 210/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Directive assigns the maximum number and size of buffers for large headers to read from client request. </p><p>The request line can not be bigger than the size of one buffer, if the client send a bigger header nginx returns error &quot;Request URI too large&quot; (414). </p><p>The longest header line of request also must be not more than the size of one buffer, otherwise the client get the error &quot;Bad request&quot; (400). </p><p>Buffers are separated only as needed. </p><p>By default the size of one buffer is 8192 bytes. In the old nginx, this is equal to the size of page, depending on platform this either 4K or 8K, if at the end of working request connection converts to state keep-alive, then these buffers are freed. </p><br><i>Module: HttpCoreModule</i> <|start_filename|>resources/docs/directives/worker_cpu_affinity.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=CoreModule&amp;action=edit&amp;section=15" title="Edit section: worker cpu affinity">edit</a>]</span> <span class="mw-headline" id="worker_cpu_affinity"> worker_cpu_affinity </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>worker_cpu_affinity</b> <i>cpumask</i> ...</td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> main</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/ngx_core_module.html#worker_cpu_affinity">worker_cpu_affinity</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 121/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Linux only. </p><p>With this option you can bind the worker process to a CPU, it calls sched_setaffinity(). </p><p>For example, </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#worker_processes"><span class="kw1">worker_processes</span></a> <span class="nu0">4</span><span class="sy0">;</span> <a href="/NginxHttpCoreModule#worker_cpu_affinity"><span class="kw1">worker_cpu_affinity</span></a> 0001 0010 0100 <span class="nu0">1000</span><span class="sy0">;</span></pre> </div> </div><p>Bind each worker process to one CPU only. </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#worker_processes"><span class="kw1">worker_processes</span></a> <span class="nu0">2</span><span class="sy0">;</span> <a href="/NginxHttpCoreModule#worker_cpu_affinity"><span class="kw1">worker_cpu_affinity</span></a> 0101 <span class="nu0">1010</span><span class="sy0">;</span></pre> </div> </div><p>Bind the first worker to CPU0/CPU2, bind the second worker to CPU1/CPU3. This is suitable for HTT. </p><br><i>Module: CoreModule</i> <|start_filename|>resources/docs/directives/xml_entities.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpXsltModule&amp;action=edit&amp;section=3" title="Edit section: xml entities">edit</a>]</span> <span class="mw-headline" id="xml_entities"> xml_entities </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>xml_entities</b> <i>path</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_xslt_module.html#xml_entities">xml_entities</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 16/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Specifies the DTD file which describes symbolic elements (xml entities). This file is compiled at the stage of configuration. For technical reasons it's not possible to specify entities in the XML being processed, therefore they are ignored, but this specially assigned file is used instead. In this file it is not necessary to describe structure of processed XML, it is sufficient only to declare necessary symbolic elements, for example: </p><pre> &lt;! ENTITY of nbsp “&nbsp; “&gt; </pre><br><i>Module: HttpXsltModule</i> <|start_filename|>src/net/ishchenko/idea/nginx/NginxFindUsagesProvider.java<|end_filename|> package net.ishchenko.idea.nginx; import com.intellij.lang.cacheBuilder.WordsScanner; import com.intellij.lang.findUsages.FindUsagesProvider; import com.intellij.psi.PsiElement; import net.ishchenko.idea.nginx.psi.NginxInnerVariable; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class NginxFindUsagesProvider implements FindUsagesProvider { @Nullable @Override public WordsScanner getWordsScanner() { return new NginxWordsScanner(); } @Override public boolean canFindUsagesFor(@NotNull PsiElement psiElement) { return psiElement instanceof NginxInnerVariable; } @Nullable @Override public String getHelpId(@NotNull PsiElement psiElement) { return null; } @NotNull @Override public String getType(@NotNull PsiElement psiElement) { if (psiElement instanceof NginxInnerVariable) return "variable"; return ""; } @NotNull @Override public String getDescriptiveName(@NotNull PsiElement psiElement) { if (psiElement instanceof NginxInnerVariable) { NginxInnerVariable var = (NginxInnerVariable)psiElement; return var.getName(); } return ""; } @NotNull @Override public String getNodeText(@NotNull PsiElement psiElement, boolean b) { if (psiElement instanceof NginxInnerVariable) { NginxInnerVariable var = (NginxInnerVariable)psiElement; return var.getName(); } return ""; } } <|start_filename|>resources/docs/directives/geo.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpGeoModule&amp;action=edit&amp;section=3" title="Edit section: geo">edit</a>]</span> <span class="mw-headline" id="geo"> geo </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>geo</b> [ <i>$address</i> ] <i>$variable</i> { ... }</td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> http</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_geo_module.html#geo">geo</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 13/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> This directive describes the dependency of the value of the defined variable on the client's IP address. By default, the IP address used for doing the lookup is $remote_addr, but since version 0.7.27 it is possible to specify an another variable. </p><p>Note that in the case of an invalid IP address, the value <b>255.255.255.255</b> is used. </p><p>Here we're using <code>$arg_remote_addr</code>: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"> <a href="/NginxHttpGeoModule#geo"><span class="kw12">geo</span></a> <span class="re0">$arg_remote_addr</span> <span class="re0">$geo</span> <span class="br0">{</span> <span class="br0">(</span>...<span class="br0">)</span> <span class="br0">}</span></pre> </div> </div><p>IP addresses are enumerated in CIDR notation. There are four parameters for this directive: </p><ul> <li> delete – deletes the specified network (0.7.23). </li> <li> default - the value of the defined variable, if the client address does not correspond to any of the enumerated addresses in the directive clauses. Any IP address not matching the enumerated IP adresses is matched by this clause that sets the value of the defined variable. </li> <li> include - specifies a file mapping addresses to values of the defined variable. </li> </ul><p>Multiple files can be included. </p><ul> <li> proxy - specifies the address of a proxy server (requires Nginx version ≥ 0.8.7). NEED MORE DESCRIPTION... </li> <li> ranges – specifies that the IP addresses enumerated are in the form of ranges (requires Nginx version ≥ 0.7.23) instead of CIDR notation. This directive must <b>precede</b> all other . </li> </ul><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"> <a href="/NginxHttpGeoModule#geo"><span class="kw12">geo</span></a> <span class="re0">$country</span> <span class="br0">{</span> default no<span class="sy0">;</span> <span class="co1"># Sets the default value (client doesn't match any of the enumerated IP addresses) to &quot;no&quot;</span> <a href="/NginxHttpCoreModule#include"><span class="kw1">include</span></a> conf/<a href="/NginxHttpGeoModule#geo"><span class="kw12">geo</span></a>.conf<span class="sy0">;</span> 127.0.0.0/<span class="nu0">24</span> us<span class="sy0">;</span> 127.0.0.1/<span class="nu0">32</span> ru<span class="sy0">;</span> 10.1.0.0/<span class="nu0">16</span> ru<span class="sy0">;</span> 192.168.1.0/<span class="nu0">24</span> uk<span class="sy0">;</span> <span class="br0">}</span></pre> </div> </div><p>In the file conf/geo.conf: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"> 10.2.0.0/<span class="nu0">16</span> ru<span class="sy0">;</span> 192.168.2.0/<span class="nu0">24</span> ru<span class="sy0">;</span></pre> </div> </div><p>The value will be the the one with maximum agreement. For example, the IP address 127.0.0.1 will get the value &quot;ru&quot;, but not &quot;us&quot;. </p><p>Example with ranges: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"> <a href="/NginxHttpGeoModule#geo"><span class="kw12">geo</span></a> <span class="re0">$country</span> <span class="br0">{</span> ranges<span class="sy0">;</span> default no<span class="sy0">;</span> <span class="co1"># note that ranges precedes all other directives</span> 127.0.0.0-127.0.0.0 us<span class="sy0">;</span> 127.0.0.1-127.0.0.1 ru<span class="sy0">;</span> 127.0.0.1-127.0.0.255 us<span class="sy0">;</span> 10.1.0.0-10.1.255.255 ru<span class="sy0">;</span> 192.168.1.0-192.168.1.255 uk<span class="sy0">;</span> <span class="br0">}</span></pre> </div> </div><h1><span class="editsection">[<a href="/index.php?title=HttpGeoModule&amp;action=edit&amp;section=4" title="Edit section: References">edit</a>]</span> <span class="mw-headline" id="References"> References </span></h1><ul> <li> <a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_geo_module.html">Original Documentation</a> </li> <li> <a href="/HWLoadbalancerCheckErrors" title="HWLoadbalancerCheckErrors">HWLoadbalancerCheckErrors</a> </li> <li> <a rel="nofollow" class="external text" href="http://www.ruby-forum.com/topic/125810">Creating geo.conf From MaxMind GeoIP Country Database</a> </li> </ul><br><i>Module: HttpGeoModule</i> <|start_filename|>resources/docs/directives/memcached_buffer_size.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpMemcachedModule&amp;action=edit&amp;section=7" title="Edit section: memcached buffer size">edit</a>]</span> <span class="mw-headline" id="memcached_buffer_size"> memcached_buffer_size </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>memcached_buffer_size</b> <i>size</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>4k|8k</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_memcached_module.html#memcached_buffer_size">memcached_buffer_size</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 41/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> The recv/send buffer size, in bytes. </p><br><i>Module: HttpMemcachedModule</i> <|start_filename|>resources/docs/directives/proxy_cache_bypass.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpProxyModule&amp;action=edit&amp;section=9" title="Edit section: proxy cache bypass">edit</a>]</span> <span class="mw-headline" id="proxy_cache_bypass"> proxy_cache_bypass </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>proxy_cache_bypass</b> <i>string</i> ...</td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_cache_bypass">proxy_cache_bypass</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 52/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> The directive specifies the conditions under which the answer will not be taken from the cache. If at least one of a string variable is not empty and not equal to &quot;0&quot;, the answer is not taken from the cache: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"> proxy_cache_bypass <span class="re0">$cookie_nocache</span> <span class="re0">$arg_nocache</span> <span class="re0">$arg_comment</span><span class="sy0">;</span> proxy_cache_bypass <span class="re0">$http_pragma</span> <span class="re0">$http_authorization</span><span class="sy0">;</span></pre> </div> </div><p>Note that the response from the back-end is still eligible for caching. Thus one way of refreshing an item in the cache is sending a request with a header you pick yourself, e.g. &quot;My-Secret-Header: 1&quot;, then having a <b>proxy_cache_bypass</b> line like: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1">proxy_cache_bypass <span class="re0">$http_my_secret_header</span><span class="sy0">;</span></pre> </div> </div><p>Can be used in conjunction with the directive <a href="#proxy_no_cache">proxy_no_cache</a>. </p><br><i>Module: HttpProxyModule</i> <|start_filename|>resources/docs/directives/variables_hash_max_size.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpCoreModule&amp;action=edit&amp;section=76" title="Edit section: variables hash max size">edit</a>]</span> <span class="mw-headline" id="variables_hash_max_size"> variables_hash_max_size </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>variables_hash_max_size</b> <i>size</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>512</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_core_module.html#variables_hash_max_size">variables_hash_max_size</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 665/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> The maximum size of the variables hash table. For more detail see the description of tuning the hash tables in <a href="/Optimizations" title="Optimizations">Nginx Optimizations</a>. </p><h1><span class="editsection">[<a href="/index.php?title=HttpCoreModule&amp;action=edit&amp;section=77" title="Edit section: Variables">edit</a>]</span> <span class="mw-headline" id="Variables"> Variables </span></h1><p>The core module supports built-in variables, whose names correspond with the names of variables in Apache. </p><p>First of all, there are variables which represent header lines in the client request, for example, <code>$http_user_agent</code>, <code>$http_cookie</code>, and so forth. Note that because these correspond to what the client actually sends, they are not guaranteed to exist and their meaning is defined elsewhere (e.g. in relevant standards). </p><p>Furthermore, there are other variables: </p><br><i>Module: HttpCoreModule</i> <|start_filename|>resources/docs/directives/merge_slashes.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpCoreModule&amp;action=edit&amp;section=38" title="Edit section: merge slashes">edit</a>]</span> <span class="mw-headline" id="merge_slashes"> merge_slashes </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>merge_slashes</b> <code>on</code> | <code>off</code> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>on</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_core_module.html#merge_slashes">merge_slashes</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 330/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Enables merging adjacent slashes when parsing the request line. For example, a request for <a rel="nofollow" class="external free" href="http://www.example.com/foo//bar/">http://www.example.com/foo//bar/</a> will produce the following values for $uri: </p><ul> <li> on: /foo/bar/ </li> <li> off: /foo//bar/ </li> </ul><p><b>Be aware</b> that static location matching is performed as a string compare, so if merge_slashes is turned off, a request for /foo//bar/ will *not* match <code>location /foo/bar/</code>. </p><br><i>Module: HttpCoreModule</i> <|start_filename|>resources/docs/directives/ssl_protocols.html<|end_filename|> <h3>Directive can have multiple meanings. Each variant is separated with horizontal line</h3><hr><h2><span class="editsection">[<a href="/index.php?title=HttpSslModule&amp;action=edit&amp;section=13" title="Edit section: ssl protocols">edit</a>]</span> <span class="mw-headline" id="ssl_protocols"> ssl_protocols </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>ssl_protocols</b> [ <code>SSLv2</code> ] [ <code>SSLv3</code> ] [ <code>TLSv1</code> ] [ <code>TLSv1.1</code> ] [ <code>TLSv1.2</code> ]</td> </tr> <tr> <td><b>Default:</b></td> <td> <i>SSLv3 TLSv1 TLSv1.1 TLSv1.2</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_ssl_module.html#ssl_protocols">ssl_protocols</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 107/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> This directive enables the protocol versions specified. </p><br><i>Module: HttpSslModule</i><hr><h2><span class="editsection">[<a href="/index.php?title=MailSslModule&amp;action=edit&amp;section=8" title="Edit section: ssl protocols">edit</a>]</span> <span class="mw-headline" id="ssl_protocols"> ssl_protocols </span></h2><p><b>syntax:</b> <i>ssl_protocols</i> <i><b>[SSLv2] [SSLv3] [TLSv1] </b></i> </p><p><b>default:</b> <i>SSLv2 SSLv3 TLSv1</i> </p><p><b>context:</b> <i>mail, server</i> </p><p>Directive enables the protocols indicated. </p><br><i>Module: MailSslModule</i> <|start_filename|>src/net/ishchenko/idea/nginx/psi/NginxLuaContext.java<|end_filename|> package net.ishchenko.idea.nginx.psi; import com.intellij.psi.PsiLanguageInjectionHost; public interface NginxLuaContext extends NginxPsiElement, NginxDirective, PsiLanguageInjectionHost { } <|start_filename|>resources/docs/directives/aio.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpCoreModule&amp;action=edit&amp;section=3" title="Edit section: aio">edit</a>]</span> <span class="mw-headline" id="aio"> aio </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>aio</b> <code>on</code> | <code>off</code> | <code>sendfile</code> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>off</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Appeared in:</b></td> <td> 0.8.11</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_core_module.html#aio">aio</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 10/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> This directive is usable as of Linux kernel 2.6.22. For Linux it is required to use directio, this automatically disables sendfile support. </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#location"><span class="kw3">location</span></a> /video <span class="br0">{</span> aio on<span class="sy0">;</span> directio <span class="nu0">512</span><span class="sy0">;</span> output_buffers <span class="nu0">1</span> 128k<span class="sy0">;</span> <span class="br0">}</span></pre> </div> </div><p>In FreeBSD before 5.2.1 and Nginx 0.8.12 you must disable sendfile support. </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#location"><span class="kw3">location</span></a> /video <span class="br0">{</span> aio on<span class="sy0">;</span> <a href="/NginxHttpCoreModule#sendfile"><span class="kw3">sendfile</span></a> off<span class="sy0">;</span> output_buffers <span class="nu0">1</span> 128k<span class="sy0">;</span> <span class="br0">}</span></pre> </div> </div><p>As of FreeBSD 5.2.1 and Nginx 0.8.12 you can use it along with sendfile. </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#location"><span class="kw3">location</span></a> /video <span class="br0">{</span> aio <a href="/NginxHttpCoreModule#sendfile"><span class="kw3">sendfile</span></a><span class="sy0">;</span> <a href="/NginxHttpCoreModule#sendfile"><span class="kw3">sendfile</span></a> on<span class="sy0">;</span> <a href="/NginxHttpCoreModule#tcp_nopush"><span class="kw3">tcp_nopush</span></a> on<span class="sy0">;</span> <span class="br0">}</span></pre> </div> </div><br><i>Module: HttpCoreModule</i> <|start_filename|>resources/docs/directives/types.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpCoreModule&amp;action=edit&amp;section=71" title="Edit section: types">edit</a>]</span> <span class="mw-headline" id="types"> types </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>types</b> { ... }</td> </tr> <tr> <td><b>Default:</b></td> <td> <i>{ text/html html; image/gif gif; image/jpeg jpg; }</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_core_module.html#types">types</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 624/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Specifies one or more mappings between MIME types and file extensions. More than one extension can be assigned to a MIME type. </p><p>For example: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#types"><span class="kw3">types</span></a> <span class="br0">{</span> text/html html<span class="sy0">;</span> image/gif gif<span class="sy0">;</span> image/jpeg jpg<span class="sy0">;</span> <span class="br0">}</span></pre> </div> </div><p>A sufficiently complete table of mappings is included with nginx, and is located at <code>conf/mime.types</code>. </p><p>If you wanted responses to particular location to always indicate a single MIME type, you could define an empty <i>types</i> block and set the <i>default_type</i> directive. For example: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpCoreModule#location"><span class="kw3">location</span></a> /download/ <span class="br0">{</span> <a href="/NginxHttpCoreModule#types"><span class="kw3">types</span></a> <span class="br0">{</span> <span class="br0">}</span> <a href="/NginxHttpCoreModule#default_type"><span class="kw3">default_type</span></a> application/octet-stream<span class="sy0">;</span> <span class="br0">}</span></pre> </div> </div><br><i>Module: HttpCoreModule</i> <|start_filename|>resources/docs/directives/geoip_country.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpGeoipModule&amp;action=edit&amp;section=3" title="Edit section: geoip country">edit</a>]</span> <span class="mw-headline" id="geoip_country"> geoip_country </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>geoip_country</b> <i>file</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> http</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_geoip_module.html#geoip_country">geoip_country</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 37/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> This directive specifies the full path to the Geo IP database .dat file that associates IP addresses with country geolocation information. This allows you to get the country corresponding to the given IP. It can be used to determine the visitor's country from the IP address of the client. When set the following variables are available: </p><ul> <li> $geoip_country_code — two-letter country code, for example, &quot;RU&quot;, &quot;US&quot;. </li> <li> $geoip_country_code3 — three-letter country code, for example, &quot;RUS&quot;, &quot;USA&quot;. </li> <li> $geoip_country_name — the (verbose) name of the country, for example, &quot;Russian Federation&quot;, &quot;United States&quot;, &amp;c. </li> </ul><p>Nginx caches all supplied databases in memory. The country database is small, roughly 1.4M, therefore there's very little penalty in caching it. The city database is much bigger. Hence its memory footprint is larger. </p><br><i>Module: HttpGeoipModule</i> <|start_filename|>resources/docs/directives/block.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpSsiModule&amp;action=edit&amp;section=8" title="Edit section: block">edit</a>]</span> <span class="mw-headline" id="block"> block </span></h2><p>This command creates a block, which can be used as a silencer in command <code>include</code>. Inside the block there can be other SSI commands. </p><ul> <li> <code>name</code> — the name of the block. For example: </li> </ul><pre> &lt;!--# block name=&quot;one&quot; --&gt; the silencer &lt;!--# endblock --&gt; </pre><br><i>Module: HttpSsiModule</i> <|start_filename|>src/net/ishchenko/idea/nginx/run/NginxProcessHandler.java<|end_filename|> /* * Copyright 2009 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.ishchenko.idea.nginx.run; import com.intellij.execution.ExecutionException; import com.intellij.execution.process.OSProcessHandler; import com.intellij.execution.process.ProcessAdapter; import com.intellij.execution.process.ProcessEvent; import com.intellij.execution.process.ProcessOutputTypes; import com.intellij.execution.ui.ConsoleView; import com.intellij.execution.ui.ConsoleViewContentType; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import net.ishchenko.idea.nginx.NginxBundle; import net.ishchenko.idea.nginx.configurator.NginxServerDescriptor; import net.ishchenko.idea.nginx.configurator.NginxServersConfiguration; import net.ishchenko.idea.nginx.platform.PlatformDependentTools; import java.io.File; import java.io.IOException; /** * Created by IntelliJ IDEA. * User: Max * Date: 24.07.2009 * Time: 2:42:59 */ public class NginxProcessHandler extends OSProcessHandler { public static final Logger LOG = Logger.getInstance("#net.ishchenko.idea.nginx.run.NginxProcessHandler"); private NginxServerDescriptor descriptorCopy; private ConsoleView console; private NginxProcessHandler(Process process, String commandLine, NginxServerDescriptor descriptorCopy) { super(process, commandLine); this.descriptorCopy = descriptorCopy; } public static NginxProcessHandler create(NginxRunConfiguration config) throws ExecutionException { String descriptorId = config.getServerDescriptorId(); NginxServerDescriptor descriptor = NginxServersConfiguration.getInstance().getDescriptorById(descriptorId); if (descriptor == null) { throw new ExecutionException(NginxBundle.message("run.error.servernotfound")); } NginxServerDescriptor descriptorCopy = descriptor.clone(); VirtualFile executableVirtualFile = LocalFileSystem.getInstance().findFileByPath(descriptorCopy.getExecutablePath()); if (executableVirtualFile == null || executableVirtualFile.isDirectory()) { throw new ExecutionException(NginxBundle.message("run.error.badpath", descriptorCopy.getExecutablePath())); } PlatformDependentTools pdt = ServiceManager.getService(PlatformDependentTools.class); ProcessBuilder builder = new ProcessBuilder(pdt.getStartCommand(descriptorCopy)); builder.directory(new File(executableVirtualFile.getParent().getPath())); try { return new NginxProcessHandler(builder.start(), StringUtil.join(pdt.getStartCommand(descriptorCopy), " "), descriptorCopy.clone()); } catch (IOException e) { throw new ExecutionException(e.getMessage(), e); } } @Override public void destroyProcess() { if (tryToStop()) { super.destroyProcess(); } else { console.print("Could not stop process.\n", ConsoleViewContentType.ERROR_OUTPUT); } } private boolean tryToStop() { PlatformDependentTools pdt = ServiceManager.getService(PlatformDependentTools.class); VirtualFile executableVirtualFile = LocalFileSystem.getInstance().findFileByPath(descriptorCopy.getExecutablePath()); String[] stopCommand = pdt.getStopCommand(descriptorCopy); ProcessBuilder builder = new ProcessBuilder(stopCommand); builder.directory(new File(executableVirtualFile.getParent().getPath())); boolean successfullyStopped = false; try { OSProcessHandler osph = new OSProcessHandler(builder.start(), StringUtil.join(stopCommand, " ")); osph.addProcessListener(new ProcessAdapter() { @Override public void onTextAvailable(final ProcessEvent event, Key outputType) { ConsoleViewContentType contentType = ConsoleViewContentType.SYSTEM_OUTPUT; if (outputType == ProcessOutputTypes.STDERR) { contentType = ConsoleViewContentType.ERROR_OUTPUT; } console.print(event.getText(), contentType); } }); osph.startNotify(); osph.waitFor(); osph.destroyProcess(); //is that needed if waitFor has returned? successfullyStopped = osph.getProcess().exitValue() == 0; } catch (IOException e) { LOG.error(e); } return successfullyStopped; } public void setConsole(ConsoleView console) { this.console = console; } public NginxServerDescriptor getDescriptor() { return descriptorCopy; } } <|start_filename|>resources/docs/directives/ssl_certificate_key.html<|end_filename|> <h3>Directive can have multiple meanings. Each variant is separated with horizontal line</h3><hr><h2><span class="editsection">[<a href="/index.php?title=HttpSslModule&amp;action=edit&amp;section=7" title="Edit section: ssl certificate key">edit</a>]</span> <span class="mw-headline" id="ssl_certificate_key"> ssl_certificate_key </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>ssl_certificate_key</b> <i>file</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_ssl_module.html#ssl_certificate_key">ssl_certificate_key</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 56/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> This directive specifies the file containing the private key, in PEM format, for this virtual host. Since version 0.6.7 the file path is relative to the directory where nginx main configuration file, nginx.conf, resides. </p><br><i>Module: HttpSslModule</i><hr><h2><span class="editsection">[<a href="/index.php?title=MailSslModule&amp;action=edit&amp;section=5" title="Edit section: ssl certificate key">edit</a>]</span> <span class="mw-headline" id="ssl_certificate_key"> ssl_certificate_key </span></h2><p><b>syntax:</b> <i>ssl_certificate_key</i> <i><b>file</b></i> </p><p><b>default:</b> <i>cert.pem</i> </p><p><b>context:</b> <i>mail, server</i> </p><p>Indicates file with the secret key in PEM format for this virtual server. </p><br><i>Module: MailSslModule</i> <|start_filename|>resources/docs/directives/client_max_body_size.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpCoreModule&amp;action=edit&amp;section=13" title="Edit section: client max body size">edit</a>]</span> <span class="mw-headline" id="client_max_body_size"> client_max_body_size </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>client_max_body_size</b> <i>size</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>1m</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_core_module.html#client_max_body_size">client_max_body_size</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 101/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Specifies the maximum accepted body size of a client request, as indicated by the request header <code>Content-Length</code>. </p><p>If the stated content length is greater than this size, then the client receives the HTTP error code 413 (&quot;Request Entity Too Large&quot;). It should be noted that web browsers do not usually know how to properly display such an HTTP error. </p><p>Set to 0 to disable. </p><br><i>Module: HttpCoreModule</i> <|start_filename|>resources/docs/directives/fastcgi_max_temp_file_size.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpFastcgiModule&amp;action=edit&amp;section=24" title="Edit section: fastcgi max temp file size">edit</a>]</span> <span class="mw-headline" id="fastcgi_max_temp_file_size"> fastcgi_max_temp_file_size </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>fastcgi_max_temp_file_size</b> <i>size</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> <i>1024m</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_max_temp_file_size">fastcgi_max_temp_file_size</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 184/1000000 Post-expand include size: 0/2097152 bytes Template argument size: 0/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> To disable buffering to temporary files on disk for all replies that are greater than the <a href="/HttpFcgiModule#fastcgi_buffers" title="HttpFcgiModule" class="mw-redirect">fastcgi_buffers</a> and transfer data synchronously to the client set fastcgi_max_temp_file_size to 0. </p><p>Otherwise if specified it must be equal or bigger than maximum of the value of fastcgi_buffer_size and one of the fastcgi_buffers. </p><br><i>Module: HttpFastcgiModule</i> <|start_filename|>resources/docs/directives/fastcgi_store_access.html<|end_filename|> <h2><span class="editsection">[<a href="/index.php?title=HttpFastcgiModule&amp;action=edit&amp;section=37" title="Edit section: fastcgi store access">edit</a>]</span> <span class="mw-headline" id="fastcgi_store_access"> fastcgi_store_access </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>fastcgi_store_access</b> <i>users</i>&nbsp;: <i>permissions</i> ...</td> </tr> <tr> <td><b>Default:</b></td> <td> <i>user:rw</i></td> </tr> <tr> <td><b>Context:</b></td> <td> http<br />server<br />location</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_store_access">fastcgi_store_access</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 346/1000000 Post-expand include size: 401/2097152 bytes Template argument size: 178/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> This directive assigns the permissions for the created files and directories, for example: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpFcgiModule#fastcgi_store_access"><span class="kw11">fastcgi_store_access</span></a> <a href="/NginxHttpCoreModule#user"><span class="kw1">user</span></a>:rw group:rw all:r<span class="sy0">;</span></pre> </div> </div><p>If any rights for groups or all are assigned, then it is not necessary to assign rights for user: </p><div dir="ltr" class="mw-geshi" style="text-align: left;"> <div class="nginx source-nginx"> <pre class="de1"><a href="/NginxHttpFcgiModule#fastcgi_store_access"><span class="kw11">fastcgi_store_access</span></a> group:rw all:r<span class="sy0">;</span></pre> </div> </div><br><i>Module: HttpFastcgiModule</i> <|start_filename|>resources/docs/directives/set.html<|end_filename|> <h3>Directive can have multiple meanings. Each variant is separated with horizontal line</h3><hr><h2><span class="editsection">[<a href="/index.php?title=HttpRewriteModule&amp;action=edit&amp;section=8" title="Edit section: set">edit</a>]</span> <span class="mw-headline" id="set"> set </span></h2><table class="directive-ref-table"> <tbody> <tr> <td class="drt-td1"><b>Syntax:</b></td> <td class="drt-td2"> <b>set</b> <i>variable</i> <i>value</i> </td> </tr> <tr> <td><b>Default:</b></td> <td> </td> </tr> <tr> <td><b>Context:</b></td> <td> server<br />location<br />if</td> </tr> <tr> <td><b>Reference:</b></td> <td><a rel="nofollow" class="external text" href="http://nginx.org/en/docs/http/ngx_http_rewrite_module.html#set">set</a></td> </tr> </tbody> </table><p> <!-- NewPP limit report Preprocessor node count: 99/1000000 Post-expand include size: 186/2097152 bytes Template argument size: 90/2097152 bytes Expensive parser function count: 0/100 --> </p><p><br /> Directive establishes value for the variable indicated. As the value it is possible to use a text, variables and their combination. </p><p>You can use <b>set</b> to define a new variable. Note that you can't set the value of a <i>$http_xxx</i> header variable. </p><br><i>Module: HttpRewriteModule</i><hr><h2><span class="editsection">[<a href="/index.php?title=HttpSsiModule&amp;action=edit&amp;section=13" title="Edit section: set">edit</a>]</span> <span class="mw-headline" id="set"> set </span></h2><p>Assign a variable. </p><ul> <li> <code>var</code> — the variable. </li> <li> <code>value</code> — its value. If it contains variable names, these will be evaluated. </li> </ul><h1><span class="editsection">[<a href="/index.php?title=HttpSsiModule&amp;action=edit&amp;section=14" title="Edit section: Variables">edit</a>]</span> <span class="mw-headline" id="Variables"> Variables </span></h1><br><i>Module: HttpSsiModule</i>
griffenliu/idea-nginx
<|start_filename|>src/Language/Haskell/Generate/Expression.hs<|end_filename|> module Language.Haskell.Generate.Expression ( Expression(..) , app ) where import Language.Haskell.Exts.Syntax newtype Expression t = Expression { runExpression :: Exp } app :: Expression (a -> b) -> Expression a -> Expression b app (Expression a) (Expression b) = Expression $ App a b <|start_filename|>src/Language/Haskell/Generate/Monad.hs<|end_filename|> {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE CPP #-} module Language.Haskell.Generate.Monad ( Generate(..), ExpG , runGenerate, newName , returnE , useValue, useCon, useVar , caseE , applyE, applyE2, applyE3, applyE4, applyE5, applyE6 , (<>$) , GenExp(..) , ModuleM(..) , ModuleG , FunRef(..) , Name(..) , exportFun , addDecl , runModuleM , generateModule , generateExp ) where import Control.Applicative import Control.Monad import Control.Monad.Trans.Class import Control.Monad.Trans.State import Control.Monad.Trans.Writer import qualified Data.Set as S import Language.Haskell.Exts.Pretty import Language.Haskell.Exts.SrcLoc import Language.Haskell.Exts.Syntax import Language.Haskell.Generate.Expression import Prelude -------------------------------------------------------------------------------- -- Generate expressions -- | This monad keeps track of a counter for generating unique names and the set of modules -- that are needed for the expression. newtype Generate a = Generate { unGenerate :: StateT Integer (Writer (S.Set ModuleName)) a } deriving (Functor, Applicative, Monad) -- | Extract the set of modules and the value from a Generate action. runGenerate :: Generate a -> (a, S.Set ModuleName) runGenerate (Generate a) = runWriter $ evalStateT a 0 -- | This is a type alias for a Generate action that returns an expression of type 't'. type ExpG t = Generate (Expression t) -- | Use a haskell-src-exts Exp as the result of a Generate action. returnE :: Exp -> ExpG t returnE = return . Expression -- | Pretty print the expression generated by a given action. generateExp :: ExpG t -> String generateExp = prettyPrint . runExpression . fst . runGenerate -- | Generate a case expression. caseE :: ExpG x -> [(Pat, ExpG t)] -> ExpG t caseE v alt = do v' <- v #if MIN_VERSION_haskell_src_exts(1,17,0) alt' <- mapM (\(p,a) -> fmap (\a' -> Alt noLoc p (UnGuardedRhs $ runExpression a') Nothing) a) alt #elif MIN_VERSION_haskell_src_exts(1,16,0) alt' <- mapM (\(p,a) -> fmap (\a' -> Alt noLoc p (UnGuardedRhs $ runExpression a') (BDecls [])) a) alt #else alt' <- mapM (\(p,a) -> fmap (\a' -> Alt noLoc p (UnGuardedAlt $ runExpression a') (BDecls [])) a) alt #endif return $ Expression $ Case (runExpression v') alt' -- | Import a function from a module. This function is polymorphic in the type of the resulting expression, -- you should probably only use this function to define type-restricted specializations. -- -- Example: -- -- > addInt :: ExpG (Int -> Int -> Int) -- Here we restricted the type to something sensible -- > addInt = useValue "Prelude" $ Symbol "+" -- useValue :: String -> Name -> ExpG a useValue md name = Generate $ do lift $ tell $ S.singleton $ ModuleName md return $ Expression $ Var $ Qual (ModuleName md) name -- | Import a value constructor from a module. Returns the qualified name of the constructor. useCon :: String -> Name -> Generate QName useCon md name = Generate $ do lift $ tell $ S.singleton $ ModuleName md return $ Qual (ModuleName md) name -- | Use the value of a variable with the given name. useVar :: Name -> ExpG t useVar name = return $ Expression $ Var $ UnQual name -- | Generate a new unique variable name with the given prefix. Note that this new variable name -- is only unique relative to other variable names generated by this function. newName :: String -> Generate Name newName pref = Generate $ do i <- get <* modify succ return $ Ident $ pref ++ show i -- | Generate a expression from a haskell value. This can for example be used to create lambdas: -- -- >>> putStrLn $ generateExp $ expr (\x f -> f <>$ x) -- \ pvar_0 -> \ pvar_1 -> pvar_1 pvar_0 -- -- Or string literals: -- -- >>> putStrLn $ generateExp $ expr "I'm a string!" -- ['I', '\'', 'm', ' ', 'a', ' ', 's', 't', 'r', 'i', 'n', 'g', '!'] -- class GenExp t where type GenExpType t :: * -- | This function generates the haskell expression from the given haskell value. expr :: t -> ExpG (GenExpType t) instance GenExp (ExpG a) where type GenExpType (ExpG a) = a expr = id instance GenExp (Expression t) where type GenExpType (Expression t) = t expr = return instance GenExp Char where type GenExpType Char = Char expr = return . Expression . Lit . Char instance GenExp Integer where type GenExpType Integer = Integer expr = return . Expression . Lit . Int instance GenExp Rational where type GenExpType Rational = Rational expr = return . Expression . Lit . Frac instance GenExp a => GenExp [a] where type GenExpType [a] = [GenExpType a] expr = Generate . fmap (Expression . List . map runExpression) . mapM (unGenerate . expr) instance GenExp x => GenExp (ExpG a -> x) where type GenExpType (ExpG a -> x) = a -> GenExpType x expr f = do pvarName <- newName "pvar_" body <- expr $ f $ return $ Expression $ Var $ UnQual pvarName return $ Expression $ Lambda noLoc [PVar pvarName] $ runExpression body -------------------------------------------------------------------------------- -- Apply functions -- | Apply a function in a haskell expression to a value. applyE :: ExpG (a -> b) -> ExpG a -> ExpG b applyE a b = wrap $ liftM (foldl1 App) $ sequence [unwrap a, unwrap b] where wrap = fmap Expression unwrap = fmap runExpression -- | Operator for 'applyE'. (<>$) :: ExpG (a -> b) -> ExpG a -> ExpG b (<>$) = applyE infixl 1 <>$ -- | ApplyE for 2 arguments applyE2 :: ExpG (a -> b -> c) -> ExpG a -> ExpG b -> ExpG c applyE2 a b c = wrap $ liftM (foldl1 App) $ sequence [unwrap a,unwrap b,unwrap c] where wrap = fmap Expression unwrap = fmap runExpression -- | Apply a function to 3 arguments applyE3 :: ExpG (a -> b -> c -> d) -> ExpG a -> ExpG b -> ExpG c -> ExpG d applyE3 a b c d = wrap $ liftM (foldl1 App) $ sequence [unwrap a,unwrap b,unwrap c,unwrap d] where wrap = fmap Expression unwrap = fmap runExpression -- | Apply a function to 4 arguments applyE4 :: ExpG (a -> b -> c -> d -> e) -> ExpG a -> ExpG b -> ExpG c -> ExpG d -> ExpG e applyE4 a b c d e = wrap $ liftM (foldl1 App) $ sequence [unwrap a,unwrap b,unwrap c,unwrap d,unwrap e] where wrap = fmap Expression unwrap = fmap runExpression -- | Apply a function to 5 arguments applyE5 :: ExpG (a -> b -> c -> d -> e -> f) -> ExpG a -> ExpG b -> ExpG c -> ExpG d -> ExpG e -> ExpG f applyE5 a b c d e f = wrap $ liftM (foldl1 App) $ sequence [unwrap a,unwrap b,unwrap c,unwrap d,unwrap e,unwrap f] where wrap = fmap Expression unwrap = fmap runExpression -- | Apply a function to 6 arguments applyE6 :: ExpG (a -> b -> c -> d -> e -> f -> g) -> ExpG a -> ExpG b -> ExpG c -> ExpG d -> ExpG e -> ExpG f -> ExpG g applyE6 a b c d e f g = wrap $ liftM (foldl1 App) $ sequence [unwrap a,unwrap b,unwrap c,unwrap d,unwrap e,unwrap f,unwrap g] where wrap = fmap Expression unwrap = fmap runExpression -------------------------------------------------------------------------------- -- Generate modules -- | A module keeps track of the needed imports, but also has a list of declarations in it. newtype ModuleM a = ModuleM (Writer (S.Set ModuleName, [Decl]) a) deriving (Functor, Applicative, Monad) -- | This is the resulting type of a function generating a module. It is a ModuleM action returning the export list. type ModuleG = ModuleM (Maybe [ExportSpec]) -- | A reference to a function. With a reference to a function, you can apply it (by lifting it into ExprT using 'expr') to some value -- or export it using 'exportFun'. data FunRef t = FunRef Name instance GenExp (FunRef t) where type GenExpType (FunRef t) = t expr (FunRef n) = return $ Expression $ Var $ UnQual n -- | Generate a ExportSpec for a given function item. exportFun :: FunRef t -> ExportSpec #if MIN_VERSION_haskell_src_exts(1,16,0) && !MIN_VERSION_haskell_src_exts(1,17,0) exportFun (FunRef name) = EVar NoNamespace (UnQual name) #else exportFun (FunRef name) = EVar (UnQual name) #endif -- | Add a declaration to the module. Return a reference to it that can be used to either apply the function to some values or export it. addDecl :: Name -> ExpG t -> ModuleM (FunRef t) addDecl name e = ModuleM $ do let (body, mods) = runGenerate e #if MIN_VERSION_haskell_src_exts(1,17,0) tell (mods, [FunBind [Match noLoc name [] Nothing (UnGuardedRhs $ runExpression body) Nothing]]) #else tell (mods, [FunBind [Match noLoc name [] Nothing (UnGuardedRhs $ runExpression body) $ BDecls []]]) #endif return $ FunRef name -- | Extract the Module from a module generator. runModuleM :: ModuleG -> String -> Module runModuleM (ModuleM act) name = #if MIN_VERSION_haskell_src_exts(1,16,0) Module noLoc (ModuleName name) [] Nothing export (map (\md -> ImportDecl noLoc md True False False Nothing Nothing Nothing) $ S.toList imps) decls #else Module noLoc (ModuleName name) [] Nothing export (map (\md -> ImportDecl noLoc md True False Nothing Nothing Nothing) $ S.toList imps) decls #endif where (export, (imps, decls)) = runWriter act -- | Generate the source code for a module. generateModule :: ModuleG -> String -> String generateModule = fmap prettyPrint . runModuleM <|start_filename|>src/Language/Haskell/Generate/TH.hs<|end_filename|> {-# LANGUAGE TemplateHaskell #-} module Language.Haskell.Generate.TH ( -- | This module provides functions for automagically generating type-safe ExpG definitions from functions. For an example on how to use this, -- you can look at the 'Language.Haskell.Generate.Prelude' module. declareFunction , declareNamedSymbol , declareNamedFunction , declareNamedThing ) where import Data.Char import Language.Haskell.Exts.Syntax hiding (Name) import Language.Haskell.Generate.Monad hiding (Name) import Language.Haskell.TH import Language.Haskell.TH.Syntax -- | Make a ExpG for the given function, using the given name for the definition. declareNamedFunction :: (Name, String) -> DecsQ declareNamedFunction (func, name) = declareNamedThing (func, name, 'Ident) -- | Make a ExpG for some thing, using the given name for the definition. The third tuple element -- specifies the constructor to use for constructing the Name. This can either be @'Symbol@ (for symbols) -- or @'Ident@ (for functions). declareNamedThing :: (Name, String, Name) -> DecsQ declareNamedThing (thing, name, thingClass) = do info <- reify thing typ <- case info of VarI _ t _ _ -> return t ClassOpI _ t _ _ -> return t DataConI _ t _ _ -> return t _ -> fail $ "Not a function: " ++ nameBase thing md <- maybe (fail "No module name for function!") return $ nameModule thing sequence [ sigD (mkName name) $ return $ overQuantifiedType (ConT ''ExpG `AppT`) typ , funD (mkName name) $ return $ flip (clause []) [] $ normalB [| useValue $(lift md) $ $(conE thingClass) $(lift $ nameBase thing) |] ] where overQuantifiedType f (ForallT bnds ctx t) = ForallT (map removeKind bnds) ctx $ overQuantifiedType f t overQuantifiedType f x = f x removeKind :: TyVarBndr -> TyVarBndr removeKind (KindedTV n _) = PlainTV n removeKind x = x -- | Declare a symbol, using the given name for the definition. declareNamedSymbol :: (Name, String) -> DecsQ declareNamedSymbol (func, name) = declareNamedThing (func, name, 'Symbol) -- | Declare a function. The name of the definition will be the name of the function with an added apostrophe. (Example: declareFunction 'add generates -- a definition with the name add'). declareFunction :: Name -> DecsQ declareFunction func = declareNamedFunction (func, funcName ++ "'") where funcName = case nameBase func of (h:t) -> toLower h:t x -> x <|start_filename|>src/Language/Haskell/Generate/PreludeDef.hs<|end_filename|> {-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TemplateHaskell #-} module Language.Haskell.Generate.PreludeDef where import Language.Haskell.Exts.Syntax import Language.Haskell.Generate.Monad import Language.Haskell.Generate.TH -------------------------------------------------------------------------------- -- Basic functions fmap concat $ mapM declareFunction [ 'maybe , 'either , 'fst , 'snd , 'curry , 'uncurry , 'not , 'negate, 'abs, 'signum, 'fromInteger , 'quot, 'rem, 'div, 'mod, 'quotRem, 'divMod, 'toInteger , 'recip, 'fromRational , 'pi, 'exp, 'log, 'sqrt, 'logBase, 'sin, 'cos, 'tan , 'asin, 'acos, 'atan, 'sinh, 'cosh, 'tanh, 'asinh, 'acosh, 'atanh , 'properFraction, 'truncate, 'round, 'ceiling, 'floor , 'floatRadix, 'floatDigits, 'floatRange, 'decodeFloat , 'encodeFloat, 'exponent, 'significand, 'scaleFloat, 'isNaN , 'isInfinite, 'isDenormalized, 'isIEEE, 'isNegativeZero, 'atan2 , 'subtract, 'even, 'odd, 'gcd, 'lcm , 'fromIntegral, 'realToFrac , 'fmap, 'return, 'mapM, 'mapM_ , 'id, 'const, 'flip, 'until, 'asTypeOf, 'undefined , 'map, 'filter, 'head, 'last, 'tail, 'init, 'null, 'length , 'reverse, 'foldl, 'foldr, 'foldl1, 'foldr1, 'and, 'or, 'any, 'all, 'sum, 'product , 'concat, 'concatMap, 'maximum, 'minimum , 'scanl, 'scanr, 'scanl1, 'scanr1 , 'iterate, 'repeat, 'replicate, 'cycle , 'take, 'drop, 'splitAt, 'takeWhile, 'dropWhile, 'span, 'break , 'elem, 'notElem, 'lookup , 'zip, 'zip3, 'zipWith, 'zipWith3, 'unzip, 'unzip3 , 'lines, 'words, 'unlines, 'unwords , 'read, 'show , 'putChar, 'putStr, 'putStrLn, 'print , 'getChar, 'getLine, 'getContents, 'interact , 'readFile, 'writeFile, 'appendFile, 'readIO, 'readLn , 'Just, 'Left, 'Right, 'False, 'True, 'Nothing ] fmap concat $ mapM declareNamedSymbol [ ('(.), "dot'") , ('(+), "add'") , ('(*), "mult'") , ('(/), "divide'") , ('(**), "floatPow'") , ('(>>=), "bind'") , ('(>>), "then'") , ('(++), "append'") , ('(!!), "index'") , ('(==), "equal'") , ('(/=), "notequal'") ] (<>.) :: ExpG (b -> c) -> ExpG (a -> b) -> ExpG (a -> c) (<>.) a b = dot' <>$ a <>$ b tuple0 :: ExpG () tuple0 = returnE $ Var $ Special UnitCon tuple2 :: ExpG (a -> b -> (a,b)) tuple2 = returnE $ Var $ Special $ TupleCon Boxed 2 tuple3 :: ExpG (a -> b -> c -> (a,b,c)) tuple3 = returnE $ Var $ Special $ TupleCon Boxed 3 tuple4 :: ExpG (a -> b -> c -> d -> (a,b,c,d)) tuple4 = returnE $ Var $ Special $ TupleCon Boxed 4 tuple5 :: ExpG (a -> b -> c -> d -> (a,b,c,d,e)) tuple5 = returnE $ Var $ Special $ TupleCon Boxed 5 cons :: ExpG (a -> [a] -> [a]) cons = returnE $ Var $ Special Cons instance Num t => Num (ExpG t) where a + b = add' <>$ a <>$ b a - b = flip' <>$ subtract' <>$ a <>$ b a * b = mult' <>$ a <>$ b negate a = negate' <>$ a abs a = abs' <>$ a fromInteger a = returnE $ Lit $ Int a signum a = signum' <>$ a <|start_filename|>src/Language/Haskell/Generate.hs<|end_filename|> module Language.Haskell.Generate ( module X ) where import Language.Haskell.Exts.Syntax as X import Language.Haskell.Generate.Monad as X import Language.Haskell.Generate.PreludeDef as X <|start_filename|>Setup.hs<|end_filename|> {-# OPTIONS_GHC -Wall #-} module Main (main) where import Data.IORef import Data.List ( nub ) import Data.Version ( showVersion ) import Distribution.Package ( PackageName(PackageName), PackageId, InstalledPackageId, packageVersion, packageName ) import Distribution.PackageDescription ( PackageDescription(), TestSuite(..), hsSourceDirs, libBuildInfo, buildInfo) import Distribution.Simple ( defaultMainWithHooks, UserHooks(..), simpleUserHooks ) import Distribution.Simple.BuildPaths ( autogenModulesDir ) import Distribution.Simple.LocalBuildInfo ( withLibLBI, withTestLBI, withExeLBI, ComponentLocalBuildInfo(), LocalBuildInfo(), componentPackageDeps ) import Distribution.Simple.Setup ( BuildFlags(buildVerbosity), fromFlag, buildDistPref, defaultDistPref, fromFlagOrDefault ) import Distribution.Simple.Utils ( rewriteFile, createDirectoryIfMissingVerbose ) import Distribution.Verbosity ( Verbosity ) import System.Directory ( canonicalizePath ) import System.FilePath ( (</>) ) main :: IO () main = defaultMainWithHooks simpleUserHooks { buildHook = \pkg lbi hooks flags -> do generateBuildModule (fromFlag (buildVerbosity flags)) pkg lbi flags buildHook simpleUserHooks pkg lbi hooks flags } -- Very ad-hoc implementation of difference lists singletonDL :: a -> [a] -> [a] singletonDL = (:) emptyDL :: [a] -> [a] emptyDL = id appendDL :: ([a] -> [a]) -> ([a] -> [a]) -> [a] -> [a] appendDL x y = x . y generateBuildModule :: Verbosity -> PackageDescription -> LocalBuildInfo -> BuildFlags -> IO () generateBuildModule verbosity pkg lbi flags = do let dir = autogenModulesDir lbi createDirectoryIfMissingVerbose verbosity True dir withTestLBI pkg lbi $ \suite suitelbi -> do srcDirs <- mapM canonicalizePath $ hsSourceDirs $ testBuildInfo suite distDir <- canonicalizePath $ fromFlagOrDefault defaultDistPref $ buildDistPref flags depsVar <- newIORef emptyDL withLibLBI pkg lbi $ \lib liblbi -> modifyIORef depsVar $ appendDL . singletonDL $ depsEntry (libBuildInfo lib) liblbi suitelbi withExeLBI pkg lbi $ \exe exelbi -> modifyIORef depsVar $ appendDL . singletonDL $ depsEntry (buildInfo exe) exelbi suitelbi deps <- fmap ($ []) $ readIORef depsVar rewriteFile (map fixchar $ dir </> "Build_" ++ testName suite ++ ".hs") $ unlines [ "module Build_" ++ map fixchar (testName suite) ++ " where" , "getDistDir :: FilePath" , "getDistDir = " ++ show distDir , "getSrcDirs :: [FilePath]" , "getSrcDirs = " ++ show srcDirs , "deps :: [([FilePath], [String])]" , "deps = " ++ show deps ] where formatdeps = map (formatone . snd) formatone p = case packageName p of PackageName n -> n ++ "-" ++ showVersion (packageVersion p) depsEntry targetbi targetlbi suitelbi = (hsSourceDirs targetbi, formatdeps $ testDeps targetlbi suitelbi) fixchar '-' = '_' fixchar c = c testDeps :: ComponentLocalBuildInfo -> ComponentLocalBuildInfo -> [(InstalledPackageId, PackageId)] testDeps xs ys = nub $ componentPackageDeps xs ++ componentPackageDeps ys
rdnetto/haskell-generate
<|start_filename|>Assets/OffscreenCEF.cs<|end_filename|> using Aleab.CefUnity.Structs; using System; using System.Collections; using UnityEngine; using Xilium.CefGlue; namespace Aleab.CefUnity { [DisallowMultipleComponent] [RequireComponent(typeof(MeshRenderer))] public class OffscreenCEF : MonoBehaviour { [Space] [SerializeField] private Size windowSize = new Size(1280, 720); [SerializeField] private string url = "http://www.google.com"; [Space] [SerializeField] private bool hideScrollbars = false; private bool shouldQuit = false; private OffscreenCEFClient cefClient; public Texture2D BrowserTexture { get; private set; } private void Awake() { this.BrowserTexture = new Texture2D(this.windowSize.Width, this.windowSize.Height, TextureFormat.BGRA32, false); this.GetComponent<MeshRenderer>().material.mainTexture = this.BrowserTexture; } private void Start() { this.StartCef(); this.StartCoroutine(this.MessagePump()); DontDestroyOnLoad(this.gameObject.transform.root.gameObject); } private void OnDestroy() { this.Quit(); } private void OnApplicationQuit() { this.Quit(); } private void StartCef() { #if UNITY_EDITOR CefRuntime.Load("./Assets/Plugins/x86_64"); #else CefRuntime.Load(); #endif var cefMainArgs = new CefMainArgs(new string[] { }); var cefApp = new OffscreenCEFClient.OffscreenCEFApp(); // This is where the code path diverges for child processes. if (CefRuntime.ExecuteProcess(cefMainArgs, cefApp, IntPtr.Zero) != -1) Debug.LogError("Could not start the secondary process."); var cefSettings = new CefSettings { //ExternalMessagePump = true, MultiThreadedMessageLoop = false, SingleProcess = true, LogSeverity = CefLogSeverity.Verbose, LogFile = "cef.log", WindowlessRenderingEnabled = true, NoSandbox = true, }; // Start the browser process (a child process). CefRuntime.Initialize(cefMainArgs, cefSettings, cefApp, IntPtr.Zero); // Instruct CEF to not render to a window. CefWindowInfo cefWindowInfo = CefWindowInfo.Create(); cefWindowInfo.SetAsWindowless(IntPtr.Zero, false); // Settings for the browser window itself (e.g. enable JavaScript?). CefBrowserSettings cefBrowserSettings = new CefBrowserSettings() { BackgroundColor = new CefColor(255, 60, 85, 115), JavaScript = CefState.Enabled, JavaScriptAccessClipboard = CefState.Disabled, JavaScriptCloseWindows = CefState.Disabled, JavaScriptDomPaste = CefState.Disabled, JavaScriptOpenWindows = CefState.Disabled, LocalStorage = CefState.Disabled }; // Initialize some of the custom interactions with the browser process. this.cefClient = new OffscreenCEFClient(this.windowSize, this.hideScrollbars); // Start up the browser instance. CefBrowserHost.CreateBrowser(cefWindowInfo, this.cefClient, cefBrowserSettings, string.IsNullOrEmpty(this.url) ? "http://www.google.com" : this.url); } private void Quit() { this.shouldQuit = true; this.StopAllCoroutines(); this.cefClient.Shutdown(); CefRuntime.Shutdown(); } private IEnumerator MessagePump() { while (!this.shouldQuit) { CefRuntime.DoMessageLoopWork(); if (!this.shouldQuit) this.cefClient.UpdateTexture(this.BrowserTexture); yield return null; } } } }
aleab/cef-unity-sample
<|start_filename|>vendor/github.com/keybase/go-ps/process_openbsd_test.go<|end_filename|> // +build openbsd package ps import ( "testing" "github.com/stretchr/testify/assert" ) func TestFindProcessOpenBSD(t *testing.T) { proc := testFindProcess(t, "go-ps.test") assert.True(t, proc.PPid() > 0) } func TestProcessesOpenBSD(t *testing.T) { testProcesses(t, "go") } /* // Currently querying for -1 will return -1 :P func TestProcessesOpenBSDError(t *testing.T) { proc, err := findProcess(-1) assert.Nil(t, proc) assert.Nil(t, err) } */ <|start_filename|>vendor/rsc.io/goversion/version/read.go<|end_filename|> // Copyright 2017 The Go Authors. All Rights Reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package version reports the Go version used to build program executables. package version import ( "errors" "fmt" "strings" ) // Version is the information reported by ReadExe. type Version struct { Release string // Go version (runtime.Version in the program) BoringCrypto bool // program uses BoringCrypto StandardCrypto bool // program uses standard crypto (replaced by BoringCrypto) } // ReadExe reports information about the Go version used to build // the program executable named by file. func ReadExe(file string) (Version, error) { var v Version f, err := openExe(file) if err != nil { return v, err } defer f.Close() isGo := false for _, name := range f.SectionNames() { if name == ".note.go.buildid" { isGo = true } } syms, symsErr := f.Symbols() isGccgo := false for _, sym := range syms { name := sym.Name if name == "runtime.main" || name == "main.main" { isGo = true } if strings.HasPrefix(name, "runtime.") && strings.HasSuffix(name, "$descriptor") { isGccgo = true } if name == "runtime.buildVersion" { isGo = true release, err := readBuildVersion(f, sym.Addr, sym.Size) if err != nil { return v, err } v.Release = release } if strings.Contains(name, "_Cfunc__goboringcrypto_") { v.BoringCrypto = true } for _, s := range standardCryptoNames { if strings.Contains(name, s) { v.StandardCrypto = true } } } if *debugMatch { v.Release = "" } if v.Release == "" { g, release := readBuildVersionX86Asm(f) if g { isGo = true v.Release = release } } if isGccgo && v.Release == "" { isGo = true v.Release = "gccgo (version unknown)" } if !isGo && symsErr != nil { return v, symsErr } if !isGo { return v, errors.New("not a Go executable") } if v.Release == "" { v.Release = "unknown Go version" } return v, nil } var standardCryptoNames = []string{ "crypto/sha1.(*digest)", "crypto/sha256.(*digest)", "crypto/rand.(*devReader)", "crypto/rsa.encrypt", "crypto/rsa.decrypt", } func readBuildVersion(f exe, addr, size uint64) (string, error) { if size == 0 { size = uint64(f.AddrSize() * 2) } if size != 8 && size != 16 { return "", fmt.Errorf("invalid size for runtime.buildVersion") } data, err := f.ReadData(addr, size) if err != nil { return "", fmt.Errorf("reading runtime.buildVersion: %v", err) } if size == 8 { addr = uint64(f.ByteOrder().Uint32(data)) size = uint64(f.ByteOrder().Uint32(data[4:])) } else { addr = f.ByteOrder().Uint64(data) size = f.ByteOrder().Uint64(data[8:]) } if size > 1000 { return "", fmt.Errorf("implausible string size %d for runtime.buildVersion", size) } data, err = f.ReadData(addr, size) if err != nil { return "", fmt.Errorf("reading runtime.buildVersion string data: %v", err) } return string(data), nil } <|start_filename|>goprocess/gp_test.go<|end_filename|> package goprocess import "testing" func BenchmarkFindAll(b *testing.B) { for ii := 0; ii < b.N; ii++ { _ = FindAll() } } <|start_filename|>vendor/github.com/keybase/go-ps/process_unix_test.go<|end_filename|> // +build linux package ps import ( "os" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestUnixProcess(t *testing.T) { var _ Process = new(UnixProcess) } func TestProcessesUnixError(t *testing.T) { proc, err := findProcess(-1) assert.Nil(t, proc) assert.Nil(t, err) } func TestProcessesUnixPPid(t *testing.T) { proc, err := FindProcess(os.Getpid()) require.NoError(t, err) require.NotNil(t, proc) assert.Equal(t, os.Getpid(), proc.Pid()) assert.Equal(t, os.Getppid(), proc.PPid()) } <|start_filename|>vendor/github.com/keybase/go-ps/process_windows_test.go<|end_filename|> // +build windows package ps import ( "fmt" "os" "testing" "github.com/stretchr/testify/assert" ) func TestFindProcessWindows(t *testing.T) { proc := testFindProcess(t, "go-ps.test.exe") assert.True(t, proc.PPid() > 0) } func TestProcessesWindows(t *testing.T) { testProcesses(t, "go.exe") } func TestProcessesWindowsError(t *testing.T) { errFn := func() ([]Process, error) { return nil, fmt.Errorf("oops") } proc, err := findProcessWithFn(errFn, os.Getpid()) assert.Nil(t, proc) assert.EqualError(t, err, "Error listing processes: oops") } <|start_filename|>examples/hello/main.go<|end_filename|> // Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "log" "time" "github.com/google/gops/agent" ) func main() { if err := agent.Listen(agent.Options{ ShutdownCleanup: true, // automatically closes on os.Interrupt }); err != nil { log.Fatal(err) } time.Sleep(time.Hour) } <|start_filename|>vendor/github.com/xlab/treeprint/struct_test.go<|end_filename|> package treeprint import ( "fmt" "testing" "github.com/stretchr/testify/assert" ) type nameStruct struct { One string `json:"one" tree:"one"` Two int `tree:"two"` Three struct { SubOne []string SubTwo []interface{} SubThree struct { InnerOne *float64 `tree:"inner_one,omitempty"` InnerTwo *struct{} `tree:",omitempty"` InnerThree *float64 `tree:"inner_three"` } } } func TestFromStructName(t *testing.T) { assert := assert.New(t) tree, err := FromStruct(nameStruct{}, StructNameTree) assert.NoError(err) actual := tree.String() expected := `. ├── one ├── two └── Three ├── SubOne ├── SubTwo └── SubThree └── inner_three ` assert.Equal(expected, actual) } func TestFromStructTags(t *testing.T) { assert := assert.New(t) tree, err := FromStruct(nameStruct{}, StructTagTree) assert.NoError(err) actual := tree.String() expected := `. ├── [json:"one"] one ├── [] two └── [] Three ├── [] SubOne ├── [] SubTwo └── [] SubThree └── [] inner_three ` assert.Equal(expected, actual) } type typeStruct struct { One string `json:"one" tree:"one"` Two int `tree:"two"` Three subtypeStruct } type subtypeStruct struct { SubOne []string SubTwo []interface{} SubThree subsubTypeStruct } type subsubTypeStruct struct { InnerOne *float64 `tree:"inner_one,omitempty"` InnerTwo *struct{} `tree:",omitempty"` InnerThree *float64 `tree:"inner_three"` } func TestFromStructType(t *testing.T) { assert := assert.New(t) tree, err := FromStruct(typeStruct{}, StructTypeTree) assert.NoError(err) actual := tree.String() expected := `. ├── [string] one ├── [int] two └── [treeprint.subtypeStruct] Three ├── [[]string] SubOne ├── [[]interface {}] SubTwo └── [treeprint.subsubTypeStruct] SubThree └── [*float64] inner_three ` assert.Equal(expected, actual) } func TestFromStructTypeSize(t *testing.T) { assert := assert.New(t) tree, err := FromStruct(typeStruct{}, StructTypeSizeTree) assert.NoError(err) actual := tree.String() expected := `. ├── [16] one ├── [8] two └── [72] Three ├── [24] SubOne ├── [24] SubTwo └── [24] SubThree └── [8] inner_three ` assert.Equal(expected, actual) } type valueStruct struct { Name string Bio struct { Age int City string Meta interface{} } } func TestFromStructValue(t *testing.T) { assert := assert.New(t) val := valueStruct{ Name: "Max", } val.Bio.Age = 100 val.Bio.City = "NYC" val.Bio.Meta = []byte("hello") tree, err := FromStruct(val, StructValueTree) assert.NoError(err) actual := tree.String() expected := `. ├── [Max] Name └── Bio ├── [100] Age ├── [NYC] City └── [[104 101 108 108 111]] Meta ` assert.Equal(expected, actual) } func TestFromStructWithMeta(t *testing.T) { assert := assert.New(t) val := valueStruct{ Name: "Max", } val.Bio.Age = 100 val.Bio.City = "NYC" val.Bio.Meta = []byte("hello") tree, err := FromStructWithMeta(val, func(_ string, v interface{}) (string, bool) { return fmt.Sprintf("lol %T", v), true }) assert.NoError(err) actual := tree.String() expected := `. ├── [lol string] Name └── [lol struct { Age int; City string; Meta interface {} }] Bio ├── [lol int] Age ├── [lol string] City └── [lol []uint8] Meta ` assert.Equal(expected, actual) } <|start_filename|>vendor/github.com/keybase/go-ps/process_darwin_test.go<|end_filename|> // +build darwin package ps import ( "os" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestFindProcessDarwin(t *testing.T) { proc := testFindProcess(t, "go-ps.test") assert.True(t, proc.PPid() > 0) } func TestProcessesDarwin(t *testing.T) { testProcesses(t, "go") } func TestProcessesDarwinError(t *testing.T) { proc, err := findProcess(-1) assert.Nil(t, proc) assert.Nil(t, err) } func TestProcessExecRemoved(t *testing.T) { procPath, cmd, proc := testExecRun(t) defer cleanup(cmd, procPath) t.Logf("Ran with PID: %d", cmd.Process.Pid) // Remove it while it is running _ = os.Remove(procPath) matchPath := func(p Process) bool { return p.Pid() == proc.Pid() } procs, err := findProcessesWithFn(processes, matchPath, 1) require.NoError(t, err) t.Logf("Proc: %#v", procs[0]) }
Jorengarenar/gops
<|start_filename|>src/tree/Dimension.js<|end_filename|> import dimension from 'less/lib/less/tree/dimension'; import VariableNode from "./VariableNode"; import operate from "./operate"; export default class Dimension extends dimension { constructor(value, unit) { super(value, unit); } operate(context, op, other) { return new VariableNode(operate(context, this, op, other)); } } <|start_filename|>src/functions/types.js<|end_filename|> import VariableNode from "../tree/VariableNode"; import {convertNode as c} from "../tree/convert"; export const iscolor = value => { return new VariableNode(`require('tinycolor2')(${c(value)}).isValid().toString()`); }; export const isnumber = value => { return new VariableNode(`(!isNaN(parseFloat(${c(value)}))).toString()`); }; export const isstring = value => { return new VariableNode(`(('' + ${c(value)})[0] === '"').toString()`); }; export const ispixel = value => { return new VariableNode(`(('' + ${c(value)}).endsWith("px")).toString()`); }; export const ispercentage = value => { return new VariableNode(`(('' + ${c(value)}).endsWith("%")).toString()`); }; export const isem = value => { return new VariableNode(`(('' + ${c(value)}).endsWith("em")).toString()`); }; <|start_filename|>test/Component/List.test.js<|end_filename|> import React from 'react'; import renderer from 'react-test-renderer'; import styled from 'styled-components'; import 'jest-styled-components'; test.skip('Returns the number of elements in a value list', () => { const Div = styled.div` @list: "banana", "tomato", "potato", "peach"; n: length(@list); n2: length(1px solid #0080ff); `; expect(renderer.create(<Div/>).toJSON()).toMatchSnapshot(); }); test.skip('Returns the value at a specified position in a list.', () => { const Div = styled.div` @list: apple, pear, coconut, orange; value: extract(@list, 3); `; expect(renderer.create(<Div/>).toJSON()).toMatchSnapshot(); }); <|start_filename|>src/tree/operate.js<|end_filename|> export default (context, self, op, other) => { let unit = (self.unit && self.unit.toString()) || (other.unit && other.unit.toString()); if (unit) { unit = `"${unit}"`; } else { unit = `(('' + ${self.value}).replace(/[\\d.-]*/, "") || ('' + ${other.value}).replace(/[\\d.-]*/, ""))`; } return `parseFloat(${self.value}) ${op} parseFloat(${other.value}) + ${unit}`; } <|start_filename|>examples/index.js<|end_filename|> import React from 'react'; import ReactDOM from 'react-dom'; import Theme from './Theme'; import App from './App'; ReactDOM.render(<Theme><App/></Theme>, document.getElementById('root')); <|start_filename|>src/functions/index.js<|end_filename|> export * from "./boolean"; export * from "./color"; export * from "./math"; export * from "./number"; export * from "./types"; <|start_filename|>examples/Theme.js<|end_filename|> import React, {Component} from 'react'; import {ThemeProvider} from 'styled-components'; import lessToJs from 'less-vars-to-js'; import fs from 'fs'; const constants = lessToJs(fs.readFileSync(__dirname + "/variables.less", "utf8"), {resolveVariables: true, stripPrefix: true}); export default class extends Component { render() { return <ThemeProvider theme={constants}> {this.props.children} </ThemeProvider> } } <|start_filename|>test/Component/Condition.test.js<|end_filename|> import React from 'react'; import renderer from 'react-test-renderer'; import styled from 'styled-components'; import 'jest-styled-components'; test('Test and', () => { const Div = styled.div` opacity1: if((@errorText) and (@warning), 1, 0); opacity2: if(@errorText and @warning, 1, 0); `; expect(renderer.create(<Div/>).toJSON()).toMatchSnapshot(); expect(renderer.create(<Div errorText/>).toJSON()).toMatchSnapshot(); expect(renderer.create(<Div warning/>).toJSON()).toMatchSnapshot(); expect(renderer.create(<Div errorText warning/>).toJSON()).toMatchSnapshot(); }); test('Test or', () => { const Div = styled.div` opacity1: if((@errorText) or (@warning), 1, 0); opacity2: if(@errorText or @warning, 1, 0); `; expect(renderer.create(<Div/>).toJSON()).toMatchSnapshot(); expect(renderer.create(<Div errorText/>).toJSON()).toMatchSnapshot(); expect(renderer.create(<Div warning/>).toJSON()).toMatchSnapshot(); expect(renderer.create(<Div errorText warning/>).toJSON()).toMatchSnapshot(); }); test('Test =', () => { const Div = styled.div` opacity1: if(@a = @b, 1, 0); `; expect(renderer.create(<Div a={1} b={1}/>).toJSON()).toMatchSnapshot(); expect(renderer.create(<Div a={1} b={0}/>).toJSON()).toMatchSnapshot(); expect(renderer.create(<Div a="lala" b="lala"/>).toJSON()).toMatchSnapshot(); expect(renderer.create(<Div a="lala" b={false}/>).toJSON()).toMatchSnapshot(); }); test('Test greater than', () => { const Div = styled.div` opacity: if(luma(@bg) > 50%, 1, 0); opacity: if(luma(@bg) >= 50%, 1, 0); opacity: if(luma(@bg) < 50%, 1, 0); opacity: if(luma(@bg) <= 50%, 1, 0); `; expect(renderer.create(<Div bg="black"/>).toJSON()).toMatchSnapshot(); expect(renderer.create(<Div bg="white"/>).toJSON()).toMatchSnapshot(); }); test('If with function', () => { const Div = styled.div` cursor: if(@onClick, pointer); `; expect(renderer.create(<Div onClick={() => false}/>).toJSON()).toMatchSnapshot(); }); <|start_filename|>src/functions/number.js<|end_filename|> import VariableNode from "../tree/VariableNode"; import {convertNode as c} from "../tree/convert"; export const min = (...args) => { const min = arr => arr[arr.reduce((iMax, x, i) => parseFloat(x) < parseFloat(arr[iMax]) ? i : iMax, 0)]; return new VariableNode(`(${min})([${args.map(a => c(a)).join(", ")}])`); }; export const max = (...args) => { const max = arr => arr[arr.reduce((iMax, x, i) => parseFloat(x) > parseFloat(arr[iMax]) ? i : iMax, 0)]; return new VariableNode(`(${max})([${args.map(a => c(a)).join(", ")}])`); }; export const mod = (x, y) => { const apply = (x, y) => parseFloat(x) % parseFloat(y) + ('' + x).replace(/[\d.-]*/, ""); return new VariableNode(`(${apply})(${c(x)}, ${c(y)})`); }; export const pow = (x, y) => { const apply = (x, y) => Math.pow(parseFloat(x), parseFloat(y)) + ('' + x).replace(/[\d.-]*/, ""); return new VariableNode(`(${apply})(${c(x)}, ${c(y)})`); }; export const percentage = value => { return new VariableNode(`(parseFloat(${c(value)}) * 100) + "%"`); }; <|start_filename|>src/tree/Condition.js<|end_filename|> import {convertNode as c} from './convert'; import VariableNode from "./VariableNode"; export default class Condition { constructor(op, l, r, i, negate) { this.op = op.trim(); this.lvalue = l; this.rvalue = r; this._index = i; this.negate = negate; } accept(visitor) { this.lvalue = visitor.visit(this.lvalue); this.rvalue = visitor.visit(this.rvalue); } eval(context) { let a = this.lvalue.eval(context); let b = this.rvalue.eval(context); a = a.value ? a.value : c(a); b = b.value ? b.value : c(b); let result; switch (this.op) { case 'and': result = `${a} && ${b}`; break; case 'or': result = `${a} || ${b}`; break; case '=': if (b === "true") { result = `!!${a}`; } else { result = `${a} == ${b}`; } break; default: result = `${a} ${this.op} ${b}`; break; } if (this.negate) { return new VariableNode(`!${result}`); } else { return new VariableNode(result); } } } <|start_filename|>test/Component/Imports.test.js<|end_filename|> import React from 'react'; import renderer from 'react-test-renderer'; import styled, {css} from "styled-components"; import 'jest-styled-components'; test('Support import', () => { const Div = styled.div` @import "import.less"; color: @color; .foo; `; expect(renderer.create(<Div/>).toJSON()).toMatchSnapshot(); expect(renderer.create(<Div color="red"/>).toJSON()).toMatchSnapshot(); }); test('Support import reference', () => { const Div = styled.div` @import (reference) "import.less"; color: @color; .foo; `; expect(renderer.create(<Div/>).toJSON()).toMatchSnapshot(); expect(renderer.create(<Div color="red"/>).toJSON()).toMatchSnapshot(); }); <|start_filename|>src/tree/Negative.js<|end_filename|> import node from 'less/lib/less/tree/node'; import convert from './convert'; import VariableNode from './VariableNode'; export default class Negative extends node { constructor(node) { super(node); this.value = node; } eval(context) { return new VariableNode(`"-" + (${convert(this.value.name)})`); } } <|start_filename|>src/index.js<|end_filename|> import taggedTemplateExpressionVisitor from './visitors/taggedTemplateExpressionVisitor' export default babel => ({ visitor: { TaggedTemplateExpression(path, state) { taggedTemplateExpressionVisitor(path, state, babel); }, } }); <|start_filename|>test/Component/NestedImports/NestedImports.test.js<|end_filename|> import React from 'react'; import renderer from 'react-test-renderer'; import styled from 'styled-components'; import 'jest-styled-components'; test('#29, nested imports', () => { const Div = styled.div` @import "tmp.less"; @import (reference) "reference.less"; &.light { color: @text-color; background: @layout-sider-background-light; } &.dark { background: @layout-header-background; color: @layout-trigger-color; } `; expect(renderer.create(<Div/>).toJSON()).toMatchSnapshot(); }); <|start_filename|>test/Component/Functional.test.js<|end_filename|> import React from 'react'; import renderer from 'react-test-renderer'; import styled from 'styled-components'; import 'jest-styled-components'; test('Darkens the primary color 20%', () => { const Div = styled.div` color: darken(@primary, 20%); `; const tree = renderer.create(<Div primary="red"/>).toJSON(); expect(tree).toMatchSnapshot(); }); test('Darkens the colors in linear-gradient', () => { const Div = styled.div` background: linear-gradient(lighten(@start, 20%) 0%, darken(@end, 20%) 100%); `; const tree = renderer.create(<Div start="red" end="blue"/>).toJSON(); expect(tree).toMatchSnapshot(); }); <|start_filename|>src/functions/boolean.js<|end_filename|> import VariableNode from '../tree/VariableNode'; import {convertNode as c} from "../tree/convert"; export const boolean = condition => { return new VariableNode(`!!(${c(condition)})`); }; const _if = (condition, trueValue, falseValue) => { const flags = { cssFragment: true }; return new VariableNode(`(${c(condition)}) ? ${c(trueValue, flags)} : ${c(falseValue, flags)}`); }; export {_if as if}; <|start_filename|>test/Component/BaseImportRelative/BaseImport.test.js<|end_filename|> import React from 'react'; import renderer from 'react-test-renderer'; import styled from 'styled-components'; import 'jest-styled-components'; test('It should fall back to base import variables', () => { const Div = styled.div` color: @base-color; .base-mixin; `; expect(renderer.create(<Div/>).toJSON()).toMatchSnapshot(); }); <|start_filename|>src/functions/math.js<|end_filename|> import VariableNode from "../tree/VariableNode"; import {convertNode as c} from "../tree/convert"; const apply = (fn, n) => fn(parseFloat(n)) + ('' + n).replace(/[\d.-]*/, ""); const applyAngle = (fn, n, funit = "") => { const angle = { rad: 1, deg: Math.PI / 180, grad: Math.PI / 200, turn: Math.PI * 2, }; const unit = ('' + n).replace(/[\d.-]*/, "") || "rad"; return fn(parseFloat(n) * angle[unit]) + funit; }; export const ceil = value => { return new VariableNode(`(${apply})(Math.ceil, ${c(value)})`); }; export const floor = value => { return new VariableNode(`(${apply})(Math.floor, ${c(value)})`); }; export const sqrt = value => { return new VariableNode(`(${apply})(Math.sqrt, ${c(value)})`); }; export const abs = value => { return new VariableNode(`(${apply})(Math.abs, ${c(value)})`); }; export const tan = value => { return new VariableNode(`(${applyAngle})(Math.tan, ${c(value)})`); }; export const sin = value => { return new VariableNode(`(${applyAngle})(Math.sin, ${c(value)})`); }; export const cos = value => { return new VariableNode(`(${applyAngle})(Math.cos, ${c(value)})`); }; export const atan = value => { return new VariableNode(`(${applyAngle})(Math.atan, ${c(value)}, "rad")`); }; export const asin = value => { return new VariableNode(`(${applyAngle})(Math.asin, ${c(value)}, "rad")`); }; export const acos = value => { return new VariableNode(`(${applyAngle})(Math.acos, ${c(value)}, "rad")`); }; export const round = (value, fraction = {}) => { return new VariableNode(`(${apply})(num => num.toFixed(${fraction.value}), ${c(value)})`); }; <|start_filename|>test/Component/String.test.js<|end_filename|> import React from 'react'; import renderer from 'react-test-renderer'; import styled from 'styled-components'; import 'jest-styled-components'; test('String characters @url', () => { const Div = styled.div` background-image: url('images/lamp-post.png?v=1'); `; expect(renderer.create(<Div/>).toJSON()).toMatchSnapshot(); }); <|start_filename|>test/Component/Boolean.test.js<|end_filename|> import React from 'react'; import renderer from 'react-test-renderer'; import styled from 'styled-components'; import 'jest-styled-components'; test('Sets a complex variable in an if check', () => { const Div = styled.div` cursor: if(@disabled, not-allowed); `; const tree = renderer.create(<Div/>).toJSON(); expect(tree).toMatchSnapshot(); const tree2 = renderer.create(<Div disabled/>).toJSON(); expect(tree2).toMatchSnapshot(); }); test('Sets conditional margins', () => { const Div = styled.div` margin: if(@val, 6px); `; const tree = renderer.create(<Div/>).toJSON(); expect(tree).toMatchSnapshot(); const tree2 = renderer.create(<Div val/>).toJSON(); expect(tree2).toMatchSnapshot(); }); test('Sets conditional margins with variables', () => { const Div = styled.div` margin: if(@val, @t, @f); `; const tree = renderer.create(<Div t="20px" f="0px"/>).toJSON(); expect(tree).toMatchSnapshot(); const tree2 = renderer.create(<Div t="20px" f="0px" val/>).toJSON(); expect(tree2).toMatchSnapshot(); }); test('Sets color to the inverse of the bg luma', () => { const Div = styled.div` @bg: if(@checked, @navy, white); @bg-light: boolean(luma(@bg) > 50%); background: @bg; color: if(@bg-light, black, white); `; const tree = renderer.create(<Div navy="#001F3F" checked/>).toJSON(); expect(tree).toMatchSnapshot(); const tree2 = renderer.create(<Div navy="#001F3F"/>).toJSON(); expect(tree2).toMatchSnapshot(); });
gullitmiranda/styless
<|start_filename|>app/src/main/kotlin/com/yoavst/kotlin/Handler.kt<|end_filename|> package com.yoavst.kotlin import android.os.Handler import android.os.Message public fun Handler.post(action: () -> Unit): Boolean = post(Runnable(action)) public fun Handler.atFrontOfQueue(action: () -> Unit): Boolean = postAtFrontOfQueue(Runnable(action)) public fun Handler.atTime(uptimeMillis: Long, action: () -> Unit): Boolean = postAtTime(Runnable(action), uptimeMillis) public fun Handler.delayed(delayMillis: Long, action: () -> Unit): Boolean = postDelayed(Runnable(action), delayMillis) public fun handler(handleMessage: (Message) -> Boolean): Handler { return android.os.Handler { p0 -> if (p0 == null) false else handleMessage(p0) } }
yoavst/androidKotlin
<|start_filename|>app-preference-activity/src/main/java/com/github/pwittchen/prefser/app/preference/MainActivity.java<|end_filename|> /* * Copyright (C) 2015 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pwittchen.prefser.app.preference; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.widget.TextView; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import com.github.myapplication.R; import com.github.pwittchen.prefser.library.rx2.Prefser; import java.util.HashSet; import java.util.Set; public class MainActivity extends Activity { private Prefser prefser; @BindView(R.id.user_name) protected TextView tvUserName; @BindView(R.id.app_updates) protected TextView tvApplicationUpdates; @BindView(R.id.screen_on) protected TextView screenOn; @BindView(R.id.download_type) protected TextView tvDownloadType; @BindView(R.id.notification_type) protected TextView tvNotificationType; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); prefser = new Prefser(this); } @Override protected void onResume() { super.onResume(); readPreferences(); } private void readPreferences() { readUserName(); readApplicationUpdates(); readScreenOn(); readDownloadType(); readNotificationType(); } private void readUserName() { String userName = prefser.get("user_name", String.class, ""); String formattedText = String.format("username: %s", userName); tvUserName.setText(formattedText); } private void readApplicationUpdates() { Boolean applicationUpdates = prefser.get("application_updates", Boolean.class, false); String formattedText = String.format("app updates: %s", applicationUpdates.toString()); tvApplicationUpdates.setText(formattedText); } private void readScreenOn() { Boolean appUpdates = prefser.get("screen_on", Boolean.class, false); String formattedText = String.format("screen on: %s", appUpdates.toString()); screenOn.setText(formattedText); } private void readDownloadType() { String downloadTypeValue = prefser.get("download_type", String.class, "0"); String[] downloadEntries = getResources().getStringArray(R.array.download_entries); String downloadEntry = downloadEntries[Integer.parseInt(downloadTypeValue)]; String formattedText = String.format("download type: %s", downloadEntry); tvDownloadType.setText(formattedText); } private void readNotificationType() { Set<String> defaultValues = new HashSet<>(); Set<String> notificationTypeValues = prefser.getPreferences().getStringSet("notification_type", defaultValues); String[] notificationEntries = getResources().getStringArray(R.array.notification_entries); StringBuilder stringBuilder = new StringBuilder(); if (!notificationTypeValues.isEmpty()) { for (String value : notificationTypeValues) { stringBuilder.append(notificationEntries[Integer.parseInt(value)]); stringBuilder.append(", "); } stringBuilder.delete(stringBuilder.length() - 2, stringBuilder.length()); } String formattedText = String.format("notification type: %s", stringBuilder.toString()); tvNotificationType.setText(formattedText); } @OnClick(R.id.show_settings) public void onShowSettingsClicked() { Intent intent = new Intent(this, SettingsActivity.class); startActivity(intent); } } <|start_filename|>library/src/main/java/com/github/pwittchen/prefser/library/rx2/PreferencesAccessorsProvider.java<|end_filename|> /* * Copyright (C) 2017 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pwittchen.prefser.library.rx2; import android.content.SharedPreferences; import java.util.HashMap; import java.util.Map; class PreferencesAccessorsProvider implements AccessorsProvider { private final SharedPreferences preferences; private final SharedPreferences.Editor editor; private final Map<Class<?>, Accessor<?>> accessors = new HashMap<>(); PreferencesAccessorsProvider(SharedPreferences preferences, SharedPreferences.Editor editor) { Preconditions.checkNotNull(preferences, "preferences == null"); Preconditions.checkNotNull(editor, "editor == null"); this.preferences = preferences; this.editor = editor; createAccessors(); } @Override public Map<Class<?>, Accessor<?>> getAccessors() { return accessors; } private void createAccessors() { createBooleanAccessor(); createFloatAccessor(); createIntegerAccessor(); createLongAccessor(); createDoubleAccessor(); createStringAccessor(); } private void createBooleanAccessor() { accessors.put(Boolean.class, new Accessor<Boolean>() { @Override public Boolean get(String key, Boolean defaultValue) { return preferences.getBoolean(key, defaultValue); } @Override public void put(String key, Boolean value) { editor.putBoolean(key, value).apply(); } }); } private void createFloatAccessor() { accessors.put(Float.class, new Accessor<Float>() { @Override public Float get(String key, Float defaultValue) { return preferences.getFloat(key, defaultValue); } @Override public void put(String key, Float value) { editor.putFloat(key, value).apply(); } }); } private void createIntegerAccessor() { accessors.put(Integer.class, new Accessor<Integer>() { @Override public Integer get(String key, Integer defaultValue) { return preferences.getInt(key, defaultValue); } @Override public void put(String key, Integer value) { editor.putInt(key, value).apply(); } }); } private void createLongAccessor() { accessors.put(Long.class, new Accessor<Long>() { @Override public Long get(String key, Long defaultValue) { return preferences.getLong(key, defaultValue); } @Override public void put(String key, Long value) { editor.putLong(key, value).apply(); } }); } private void createDoubleAccessor() { accessors.put(Double.class, new Accessor<Double>() { @Override public Double get(String key, Double defaultValue) { return Double.valueOf(preferences.getString(key, String.valueOf(defaultValue))); } @Override public void put(String key, Double value) { editor.putString(key, String.valueOf(value)).apply(); } }); } private void createStringAccessor() { accessors.put(String.class, new Accessor<String>() { @Override public String get(String key, String defaultValue) { return preferences.getString(key, String.valueOf(defaultValue)); } @Override public void put(String key, String value) { editor.putString(key, String.valueOf(value)).apply(); } }); } } <|start_filename|>library/src/test/java/com/github/pwittchen/prefser/library/rx2/PrefserTest.java<|end_filename|> /* * Copyright (C) 2015 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pwittchen.prefser.library.rx2; import android.annotation.TargetApi; import android.content.Context; import android.content.SharedPreferences; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Config; import static com.google.common.truth.Truth.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public final class PrefserTest { private static final String GIVEN_KEY = "givenKey"; private static final String GIVEN_STRING_VALUE = "givenStringValue"; private static final String KEY_WHICH_DOES_NOT_EXIST = "keyWhichDoesNotExist"; private Prefser prefser; private class CustomClass { private int valueOne; private String valueTwo; private CustomClass(int valueOne, String valueTwo) { this.valueOne = valueOne; this.valueTwo = valueTwo; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CustomClass that = (CustomClass) o; if (valueOne != that.valueOne) { return false; } return valueTwo != null ? valueTwo.equals(that.valueTwo) : that.valueTwo == null; } @Override public int hashCode() { int result = valueOne; result = 31 * result + (valueTwo != null ? valueTwo.hashCode() : 0); return result; } } @Before public void setUp() { final Context context = RuntimeEnvironment.application.getApplicationContext(); prefser = new Prefser(context); prefser.clear(); } @After public void tearDown() { prefser.clear(); } @Test public void testPrefserShouldNotBeNull() { // given: prefser declaration // when: prefser initialization in setUp() method // then assertThat(prefser).isNotNull(); } @Test public void testPrefserShouldNotBeNullWhenCreatedWithPreferences() { // given SharedPreferences sharedPreferences = mock(SharedPreferences.class); SharedPreferences.Editor editor = mock(SharedPreferences.Editor.class); when(sharedPreferences.edit()).thenReturn(editor); // when Prefser customPrefser = new Prefser(sharedPreferences); // then assertThat(customPrefser).isNotNull(); } @Test public void testPrefserWithJsonConverterShouldNotBeNull() { // given JsonConverter jsonConverter = mock(JsonConverter.class); Context context = RuntimeEnvironment.application.getApplicationContext(); // when Prefser customPrefser = new Prefser(context, jsonConverter); // then assertThat(customPrefser).isNotNull(); } @Test(expected = NullPointerException.class) public void testPrefserWithJsonConverterShouldThrowAnExceptionWhenConverterIsNull() { // given JsonConverter jsonConverter = null; Context context = RuntimeEnvironment.application.getApplicationContext(); // when new Prefser(context, jsonConverter); // then throw an exception } @Test public void testPrefserWithSharedPreferencesAndJsonConverterShouldNotBeNull() { // given JsonConverter jsonConverter = mock(JsonConverter.class); SharedPreferences sharedPreferences = mock(SharedPreferences.class); SharedPreferences.Editor editor = mock(SharedPreferences.Editor.class); when(sharedPreferences.edit()).thenReturn(editor); // when Prefser customPrefser = new Prefser(sharedPreferences, jsonConverter); // then assertThat(customPrefser).isNotNull(); } @Test(expected = NullPointerException.class) public void testPrefserWithSharedPreferencesShouldThrowAnExceptionWhenConverterIsNull() { // given JsonConverter jsonConverter = null; SharedPreferences sharedPreferences = mock(SharedPreferences.class); // when new Prefser(sharedPreferences, jsonConverter); // then throw an exception } @Test public void testPreferencesShouldNotBeNull() { // given prefser.clear(); // when SharedPreferences preferences = prefser.getPreferences(); // then assertThat(preferences).isNotNull(); } @Test public void testContains() throws Exception { // given prefser.clear(); String givenValue = GIVEN_STRING_VALUE; String givenKey = GIVEN_KEY; // when prefser.put(givenKey, givenValue); // then assertThat(prefser.contains(givenKey)).isTrue(); prefser.remove(givenKey); assertThat(prefser.contains(givenKey)).isFalse(); } @Test public void testSize() throws Exception { // given prefser.clear(); String keyToRemove = "key1"; // when prefser.put(keyToRemove, 1); prefser.put("key2", 2); prefser.put("key3", 3); // then assertThat(prefser.size()).isEqualTo(3); prefser.remove(keyToRemove); assertThat(prefser.size()).isEqualTo(2); prefser.clear(); assertThat(prefser.size()).isEqualTo(0); } @Test public void testRemove() throws Exception { // given String givenKey = GIVEN_KEY; prefser.put(givenKey, 1); // when assertThat(prefser.contains(givenKey)).isTrue(); prefser.remove(givenKey); // then assertThat(prefser.contains(givenKey)).isFalse(); } @Test public void testRemoveShouldNotCauseErrorWhileRemovingKeyWhichDoesNotExist() { // given prefser.clear(); String keyWhichDoesNotExist = KEY_WHICH_DOES_NOT_EXIST; // when prefser.remove(keyWhichDoesNotExist); // then assertThat(prefser.contains(keyWhichDoesNotExist)).isFalse(); } @Test(expected = NullPointerException.class) public void testShouldThrowAnExceptionWhileRemovingNullKey() { // given: nothing // when prefser.remove(null); // then should throw an exception } @Test public void testClear() throws Exception { // given prefser.clear(); prefser.put("key1", 1); prefser.put("key2", 2); prefser.put("key3", 3); // when assertThat(prefser.size()).isEqualTo(3); prefser.clear(); // then assertThat(prefser.size()).isEqualTo(0); } @Test public void testPutBoolean() throws Exception { // given prefser.clear(); String givenKey = GIVEN_KEY; Boolean givenValue = true; Boolean defaultValue = false; // when prefser.put(givenKey, givenValue); // then Boolean readValue = prefser.get(givenKey, Boolean.class, defaultValue); assertThat(givenValue).isEqualTo(readValue); prefser.remove(givenKey); } @Test public void testPutBooleanPrimitive() throws Exception { // given prefser.clear(); String givenKey = GIVEN_KEY; boolean givenValue = true; boolean defaultValue = false; // when prefser.put(givenKey, givenValue); // then boolean readValue = prefser.get(givenKey, Boolean.class, defaultValue); assertThat(givenValue).isEqualTo(readValue); prefser.remove(givenKey); } @Test public void testPutFloat() throws Exception { // given prefser.clear(); String givenKey = GIVEN_KEY; Float givenValue = 41f; Float defaultValue = 42f; // when prefser.put(givenKey, givenValue); // then Float readValue = prefser.get(givenKey, Float.class, defaultValue); assertThat(givenValue).isEqualTo(readValue); prefser.remove(givenKey); } @Test public void testPutFloatPrimitive() throws Exception { // given prefser.clear(); String givenKey = GIVEN_KEY; float givenValue = 41f; float defaultValue = 42f; // when prefser.put(givenKey, givenValue); // then float readValue = prefser.get(givenKey, Float.class, defaultValue); assertThat(givenValue).isEqualTo(readValue); prefser.remove(givenKey); } @Test public void testPutInteger() throws Exception { // given prefser.clear(); String givenKey = GIVEN_KEY; Integer givenValue = 42; Integer defaultValue = 43; // when prefser.put(givenKey, givenValue); // then Integer readValue = prefser.get(givenKey, Integer.class, defaultValue); assertThat(givenValue).isEqualTo(readValue); prefser.remove(givenKey); } @Test public void testPutIntegerPrimitive() throws Exception { // given prefser.clear(); String givenKey = GIVEN_KEY; int givenValue = 42; int defaultValue = 43; // when prefser.put(givenKey, givenValue); // then int readValue = prefser.get(givenKey, Integer.class, defaultValue); assertThat(givenValue).isEqualTo(readValue); prefser.remove(givenKey); } @Test public void testPutLong() throws Exception { // given prefser.clear(); String givenKey = GIVEN_KEY; Long givenValue = 43L; Long defaultValue = 44L; // when prefser.put(givenKey, givenValue); // then Long readValue = prefser.get(givenKey, Long.class, defaultValue); assertThat(givenValue).isEqualTo(readValue); prefser.remove(givenKey); } @Test public void testPutLongPrimitive() throws Exception { // given prefser.clear(); String givenKey = GIVEN_KEY; long givenValue = 43L; long defaultValue = 44L; // when prefser.put(givenKey, givenValue); // then long readValue = prefser.get(givenKey, Long.class, defaultValue); assertThat(givenValue).isEqualTo(readValue); prefser.remove(givenKey); } @Test public void testPutDouble() throws Exception { // given prefser.clear(); String givenKey = GIVEN_KEY; Double givenValue = 44.5; Double defaultValue = 46.7; // when prefser.put(givenKey, givenValue); // then Double readValue = prefser.get(givenKey, Double.class, defaultValue); assertThat(givenValue).isEqualTo(readValue); prefser.remove(givenKey); } @Test public void testPutDoublePrimitive() throws Exception { // given prefser.clear(); String givenKey = GIVEN_KEY; double givenValue = 44.5; double defaultValue = 48.3; // when prefser.put(givenKey, givenValue); // then double readValue = prefser.get(givenKey, Double.class, defaultValue); assertThat(givenValue).isEqualTo(readValue); prefser.remove(givenKey); } @Test public void testPutString() throws Exception { // given prefser.clear(); String givenKey = GIVEN_KEY; String givenValue = "sampleValueExplicit"; String defaultValue = "sampleDefaultValue"; // when prefser.put(givenKey, givenValue); // then String readValue = prefser.get(givenKey, String.class, defaultValue); assertThat(givenValue).isEqualTo(readValue); prefser.remove(givenKey); } @Test public void testPutCustomObject() throws Exception { // given prefser.clear(); String givenKey = GIVEN_KEY; CustomClass givenObject = new CustomClass(23, "someText"); CustomClass defaultObject = new CustomClass(67, "defaultText"); // when prefser.put(givenKey, givenObject); // then CustomClass readObject = prefser.get(givenKey, CustomClass.class, defaultObject); assertThat(givenObject).isEqualTo(readObject); prefser.remove(givenKey); } @Test public void testPutListOfBooleans() throws Exception { // given prefser.clear(); String givenKey = GIVEN_KEY; List<Boolean> booleans = Arrays.asList(true, false, true); List<Boolean> defaultBooleans = Arrays.asList(false, false, false); // when prefser.put(givenKey, booleans); // then TypeToken<List<Boolean>> typeToken = new TypeToken<List<Boolean>>() { }; List<Boolean> readObject = prefser.get(givenKey, typeToken, defaultBooleans); assertThat(booleans).isEqualTo(readObject); prefser.remove(givenKey); } @Test public void testPutListOfFloats() throws Exception { // given prefser.clear(); String givenKey = GIVEN_KEY; List<Float> floats = Arrays.asList(1.0f, 2.1f, 3.4f); List<Float> defaultFloats = Arrays.asList(0f, 0f, 0f); // when prefser.put(givenKey, floats); // then TypeToken<List<Float>> typeToken = new TypeToken<List<Float>>() { }; List<Float> readObject = prefser.get(givenKey, typeToken, defaultFloats); assertThat(floats).isEqualTo(readObject); prefser.remove(givenKey); } @Test public void testPutListOfIntegers() throws Exception { // given prefser.clear(); String givenKey = GIVEN_KEY; List<Integer> integers = Arrays.asList(1, 2, 3); List<Integer> defaultIntegers = Arrays.asList(0, 0, 0); // when prefser.put(givenKey, integers); // then TypeToken<List<Integer>> typeToken = new TypeToken<List<Integer>>() { }; List<Integer> readObject = prefser.get(givenKey, typeToken, defaultIntegers); assertThat(integers).isEqualTo(readObject); prefser.remove(givenKey); } @Test public void testPutListOfLongs() throws Exception { // given prefser.clear(); String givenKey = GIVEN_KEY; List<Long> longs = Arrays.asList(1L, 2L, 3L); List<Long> defaultLongs = Arrays.asList(0L, 0L, 0L); // when prefser.put(givenKey, longs); // then TypeToken<List<Long>> typeToken = new TypeToken<List<Long>>() { }; List<Long> readObject = prefser.get(givenKey, typeToken, defaultLongs); assertThat(longs).isEqualTo(readObject); prefser.remove(givenKey); } @Test public void testPutListOfDoubles() throws Exception { // given prefser.clear(); String givenKey = GIVEN_KEY; List<Double> doubles = Arrays.asList(4.0, 5.1, 6.2); List<Double> defaultDoubles = Arrays.asList(4.0, 5.1, 6.2); // when prefser.put(givenKey, doubles); TypeToken<List<Double>> typeToken = new TypeToken<List<Double>>() { }; List<Double> readObject = prefser.get(givenKey, typeToken, defaultDoubles); // then assertThat(readObject).isEqualTo(doubles); prefser.remove(givenKey); } @Test public void testPutListOfStrings() throws Exception { // given prefser.clear(); String givenKey = GIVEN_KEY; List<String> strings = Arrays.asList("yet", "another", "list"); List<String> defaultStrings = Arrays.asList("default", "string", "values"); // when prefser.put(givenKey, strings); TypeToken<List<String>> typeToken = new TypeToken<List<String>>() { }; List<String> readObject = prefser.get(givenKey, typeToken, defaultStrings); // then assertThat(readObject).isEqualTo(strings); prefser.remove(givenKey); } @Test public void testPutListOfCustomObjects() throws Exception { // given prefser.clear(); String givenKey = GIVEN_KEY; CustomClass defaultCustomObject = new CustomClass(0, "zero"); List<CustomClass> customObjects = Arrays.asList(new CustomClass(1, "this is one"), new CustomClass(2, "this is two"), new CustomClass(3, "three")); List<CustomClass> defaultCustomObjects = Arrays.asList(defaultCustomObject, defaultCustomObject, defaultCustomObject); // when prefser.put(givenKey, customObjects); TypeToken<List<CustomClass>> typeToken = new TypeToken<List<CustomClass>>() { }; List<CustomClass> readObject = prefser.get(givenKey, typeToken, defaultCustomObjects); // then assertThat(readObject).isEqualTo(customObjects); prefser.remove(givenKey); } @Test public void testPutArrayOfBooleans() { // given prefser.clear(); String givenKey = GIVEN_KEY; Boolean[] booleans = new Boolean[] { true, false, true }; Boolean[] defaultArray = new Boolean[] { false, false, false }; // when prefser.put(givenKey, booleans); Boolean[] readObject = prefser.get(givenKey, Boolean[].class, defaultArray); // then assertThat(readObject[0]).isEqualTo(booleans[0]); assertThat(readObject[1]).isEqualTo(booleans[1]); assertThat(readObject[2]).isEqualTo(booleans[2]); prefser.remove(givenKey); } @Test public void testPutArrayOfFloats() { // given prefser.clear(); String givenKey = GIVEN_KEY; Float[] floats = new Float[] { 1f, 2f, 3f }; Float[] defaultArray = new Float[] { 1f, 1f, 1f }; // when prefser.put(givenKey, floats); Float[] readObject = prefser.get(givenKey, Float[].class, defaultArray); // then assertThat(readObject[0]).isEqualTo(floats[0]); assertThat(readObject[1]).isEqualTo(floats[1]); assertThat(readObject[2]).isEqualTo(floats[2]); prefser.remove(givenKey); } @Test public void testPutArrayOfInts() { // given prefser.clear(); String givenKey = GIVEN_KEY; Integer[] integers = new Integer[] { 1, 2, 3 }; Integer[] defaultArray = new Integer[] { 0, 0, 0 }; // when prefser.put(givenKey, integers); Integer[] readObject = prefser.get(givenKey, Integer[].class, defaultArray); // then assertThat(readObject[0]).isEqualTo(integers[0]); assertThat(readObject[1]).isEqualTo(integers[1]); assertThat(readObject[2]).isEqualTo(integers[2]); prefser.remove(givenKey); } @Test public void testPutArrayOfLongs() { // given prefser.clear(); String givenKey = GIVEN_KEY; Long[] longs = new Long[] { 1L, 2L, 3L }; Long[] defaultArray = new Long[] { 1L, 1L, 1L }; // when prefser.put(givenKey, longs); Long[] readObject = prefser.get(givenKey, Long[].class, defaultArray); // then assertThat(readObject[0]).isEqualTo(longs[0]); assertThat(readObject[1]).isEqualTo(longs[1]); assertThat(readObject[2]).isEqualTo(longs[2]); prefser.remove(givenKey); } @Test public void testPutArrayOfDoubles() { // given prefser.clear(); String givenKey = GIVEN_KEY; Double[] doubles = new Double[] { 1.0, 2.3, 4.5 }; Double[] defaultArray = new Double[] { 1.0, 1.0, 1.0 }; // when prefser.put(givenKey, doubles); Double[] readObject = prefser.get(givenKey, Double[].class, defaultArray); // then assertThat(readObject[0]).isEqualTo(doubles[0]); assertThat(readObject[1]).isEqualTo(doubles[1]); assertThat(readObject[2]).isEqualTo(doubles[2]); prefser.remove(givenKey); } @Test public void testPutArrayOfStrings() { // given prefser.clear(); String givenKey = GIVEN_KEY; String[] strings = new String[] { "hey", "I am", "array of strings!" }; String[] defaultArray = new String[] { "", "", "" }; // when prefser.put(givenKey, strings); String[] readObject = prefser.get(givenKey, String[].class, defaultArray); // then assertThat(readObject[0]).isEqualTo(strings[0]); assertThat(readObject[1]).isEqualTo(strings[1]); assertThat(readObject[2]).isEqualTo(strings[2]); prefser.remove(givenKey); } @Test public void testPutArrayOfCustomObjects() { // given prefser.clear(); String givenKey = GIVEN_KEY; CustomClass defaultCustomObject = new CustomClass(1, ""); CustomClass[] customClassesArray = new CustomClass[] { new CustomClass(1, "first"), new CustomClass(2, "second"), new CustomClass(3, "third") }; CustomClass[] defaultCustomClassesArray = new CustomClass[] { defaultCustomObject, defaultCustomObject, defaultCustomObject }; // when prefser.put(givenKey, customClassesArray); CustomClass[] readObject = prefser.get(givenKey, CustomClass[].class, defaultCustomClassesArray); // then assertThat(readObject[0]).isEqualTo(customClassesArray[0]); assertThat(readObject[1]).isEqualTo(customClassesArray[1]); assertThat(readObject[2]).isEqualTo(customClassesArray[2]); prefser.remove(givenKey); } @Test @TargetApi(value = 11) @SuppressWarnings("deprecation of assertThat for Java Collections") public void testPutSetOfStrings() { // given prefser.clear(); Set<String> strings = new HashSet<>(Arrays.asList("one", "two", "three")); Set<String> defaultStrings = new HashSet<>(Arrays.asList("this", "is", "default")); String givenKey = GIVEN_KEY; // when // we put set of string in a "classical way" prefser.getPreferences().edit().putStringSet(givenKey, strings).apply(); // then // we read set of string in a "classical way" Set<String> readObject = prefser.getPreferences().getStringSet(givenKey, defaultStrings); assertThat(readObject).isEqualTo(strings); prefser.remove(givenKey); } @Test public void testPutSetOfDoubles() { // given prefser.clear(); Set<Double> doubles = new HashSet<>(Arrays.asList(1.2, 2.3, 3.0)); Set<Double> defaultDoubles = new HashSet<>(Arrays.asList(1.0, 1.0, 1.0)); String givenKey = GIVEN_KEY; // when prefser.put(givenKey, doubles); // then TypeToken<Set<Double>> typeToken = new TypeToken<Set<Double>>() { }; Set<Double> readObject = prefser.get(givenKey, typeToken, defaultDoubles); assertThat(readObject).isEqualTo(doubles); assertThat(readObject).isInstanceOf(Set.class); prefser.remove(givenKey); } @Test public void testGetDefaultBoolean() { // given prefser.clear(); String keyWhichDoesNotExist = KEY_WHICH_DOES_NOT_EXIST; boolean defaultValue = true; // when boolean readValue = prefser.get(keyWhichDoesNotExist, Boolean.class, defaultValue); // then assertThat(readValue).isEqualTo(defaultValue); } @Test public void testGetDefaultFloat() { // given prefser.clear(); String keyWhichDoesNotExist = KEY_WHICH_DOES_NOT_EXIST; float defaultValue = 42f; // when float readValue = prefser.get(keyWhichDoesNotExist, Float.class, defaultValue); // then assertThat(readValue).isEqualTo(defaultValue); } @Test public void testGetDefaultInteger() { // given prefser.clear(); String keyWhichDoesNotExist = KEY_WHICH_DOES_NOT_EXIST; int defaultValue = 43; // when int readValue = prefser.get(keyWhichDoesNotExist, Integer.class, defaultValue); // then assertThat(readValue).isEqualTo(defaultValue); } @Test public void testGetDefaultLong() { // given prefser.clear(); String keyWhichDoesNotExist = KEY_WHICH_DOES_NOT_EXIST; long defaultValue = 44L; // when long readValue = prefser.get(keyWhichDoesNotExist, Long.class, defaultValue); // then assertThat(readValue).isEqualTo(defaultValue); } @Test public void testGetDefaultDouble() { // given prefser.clear(); String keyWhichDoesNotExist = KEY_WHICH_DOES_NOT_EXIST; double defaultValue = 45.6; // when double readValue = prefser.get(keyWhichDoesNotExist, Double.class, defaultValue); // then assertThat(readValue).isEqualTo(defaultValue); } @Test public void testGetDefaultString() { // given prefser.clear(); String keyWhichDoesNotExist = KEY_WHICH_DOES_NOT_EXIST; String defaultValue = "default string value"; // when String readValue = prefser.get(keyWhichDoesNotExist, String.class, defaultValue); // then assertThat(readValue).isEqualTo(defaultValue); } @Test public void testGetDefaultCustomObject() { // given prefser.clear(); String keyWhichDoesNotExist = KEY_WHICH_DOES_NOT_EXIST; CustomClass defaultValue = new CustomClass(23, "string in default object"); // when CustomClass readValue = prefser.get(keyWhichDoesNotExist, CustomClass.class, defaultValue); // then assertThat(readValue).isEqualTo(defaultValue); } @Test public void testGetDefaultListOfBooleans() { // given prefser.clear(); String keyWhichDoesNotExist = KEY_WHICH_DOES_NOT_EXIST; List<Boolean> defaultValue = Arrays.asList(true, false, true); // when TypeToken<List<Boolean>> typeToken = new TypeToken<List<Boolean>>() { }; List<Boolean> readValue = prefser.get(keyWhichDoesNotExist, typeToken, defaultValue); // then assertThat(readValue).isEqualTo(defaultValue); } @Test public void testGetDefaultListOfFloats() { // given prefser.clear(); String keyWhichDoesNotExist = KEY_WHICH_DOES_NOT_EXIST; List<Float> defaultValue = Arrays.asList(1f, 2f, 3f); // when TypeToken<List<Float>> typeToken = new TypeToken<List<Float>>() { }; List<Float> readValue = prefser.get(keyWhichDoesNotExist, typeToken, defaultValue); // then assertThat(readValue).isEqualTo(defaultValue); } @Test public void testGetDefaultListOfIntegers() { // given prefser.clear(); String keyWhichDoesNotExist = KEY_WHICH_DOES_NOT_EXIST; List<Integer> defaultValue = new ArrayList<>(Arrays.asList(1, 2, 3)); // when TypeToken<List<Integer>> typeToken = new TypeToken<List<Integer>>() { }; List<Integer> readValue = prefser.get(keyWhichDoesNotExist, typeToken, defaultValue); // then assertThat(readValue).isEqualTo(defaultValue); } @Test public void testGetDefaultListOfLongs() { // given prefser.clear(); String keyWhichDoesNotExist = KEY_WHICH_DOES_NOT_EXIST; List<Long> defaultValue = new ArrayList<>(Arrays.asList(1L, 2L, 3L)); // when TypeToken<List<Long>> typeToken = new TypeToken<List<Long>>() { }; List<Long> readValue = prefser.get(keyWhichDoesNotExist, typeToken, defaultValue); // then assertThat(readValue).isEqualTo(defaultValue); } @Test public void testGetDefaultListOfDoubles() { // given prefser.clear(); String keyWhichDoesNotExist = KEY_WHICH_DOES_NOT_EXIST; List<Double> defaultValue = new ArrayList<>(Arrays.asList(1.2, 2.3, 3.4)); // when TypeToken<List<Double>> typeToken = new TypeToken<List<Double>>() { }; List<Double> readValue = prefser.get(keyWhichDoesNotExist, typeToken, defaultValue); // then assertThat(readValue).isEqualTo(defaultValue); } @Test public void testGetDefaultListOfStrings() { // given prefser.clear(); String keyWhichDoesNotExist = KEY_WHICH_DOES_NOT_EXIST; List<String> defaultValue = new ArrayList<>(Arrays.asList("value one", " value two", " value three")); // when TypeToken<List<String>> typeToken = new TypeToken<List<String>>() { }; List<String> readValue = prefser.get(keyWhichDoesNotExist, typeToken, defaultValue); // then assertThat(readValue).isEqualTo(defaultValue); } @Test public void testGetDefaultListOfCustomObjects() { // given prefser.clear(); String keyWhichDoesNotExist = KEY_WHICH_DOES_NOT_EXIST; CustomClass defaultCustomObject = new CustomClass(0, "zero"); List<CustomClass> defaultObjects = Arrays.asList(defaultCustomObject, defaultCustomObject, defaultCustomObject); // when TypeToken<List<CustomClass>> typeToken = new TypeToken<List<CustomClass>>() { }; List<CustomClass> readValue = prefser.get(keyWhichDoesNotExist, typeToken, defaultObjects); // then assertThat(readValue).isEqualTo(defaultObjects); } @Test public void testGetDefaultArrayOfBooleans() { // given prefser.clear(); String keyWhichDoesNotExist = KEY_WHICH_DOES_NOT_EXIST; Boolean[] defaultValue = new Boolean[] { true, false, true }; // when Boolean[] readValue = prefser.get(keyWhichDoesNotExist, Boolean[].class, defaultValue); // then assertThat(readValue).isEqualTo(defaultValue); } @Test public void testGetDefaultArrayOfFloats() { // given prefser.clear(); String keyWhichDoesNotExist = KEY_WHICH_DOES_NOT_EXIST; Float[] defaultValue = new Float[] { 1f, 2f, 3f }; // when Float[] readValue = prefser.get(keyWhichDoesNotExist, Float[].class, defaultValue); // then assertThat(readValue).isEqualTo(defaultValue); } @Test public void testGetDefaultArrayOfIntegers() { // given prefser.clear(); String keyWhichDoesNotExist = KEY_WHICH_DOES_NOT_EXIST; Integer[] defaultValue = new Integer[] { 2, 3, 4 }; // when Integer[] readValue = prefser.get(keyWhichDoesNotExist, Integer[].class, defaultValue); // then assertThat(readValue).isEqualTo(defaultValue); } @Test public void testGetDefaultArrayOfLongs() { // given prefser.clear(); String keyWhichDoesNotExist = KEY_WHICH_DOES_NOT_EXIST; Long[] defaultValue = new Long[] { 3L, 4L, 5L }; // when Long[] readValue = prefser.get(keyWhichDoesNotExist, Long[].class, defaultValue); // then assertThat(readValue).isEqualTo(defaultValue); } @Test public void testGetDefaultArrayOfDoubles() { // given prefser.clear(); String keyWhichDoesNotExist = KEY_WHICH_DOES_NOT_EXIST; Double[] defaultValue = new Double[] { 1.2, 3.0, 4.5 }; // when Double[] readValue = prefser.get(keyWhichDoesNotExist, Double[].class, defaultValue); // then assertThat(readValue).isEqualTo(defaultValue); } @Test public void testGetDefaultArrayOfStrings() { // given prefser.clear(); String keyWhichDoesNotExist = KEY_WHICH_DOES_NOT_EXIST; String[] defaultValue = new String[] { "first", "next", "another one" }; // when String[] readValue = prefser.get(keyWhichDoesNotExist, String[].class, defaultValue); // then assertThat(readValue).isEqualTo(defaultValue); } @Test public void testGetDefaultArrayOfCustomObjects() { // given prefser.clear(); String keyWhichDoesNotExist = KEY_WHICH_DOES_NOT_EXIST; CustomClass[] defaultValue = new CustomClass[] { new CustomClass(1, "Hey"), new CustomClass(2, "Dude"), new CustomClass(3, "Don't make it bad") }; // when CustomClass[] readValue = prefser.get(keyWhichDoesNotExist, CustomClass[].class, defaultValue); // then assertThat(readValue).isEqualTo(defaultValue); } @Test(expected = NullPointerException.class) public void testShouldThrownAnExceptionWhenPreferencesAreNull() { // given SharedPreferences sharedPreferences = null; // when new Prefser(sharedPreferences); // then // throw an exception } @Test(expected = NullPointerException.class) public void testShouldThrowAnExceptionWhenKeyForGetIsNull() { // given String key = null; Class<String> classOfT = String.class; // when prefser.get(key, classOfT, ""); // then // throw an exception } @Test(expected = NullPointerException.class) public void testShouldThrowAnExceptionWhenClassOfTForGetIsNull() { // given String key = GIVEN_KEY; Class classOfT = null; prefser.put(key, GIVEN_STRING_VALUE); // when prefser.get(key, classOfT, ""); // then // throw an exception } @Test(expected = NullPointerException.class) public void testShouldThrowAnExceptionWhenKeyForGetWithDefaultValueIsNull() { // given String key = null; Class<String> classOfT = String.class; String defaultValue = "some default value"; // when prefser.get(key, classOfT, defaultValue); // then // throw an exception } @Test(expected = NullPointerException.class) public void testShouldThrowAnExceptionWhenClassOfTForGetWithDefaultValueIsNull() { // given String key = GIVEN_KEY; Class<String> classOfT = null; String defaultValue = "some default value"; // when prefser.get(key, classOfT, defaultValue); // then // throw an exception } @Test(expected = NullPointerException.class) public void testPutShouldThrowAnExceptionWhenKeyIsNullForPut() { // given String key = null; String value = GIVEN_STRING_VALUE; // when prefser.put(key, value); // then // throw an exception } @Test(expected = NullPointerException.class) public void testPutShouldThrowAnExceptionWhenValueIsNullForPut() { // given String key = GIVEN_KEY; String value = null; // when prefser.put(key, value); // then // throw an exception } @Test(expected = NullPointerException.class) public void testPutShouldThrowAnExceptionWhenKeyAndValueAreNullForPut() { // given String key = null; String value = null; // when prefser.put(key, value); // then // throw an exception } @Test(expected = NullPointerException.class) public void testPutShouldThrowAnExceptionWhenKeyIsNullForRemove() { // given String key = null; // when prefser.remove(key); // then // throw an exception } @Test public void testGetShouldReturnNullForStringType() { // given prefser.clear(); String keyWhichDoesNotExist = KEY_WHICH_DOES_NOT_EXIST; // when String value = prefser.get(keyWhichDoesNotExist, String.class, null); // then assertThat(value).isNull(); } } <|start_filename|>app-many-observables/src/main/java/com/github/pwittchen/prefser/app/manyobservables/MainActivity.java<|end_filename|> /* * Copyright (C) 2015 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pwittchen.prefser.app.manyobservables; import android.app.Activity; import android.os.Bundle; import android.widget.EditText; import android.widget.Toast; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import com.github.pwittchen.prefser.library.rx2.Prefser; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.schedulers.Schedulers; public class MainActivity extends Activity { private final static String EMPTY_STRING = ""; private final static String MY_KEY_ONE = "MY_KEY_ONE"; private final static String MY_KEY_TWO = "MY_KEY_TWO"; private final static String MY_KEY_THREE = "MY_KEY_THREE"; private Prefser prefser; private Disposable subscriptionOne; private Disposable subscriptionTwo; private Disposable subscriptionThree; @BindView(R.id.value_one) protected EditText valueOne; @BindView(R.id.value_two) protected EditText valueTwo; @BindView(R.id.value_three) protected EditText valueThree; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); prefser = new Prefser(this); } @Override protected void onResume() { super.onResume(); createSubscriptionOne(); createSubscriptionTwo(); createSubscriptionThree(); } @Override protected void onPause() { super.onPause(); if (!subscriptionOne.isDisposed()) { subscriptionOne.dispose(); } if (!subscriptionTwo.isDisposed()) { subscriptionTwo.dispose(); } if (!subscriptionThree.isDisposed()) { subscriptionThree.dispose(); } } private void createSubscriptionOne() { subscriptionOne = prefser.getAndObserve(MY_KEY_ONE, String.class, EMPTY_STRING) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(value -> { valueOne.setText(value); showToast(value); }); } private void createSubscriptionTwo() { subscriptionTwo = prefser.getAndObserve(MY_KEY_TWO, String.class, EMPTY_STRING) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(value -> { valueTwo.setText(value); showToast(value); }); } private void createSubscriptionThree() { subscriptionThree = prefser.getAndObserve(MY_KEY_THREE, String.class, EMPTY_STRING) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(value -> { valueThree.setText(value); showToast(value); }); } private void showToast(String message) { if (message.equals(EMPTY_STRING)) { message = "empty"; } String formattedMessage = String.format("value is %s", message); Toast.makeText(MainActivity.this, formattedMessage, Toast.LENGTH_SHORT).show(); } @OnClick(R.id.save) public void onSaveClicked() { prefser.put(MY_KEY_ONE, valueOne.getText().toString()); prefser.put(MY_KEY_TWO, valueTwo.getText().toString()); prefser.put(MY_KEY_THREE, valueThree.getText().toString()); } } <|start_filename|>library/src/test/java/com/github/pwittchen/prefser/library/rx2/utils/RecordingObserver.java<|end_filename|> /* * Copyright (C) 2015 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pwittchen.prefser.library.rx2.utils; import android.util.Log; import io.reactivex.Observer; import io.reactivex.annotations.NonNull; import io.reactivex.disposables.Disposable; import java.util.NoSuchElementException; import java.util.concurrent.BlockingDeque; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.TimeUnit; import static com.google.common.truth.Truth.assertThat; /** * This class is taken from RxBinding (former NotRxAndroid) project by <NAME> * Original source of this file can be found at: * https://github.com/JakeWharton/RxBinding (former: NotRxAndroid) */ public final class RecordingObserver<T> implements Observer<T> { private static final String TAG = "RecordingObserver"; private final BlockingDeque<Object> events = new LinkedBlockingDeque<>(); @Override public void onError(Throwable e) { Log.v(TAG, "onError", e); events.addLast(new OnError(e)); } @Override public void onComplete() { Log.v(TAG, "onCompleted"); events.addLast(new OnCompleted()); } @Override public void onSubscribe(@NonNull Disposable d) { Log.v(TAG, "onSubscribe"); } @Override public void onNext(T t) { Log.v(TAG, "onNext " + t); events.addLast(new OnNext(t)); } private <E> E takeEvent(Class<E> wanted) { Object event; try { event = events.pollFirst(1, TimeUnit.SECONDS); } catch (InterruptedException e) { throw new RuntimeException(e); } if (event == null) { throw new NoSuchElementException( "No event found while waiting for " + wanted.getSimpleName()); } assertThat(event).isInstanceOf(wanted); return wanted.cast(event); } public T takeNext() { OnNext event = takeEvent(OnNext.class); return event.value; } public Throwable takeError() { return takeEvent(OnError.class).throwable; } public void assertOnCompleted() { takeEvent(OnCompleted.class); } public void assertNoMoreEvents() { try { Object event = takeEvent(Object.class); throw new IllegalStateException("Expected no more events but got " + event); } catch (NoSuchElementException ignored) { } } private final class OnNext { final T value; private OnNext(T value) { this.value = value; } @Override public String toString() { return "OnNext[" + value + "]"; } } private final class OnCompleted { @Override public String toString() { return "OnCompleted"; } } private final class OnError { private final Throwable throwable; private OnError(Throwable throwable) { this.throwable = throwable; } @Override public String toString() { return "OnError[" + throwable + "]"; } } } <|start_filename|>app-preference-activity/src/main/java/com/github/pwittchen/prefser/app/preference/SettingsActivity.java<|end_filename|> /* * Copyright (C) 2015 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pwittchen.prefser.app.preference; import android.os.Bundle; import android.preference.PreferenceActivity; import android.preference.PreferenceFragment; import android.widget.Toast; import com.github.myapplication.R; import com.github.pwittchen.prefser.library.rx2.Prefser; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; public class SettingsActivity extends PreferenceActivity { private Prefser prefser; @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); getFragmentManager().beginTransaction() .replace(android.R.id.content, new SamplePreferenceFragment()) .commit(); prefser = new Prefser(this); showToastOnPreferenceUpdate(); } public static class SamplePreferenceFragment extends PreferenceFragment { @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); } } private void showToastOnPreferenceUpdate() { prefser.observePreferences() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(key -> Toast.makeText(SettingsActivity.this, String.format("%s is changed", key), Toast.LENGTH_SHORT).show()); } } <|start_filename|>library/src/test/java/com/github/pwittchen/prefser/library/rx2/PrefserObservablesTest.java<|end_filename|> /* * Copyright (C) 2015 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pwittchen.prefser.library.rx2; import android.content.Context; import com.github.pwittchen.prefser.library.rx2.utils.RecordingObserver; import io.reactivex.Observable; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Consumer; import java.util.Arrays; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Config; import static com.google.common.truth.Truth.assertThat; @RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public final class PrefserObservablesTest { private static final String GIVEN_KEY = "givenKey"; private static final String GIVEN_STRING_VALUE = "givenStringValue"; private Prefser prefser; private class CustomClass { private int valueOne; private String valueTwo; private CustomClass(int valueOne, String valueTwo) { this.valueOne = valueOne; this.valueTwo = valueTwo; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CustomClass that = (CustomClass) o; if (valueOne != that.valueOne) { return false; } return valueTwo != null ? valueTwo.equals(that.valueTwo) : that.valueTwo == null; } @Override public int hashCode() { int result = valueOne; result = 31 * result + (valueTwo != null ? valueTwo.hashCode() : 0); return result; } } @Before public void setUp() { final Context context = RuntimeEnvironment.application.getApplicationContext(); prefser = new Prefser(context); prefser.clear(); } @After public void tearDown() { prefser.clear(); } @Test public void testObserveBoolean() { // given prefser.clear(); String givenKey = GIVEN_KEY; boolean givenValue = true; Boolean defaultValue = false; // when RecordingObserver<Boolean> observer = new RecordingObserver<>(); prefser.observe(givenKey, Boolean.class, defaultValue).subscribe(observer); prefser.put(givenKey, givenValue); // then assertThat(observer.takeNext()).isTrue(); observer.assertNoMoreEvents(); } @Test public void testGetAndObserveBoolean() { // given prefser.clear(); String givenKey = GIVEN_KEY; boolean givenValue = true; Boolean defaultValue = false; // when prefser.put(givenKey, givenValue); Boolean first = prefser.getAndObserve(givenKey, Boolean.class, defaultValue).blockingFirst(); // then assertThat(first).isTrue(); } @Test public void testObserveBooleanPrimitive() { // given prefser.clear(); String givenKey = GIVEN_KEY; boolean givenValue = true; boolean defaultValue = false; // when RecordingObserver<Boolean> observer = new RecordingObserver<>(); prefser.observe(givenKey, Boolean.class, defaultValue).subscribe(observer); prefser.put(givenKey, givenValue); // then assertThat(observer.takeNext()).isTrue(); observer.assertNoMoreEvents(); } @Test public void testGetAndObserveBooleanPrimitive() { // given prefser.clear(); String givenKey = GIVEN_KEY; boolean givenValue = true; boolean defaultValue = false; // when prefser.put(givenKey, givenValue); boolean first = prefser.getAndObserve(givenKey, Boolean.class, defaultValue).blockingFirst(); // then assertThat(first).isTrue(); } @Test public void testObserveFloat() { // given prefser.clear(); String givenKey = GIVEN_KEY; Float givenValue = 3.0f; Float defaultValue = 1.0f; // when RecordingObserver<Float> observer = new RecordingObserver<>(); prefser.observe(givenKey, Float.class, defaultValue).subscribe(observer); prefser.put(givenKey, givenValue); // then assertThat(observer.takeNext()).isEqualTo(givenValue); observer.assertNoMoreEvents(); } @Test public void testGetAndObserveFloat() { // given prefser.clear(); String givenKey = GIVEN_KEY; Float givenValue = 3.0f; Float defaultValue = 1.0f; // when prefser.put(givenKey, givenValue); Float first = prefser.getAndObserve(givenKey, Float.class, defaultValue).blockingFirst(); // then assertThat(first).isEqualTo(givenValue); } @Test public void testObserveFloatPrimitive() { // given prefser.clear(); String givenKey = GIVEN_KEY; float givenValue = 3.0f; float defaultValue = 1.0f; // when RecordingObserver<Float> observer = new RecordingObserver<>(); prefser.observe(givenKey, Float.class, defaultValue).subscribe(observer); prefser.put(givenKey, givenValue); // then assertThat(observer.takeNext()).isEqualTo(givenValue); observer.assertNoMoreEvents(); } @Test public void testGetAndObserveFloatPrimitive() { // given prefser.clear(); String givenKey = GIVEN_KEY; float givenValue = 3.0f; float defaultValue = 1.0f; // when prefser.put(givenKey, givenValue); float first = prefser.getAndObserve(givenKey, Float.class, defaultValue).blockingFirst(); // then assertThat(first).isEqualTo(givenValue); } @Test public void testObserveInteger() { // given prefser.clear(); String givenKey = GIVEN_KEY; Integer givenValue = 5; Integer defaultValue = 8; // when RecordingObserver<Integer> observer = new RecordingObserver<>(); prefser.observe(givenKey, Integer.class, defaultValue).subscribe(observer); prefser.put(givenKey, givenValue); // then assertThat(observer.takeNext()).isEqualTo(givenValue); observer.assertNoMoreEvents(); } @Test public void testGetAndObserveInteger() { // given prefser.clear(); String givenKey = GIVEN_KEY; Integer givenValue = 5; Integer defaultValue = 8; // when prefser.put(givenKey, givenValue); Integer first = prefser.getAndObserve(givenKey, Integer.class, defaultValue).blockingFirst(); // then assertThat(first).isEqualTo(givenValue); } @Test public void testObserveIntegerPrimitive() { // given prefser.clear(); String givenKey = GIVEN_KEY; int givenValue = 5; int defaultValue = 8; // when RecordingObserver<Integer> observer = new RecordingObserver<>(); prefser.observe(givenKey, Integer.class, defaultValue).subscribe(observer); prefser.put(givenKey, givenValue); // then assertThat(observer.takeNext()).isEqualTo(givenValue); observer.assertNoMoreEvents(); } @Test public void testGetAndObserveIntegerPrimitive() { // given prefser.clear(); String givenKey = GIVEN_KEY; int givenValue = 5; int defaultValue = 8; // when prefser.put(givenKey, givenValue); int first = prefser.getAndObserve(givenKey, Integer.class, defaultValue).blockingFirst(); // then assertThat(first).isEqualTo(givenValue); } @Test public void testObserveLong() { // given prefser.clear(); String givenKey = GIVEN_KEY; Long givenValue = 12L; Long defaultValue = 16L; // when RecordingObserver<Long> observer = new RecordingObserver<>(); prefser.observe(givenKey, Long.class, defaultValue).subscribe(observer); prefser.put(givenKey, givenValue); // then assertThat(observer.takeNext()).isEqualTo(givenValue); observer.assertNoMoreEvents(); } @Test public void testGetAndObserveLong() { // given prefser.clear(); String givenKey = GIVEN_KEY; Long givenValue = 12L; Long defaultValue = 16L; // when prefser.put(givenKey, givenValue); Long first = prefser.getAndObserve(givenKey, Long.class, defaultValue).blockingFirst(); // then assertThat(first).isEqualTo(givenValue); } @Test public void testObserveLongPrimitive() { // given prefser.clear(); String givenKey = GIVEN_KEY; long givenValue = 12L; long defaultValue = 16L; // when RecordingObserver<Long> observer = new RecordingObserver<>(); prefser.observe(givenKey, Long.class, defaultValue).subscribe(observer); prefser.put(givenKey, givenValue); // then assertThat(observer.takeNext()).isEqualTo(givenValue); observer.assertNoMoreEvents(); } @Test public void testGetAndObserveLongPrimitive() { // given prefser.clear(); String givenKey = GIVEN_KEY; long givenValue = 12L; long defaultValue = 16L; // when prefser.put(givenKey, givenValue); long first = prefser.getAndObserve(givenKey, Long.class, defaultValue).blockingFirst(); // then assertThat(first).isEqualTo(givenValue); } @Test public void testObserveDouble() { // given prefser.clear(); String givenKey = GIVEN_KEY; Double givenValue = 12.4; Double defaultValue = 19.9; // when RecordingObserver<Double> observer = new RecordingObserver<>(); prefser.observe(givenKey, Double.class, defaultValue).subscribe(observer); prefser.put(givenKey, givenValue); // then assertThat(observer.takeNext()).isEqualTo(givenValue); observer.assertNoMoreEvents(); } @Test public void testGetAndObserveDouble() { // given prefser.clear(); String givenKey = GIVEN_KEY; Double givenValue = 12.4; Double defaultValue = 19.9; // when prefser.put(givenKey, givenValue); Double first = prefser.getAndObserve(givenKey, Double.class, defaultValue).blockingFirst(); // then assertThat(first).isEqualTo(givenValue); } @Test public void testObserveDoublePrimitive() { // given prefser.clear(); String givenKey = GIVEN_KEY; double givenValue = 12.4; double defaultValue = 19.9; // when RecordingObserver<Double> observer = new RecordingObserver<>(); prefser.observe(givenKey, Double.class, defaultValue).subscribe(observer); prefser.put(givenKey, givenValue); // then assertThat(observer.takeNext()).isEqualTo(givenValue); observer.assertNoMoreEvents(); } @Test public void testGetAndObserveDoublePrimitive() { // given prefser.clear(); String givenKey = GIVEN_KEY; double givenValue = 12.4; double defaultValue = 19.9; // when prefser.put(givenKey, givenValue); double first = prefser.getAndObserve(givenKey, Double.class, defaultValue).blockingFirst(); // then assertThat(first).isEqualTo(givenValue); } @Test public void testObserveString() { // given prefser.clear(); String givenKey = GIVEN_KEY; String givenValue = "hi, I'm sample string"; String defaultValue = ""; // when RecordingObserver<String> observer = new RecordingObserver<>(); prefser.observe(givenKey, String.class, defaultValue).subscribe(observer); prefser.put(givenKey, givenValue); // then assertThat(observer.takeNext()).isEqualTo(givenValue); observer.assertNoMoreEvents(); } @Test public void testGetAndObserveString() { // given prefser.clear(); String givenKey = GIVEN_KEY; String givenValue = "hi, I'm sample string"; String defaultValue = ""; // when prefser.put(givenKey, givenValue); String first = prefser.getAndObserve(givenKey, String.class, defaultValue).blockingFirst(); // then assertThat(first).isEqualTo(givenValue); } @Test public void testObserveCustomObject() { // given prefser.clear(); String givenKey = GIVEN_KEY; CustomClass customClass = new CustomClass(56, GIVEN_STRING_VALUE); CustomClass defaultClass = new CustomClass(1, ""); // when RecordingObserver<CustomClass> observer = new RecordingObserver<>(); prefser.observe(givenKey, CustomClass.class, defaultClass).subscribe(observer); prefser.put(givenKey, customClass); // then assertThat(observer.takeNext()).isEqualTo(customClass); observer.assertNoMoreEvents(); } @Test public void testGetAndObserveCustomObject() { // given prefser.clear(); String givenKey = GIVEN_KEY; CustomClass customClass = new CustomClass(56, GIVEN_STRING_VALUE); CustomClass defaultClass = new CustomClass(1, ""); // when prefser.put(givenKey, customClass); CustomClass first = prefser.getAndObserve(givenKey, CustomClass.class, defaultClass).blockingFirst(); // then assertThat(first).isEqualTo(customClass); } @Test public void testObserveListOfBooleans() { // given prefser.clear(); String givenKey = GIVEN_KEY; List<Boolean> booleans = Arrays.asList(true, false, true); List<Boolean> defaultBooleans = Arrays.asList(false, false, false); // when RecordingObserver<List<Boolean>> observer = new RecordingObserver<>(); TypeToken<List<Boolean>> typeToken = new TypeToken<List<Boolean>>() { }; prefser.observe(givenKey, typeToken, defaultBooleans).subscribe(observer); prefser.put(givenKey, booleans); // then assertThat(observer.takeNext()).isEqualTo(booleans); observer.assertNoMoreEvents(); } @Test public void testGetAndObserveListOfBooleans() { // given prefser.clear(); String givenKey = GIVEN_KEY; List<Boolean> booleans = Arrays.asList(true, false, true); List<Boolean> defaultBooleans = Arrays.asList(false, false, false); // when prefser.put(givenKey, booleans); TypeToken<List<Boolean>> typeToken = new TypeToken<List<Boolean>>() { }; List<Boolean> first = prefser.getAndObserve(givenKey, typeToken, defaultBooleans).blockingFirst(); // then assertThat(first).isEqualTo(booleans); } @Test public void testObserveListOfFloats() { // given prefser.clear(); String givenKey = GIVEN_KEY; List<Float> floats = Arrays.asList(1.1f, 2.2f, 3.3f); List<Float> defaultFloats = Arrays.asList(0f, 0f, 0f); // when RecordingObserver<List<Float>> observer = new RecordingObserver<>(); TypeToken<List<Float>> typeToken = new TypeToken<List<Float>>() { }; prefser.observe(givenKey, typeToken, defaultFloats).subscribe(observer); prefser.put(givenKey, floats); // then assertThat(observer.takeNext()).isEqualTo(floats); observer.assertNoMoreEvents(); } @Test public void testGetAndObserveListOfFloats() { // given prefser.clear(); String givenKey = GIVEN_KEY; List<Float> floats = Arrays.asList(1.1f, 2.2f, 3.3f); List<Float> defaultFloats = Arrays.asList(0f, 0f, 0f); // when prefser.put(givenKey, floats); TypeToken<List<Float>> typeToken = new TypeToken<List<Float>>() { }; List<Float> first = prefser.getAndObserve(givenKey, typeToken, defaultFloats).blockingFirst(); // then assertThat(first).isEqualTo(floats); } @Test public void testObserveListOfIntegers() { // given prefser.clear(); String givenKey = GIVEN_KEY; List<Integer> integers = Arrays.asList(1, 2, 3); List<Integer> defaultIntegers = Arrays.asList(0, 0, 0); // when RecordingObserver<List<Integer>> observer = new RecordingObserver<>(); TypeToken<List<Integer>> typeToken = new TypeToken<List<Integer>>() { }; prefser.observe(givenKey, typeToken, defaultIntegers).subscribe(observer); prefser.put(givenKey, integers); // then assertThat(observer.takeNext()).isEqualTo(integers); observer.assertNoMoreEvents(); } @Test public void testGetAndObserveListOfIntegers() { // given prefser.clear(); String givenKey = GIVEN_KEY; List<Integer> integers = Arrays.asList(1, 2, 3); List<Integer> defaultIntegers = Arrays.asList(0, 0, 0); // when prefser.put(givenKey, integers); TypeToken<List<Integer>> typeToken = new TypeToken<List<Integer>>() { }; List<Integer> first = prefser.getAndObserve(givenKey, typeToken, defaultIntegers).blockingFirst(); // then assertThat(first).isEqualTo(integers); } @Test public void testObserveListOfLongs() { // given prefser.clear(); String givenKey = GIVEN_KEY; List<Long> longs = Arrays.asList(1L, 2L, 3L); List<Long> defaultLongs = Arrays.asList(0L, 0L, 0L); // when RecordingObserver<List<Long>> observer = new RecordingObserver<>(); TypeToken<List<Long>> typeToken = new TypeToken<List<Long>>() { }; prefser.observe(givenKey, typeToken, defaultLongs).subscribe(observer); prefser.put(givenKey, longs); // then assertThat(observer.takeNext()).isEqualTo(longs); observer.assertNoMoreEvents(); } @Test public void testGetAndObserveListOfLongs() { // given prefser.clear(); String givenKey = GIVEN_KEY; List<Long> longs = Arrays.asList(1L, 2L, 3L); List<Long> defaultLongs = Arrays.asList(0L, 0L, 0L); // when prefser.put(givenKey, longs); TypeToken<List<Long>> typeToken = new TypeToken<List<Long>>() { }; List<Long> first = prefser.getAndObserve(givenKey, typeToken, defaultLongs).blockingFirst(); // then assertThat(first).isEqualTo(longs); } @Test public void testObserveListOfDoubles() { // given prefser.clear(); String givenKey = GIVEN_KEY; List<Double> doubles = Arrays.asList(1.2, 34.65, 3.6); List<Double> defaultDoubles = Arrays.asList(1.0, 1.0, 1.0); // when RecordingObserver<List<Double>> observer = new RecordingObserver<>(); TypeToken<List<Double>> typeToken = new TypeToken<List<Double>>() { }; prefser.observe(givenKey, typeToken, defaultDoubles).subscribe(observer); prefser.put(givenKey, doubles); // then assertThat(observer.takeNext()).isEqualTo(doubles); observer.assertNoMoreEvents(); } @Test public void testGetAndObserveListOfDoubles() { // given prefser.clear(); String givenKey = GIVEN_KEY; List<Double> doubles = Arrays.asList(1.2, 34.65, 3.6); List<Double> defaultDoubles = Arrays.asList(1.0, 1.0, 1.0); // when prefser.put(givenKey, doubles); TypeToken<List<Double>> typeToken = new TypeToken<List<Double>>() { }; List<Double> first = prefser.getAndObserve(givenKey, typeToken, defaultDoubles).blockingFirst(); // then assertThat(first).isEqualTo(doubles); } @Test public void testObserveListOfStrings() { // given prefser.clear(); String givenKey = GIVEN_KEY; List<String> strings = Arrays.asList("one", "two", "three"); List<String> defaultStrings = Arrays.asList("some", "default", "strings"); // when RecordingObserver<List<String>> observer = new RecordingObserver<>(); TypeToken<List<String>> typeToken = new TypeToken<List<String>>() { }; prefser.observe(givenKey, typeToken, defaultStrings).subscribe(observer); prefser.put(givenKey, strings); // then assertThat(observer.takeNext()).isEqualTo(strings); observer.assertNoMoreEvents(); } @Test public void testGetAndObserveListOfStrings() { // given prefser.clear(); String givenKey = GIVEN_KEY; List<String> strings = Arrays.asList("first", "second", "third"); List<String> defaultStrings = Arrays.asList("some", "another", "default strings"); // when prefser.put(givenKey, strings); TypeToken<List<String>> typeToken = new TypeToken<List<String>>() { }; List<String> first = prefser.getAndObserve(givenKey, typeToken, defaultStrings).blockingFirst(); // then assertThat(first).isEqualTo(strings); } @Test public void testObserveListOfCustomObjects() { // given prefser.clear(); String givenKey = GIVEN_KEY; CustomClass defaultCustomObject = new CustomClass(0, "zero"); List<CustomClass> customObjects = Arrays.asList(new CustomClass(1, "first one"), new CustomClass(2, "second one"), new CustomClass(3, "yet another one")); List<CustomClass> defaultCustomObjects = Arrays.asList(defaultCustomObject, defaultCustomObject, defaultCustomObject); // when RecordingObserver<List<CustomClass>> observer = new RecordingObserver<>(); TypeToken<List<CustomClass>> typeToken = new TypeToken<List<CustomClass>>() { }; prefser.observe(givenKey, typeToken, defaultCustomObjects).subscribe(observer); prefser.put(givenKey, customObjects); // then assertThat(observer.takeNext()).isEqualTo(customObjects); observer.assertNoMoreEvents(); } @Test public void testGetAndObserveListOfCustomObjects() { // given prefser.clear(); String givenKey = GIVEN_KEY; CustomClass defaultCustomObject = new CustomClass(0, "this is zero"); List<CustomClass> customObjects = Arrays.asList(new CustomClass(1, "first class"), new CustomClass(2, "second class"), new CustomClass(3, "third class")); List<CustomClass> defaultCustomObjects = Arrays.asList(defaultCustomObject, defaultCustomObject, defaultCustomObject); // when prefser.put(givenKey, customObjects); TypeToken<List<CustomClass>> typeToken = new TypeToken<List<CustomClass>>() { }; List<CustomClass> first = prefser.getAndObserve(givenKey, typeToken, defaultCustomObjects).blockingFirst(); // then assertThat(first).isEqualTo(customObjects); } @Test public void testObserveArrayOfBooleans() { // given prefser.clear(); String givenKey = GIVEN_KEY; Boolean[] booleans = { true, false, true }; Boolean[] defaultBooleans = { false, false, false }; // when RecordingObserver<Boolean[]> observer = new RecordingObserver<>(); prefser.observe(givenKey, Boolean[].class, defaultBooleans).subscribe(observer); prefser.put(givenKey, booleans); Boolean[] generated = observer.takeNext(); // then assertThat(generated[0]).isEqualTo(booleans[0]); assertThat(generated[1]).isEqualTo(booleans[1]); assertThat(generated[2]).isEqualTo(booleans[2]); observer.assertNoMoreEvents(); } @Test public void testGetAndObserveArrayOfBooleans() { // given prefser.clear(); String givenKey = GIVEN_KEY; Boolean[] booleans = { true, false, true }; Boolean[] defaultBooleans = { false, false, false }; // when prefser.put(givenKey, booleans); Boolean[] generated = prefser.getAndObserve(givenKey, Boolean[].class, defaultBooleans).blockingFirst(); // then assertThat(generated[0]).isEqualTo(booleans[0]); assertThat(generated[1]).isEqualTo(booleans[1]); assertThat(generated[2]).isEqualTo(booleans[2]); } @Test public void testObserveArrayOfBooleansPrimitive() { // given prefser.clear(); String givenKey = GIVEN_KEY; boolean[] booleans = { true, false, true }; boolean[] defaultBooleans = { false, false, false }; // when RecordingObserver<boolean[]> observer = new RecordingObserver<>(); prefser.observe(givenKey, boolean[].class, defaultBooleans).subscribe(observer); prefser.put(givenKey, booleans); boolean[] generated = observer.takeNext(); // then assertThat(generated[0]).isEqualTo(booleans[0]); assertThat(generated[1]).isEqualTo(booleans[1]); assertThat(generated[2]).isEqualTo(booleans[2]); observer.assertNoMoreEvents(); } @Test public void testGetAndObserveArrayOfBooleansPrimitive() { // given prefser.clear(); String givenKey = GIVEN_KEY; boolean[] booleans = { true, false, true }; boolean[] defaultBooleans = { false, false, false }; // when prefser.put(givenKey, booleans); boolean[] generated = prefser.getAndObserve(givenKey, boolean[].class, defaultBooleans).blockingFirst(); // then assertThat(generated[0]).isEqualTo(booleans[0]); assertThat(generated[1]).isEqualTo(booleans[1]); assertThat(generated[2]).isEqualTo(booleans[2]); } @Test public void testObserveArrayOfFloats() { // given prefser.clear(); String givenKey = GIVEN_KEY; Float[] floats = { 1.1f, 4.5f, 6.8f }; Float[] defaultFloats = { 1.0f, 1.0f, 1.0f }; // when RecordingObserver<Float[]> observer = new RecordingObserver<>(); prefser.observe(givenKey, Float[].class, defaultFloats).subscribe(observer); prefser.put(givenKey, floats); Float[] generated = observer.takeNext(); // then assertThat(generated[0]).isEqualTo(floats[0]); assertThat(generated[1]).isEqualTo(floats[1]); assertThat(generated[2]).isEqualTo(floats[2]); observer.assertNoMoreEvents(); } @Test public void testGetAndObserveArrayOfFloats() { // given prefser.clear(); String givenKey = GIVEN_KEY; Float[] floats = { 1.1f, 4.5f, 6.8f }; Float[] defaultFloats = { 1.0f, 1.0f, 1.0f }; // when prefser.put(givenKey, floats); Float[] generated = prefser.getAndObserve(givenKey, Float[].class, defaultFloats).blockingFirst(); // then assertThat(generated[0]).isEqualTo(floats[0]); assertThat(generated[1]).isEqualTo(floats[1]); assertThat(generated[2]).isEqualTo(floats[2]); } @Test public void testObserveArrayOfFloatsPrimitive() { // given prefser.clear(); String givenKey = GIVEN_KEY; float[] floats = { 1.1f, 4.5f, 6.8f }; float[] defaultFloats = { 1.0f, 1.0f, 1.0f }; // when RecordingObserver<float[]> observer = new RecordingObserver<>(); prefser.observe(givenKey, float[].class, defaultFloats).subscribe(observer); prefser.put(givenKey, floats); float[] generated = observer.takeNext(); // then assertThat(generated[0]).isEqualTo(floats[0]); assertThat(generated[1]).isEqualTo(floats[1]); assertThat(generated[2]).isEqualTo(floats[2]); observer.assertNoMoreEvents(); } @Test public void testGetAndObserveArrayOfFloatsPrimitive() { // given prefser.clear(); String givenKey = GIVEN_KEY; float[] floats = { 1.1f, 4.5f, 6.8f }; float[] defaultFloats = { 1.0f, 1.0f, 1.0f }; // when prefser.put(givenKey, floats); float[] generated = prefser.getAndObserve(givenKey, float[].class, defaultFloats).blockingFirst(); // then assertThat(generated[0]).isEqualTo(floats[0]); assertThat(generated[1]).isEqualTo(floats[1]); assertThat(generated[2]).isEqualTo(floats[2]); } @Test public void testObserveArrayOfInts() { // given prefser.clear(); String givenKey = GIVEN_KEY; Integer[] ints = { 4, 5, 6 }; Integer[] defaultInts = { 1, 1, 1 }; // when RecordingObserver<Integer[]> observer = new RecordingObserver<>(); prefser.observe(givenKey, Integer[].class, defaultInts).subscribe(observer); prefser.put(givenKey, ints); Integer[] generated = observer.takeNext(); // then assertThat(generated[0]).isEqualTo(ints[0]); assertThat(generated[1]).isEqualTo(ints[1]); assertThat(generated[2]).isEqualTo(ints[2]); observer.assertNoMoreEvents(); } @Test public void testGetAndObserveArrayOfInts() { // given prefser.clear(); String givenKey = GIVEN_KEY; Integer[] ints = { 4, 5, 6 }; Integer[] defaultInts = { 1, 1, 1 }; // when prefser.put(givenKey, ints); Integer[] generated = prefser.getAndObserve(givenKey, Integer[].class, defaultInts).blockingFirst(); // then assertThat(generated[0]).isEqualTo(ints[0]); assertThat(generated[1]).isEqualTo(ints[1]); assertThat(generated[2]).isEqualTo(ints[2]); } @Test public void testObserveArrayOfIntsPrimitive() { // given prefser.clear(); String givenKey = GIVEN_KEY; int[] ints = { 4, 5, 6 }; int[] defaultInts = { 1, 1, 1 }; // when RecordingObserver<int[]> observer = new RecordingObserver<>(); prefser.observe(givenKey, int[].class, defaultInts).subscribe(observer); prefser.put(givenKey, ints); int[] generated = observer.takeNext(); // then assertThat(generated[0]).isEqualTo(ints[0]); assertThat(generated[1]).isEqualTo(ints[1]); assertThat(generated[2]).isEqualTo(ints[2]); observer.assertNoMoreEvents(); } @Test public void testGetAndObserveArrayOfIntsPrimitive() { // given prefser.clear(); String givenKey = GIVEN_KEY; int[] ints = { 4, 5, 6 }; int[] defaultInts = { 1, 1, 1 }; // when prefser.put(givenKey, ints); int[] generated = prefser.getAndObserve(givenKey, int[].class, defaultInts).blockingFirst(); // then assertThat(generated[0]).isEqualTo(ints[0]); assertThat(generated[1]).isEqualTo(ints[1]); assertThat(generated[2]).isEqualTo(ints[2]); } @Test public void testObserveArrayOfDoubles() { // given prefser.clear(); String givenKey = GIVEN_KEY; Double[] doubles = { 4.5, 5.6, 6.2 }; Double[] defaultDoubles = { 1.1, 1.1, 1.1 }; // when RecordingObserver<Double[]> observer = new RecordingObserver<>(); prefser.observe(givenKey, Double[].class, defaultDoubles).subscribe(observer); prefser.put(givenKey, doubles); Double[] generated = observer.takeNext(); // then assertThat(generated[0]).isEqualTo(doubles[0]); assertThat(generated[1]).isEqualTo(doubles[1]); assertThat(generated[2]).isEqualTo(doubles[2]); observer.assertNoMoreEvents(); } @Test public void testGetAndObserveArrayOfDoubles() { // given prefser.clear(); String givenKey = GIVEN_KEY; Double[] doubles = { 4.5, 5.6, 6.2 }; Double[] defaultDoubles = { 1.1, 1.1, 1.1 }; // when prefser.put(givenKey, doubles); Double[] generated = prefser.getAndObserve(givenKey, Double[].class, defaultDoubles).blockingFirst(); // then assertThat(generated[0]).isEqualTo(doubles[0]); assertThat(generated[1]).isEqualTo(doubles[1]); assertThat(generated[2]).isEqualTo(doubles[2]); } @Test public void testObserveArrayOfDoublesPrimitive() { // given prefser.clear(); String givenKey = GIVEN_KEY; double[] doubles = { 4.5, 5.6, 6.2 }; double[] defaultDoubles = { 1.1, 1.1, 1.1 }; // when RecordingObserver<double[]> observer = new RecordingObserver<>(); prefser.observe(givenKey, double[].class, defaultDoubles).subscribe(observer); prefser.put(givenKey, doubles); double[] generated = observer.takeNext(); // then assertThat(generated[0]).isEqualTo(doubles[0]); assertThat(generated[1]).isEqualTo(doubles[1]); assertThat(generated[2]).isEqualTo(doubles[2]); observer.assertNoMoreEvents(); } @Test public void testGetAndObserveArrayOfDoublesPrimitive() { // given prefser.clear(); String givenKey = GIVEN_KEY; double[] doubles = { 4.5, 5.6, 6.2 }; double[] defaultDoubles = { 1.1, 1.1, 1.1 }; // when prefser.put(givenKey, doubles); double[] generated = prefser.getAndObserve(givenKey, double[].class, defaultDoubles).blockingFirst(); // then assertThat(generated[0]).isEqualTo(doubles[0]); assertThat(generated[1]).isEqualTo(doubles[1]); assertThat(generated[2]).isEqualTo(doubles[2]); } @Test public void testObserveArrayOfStrings() { // given prefser.clear(); String givenKey = GIVEN_KEY; String[] strings = { "hey", "this is", "array" }; String[] defaultStrings = { "yet another", "default array", "of strings" }; // when RecordingObserver<String[]> observer = new RecordingObserver<>(); prefser.observe(givenKey, String[].class, defaultStrings).subscribe(observer); prefser.put(givenKey, strings); String[] generated = observer.takeNext(); // then assertThat(generated[0]).isEqualTo(strings[0]); assertThat(generated[1]).isEqualTo(strings[1]); assertThat(generated[2]).isEqualTo(strings[2]); observer.assertNoMoreEvents(); } @Test public void testGetAndObserveArrayOfStrings() { // given prefser.clear(); String givenKey = GIVEN_KEY; String[] strings = { "some", "random", "data" }; String[] defaultStrings = { "this", "will be", "default stuff" }; // when prefser.put(givenKey, strings); String[] generated = prefser.getAndObserve(givenKey, String[].class, defaultStrings).blockingFirst(); // then assertThat(generated[0]).isEqualTo(strings[0]); assertThat(generated[1]).isEqualTo(strings[1]); assertThat(generated[2]).isEqualTo(strings[2]); } @Test public void testObserveArrayOfCustomObjects() { // given prefser.clear(); String givenKey = GIVEN_KEY; CustomClass defaultCustomObject = new CustomClass(0, "this is zero"); CustomClass[] customClasses = { new CustomClass(1, "never"), new CustomClass(2, "gonna"), new CustomClass(3, "give you up") }; CustomClass[] defaultCustomClasses = { defaultCustomObject, defaultCustomObject, defaultCustomObject }; // when RecordingObserver<CustomClass[]> observer = new RecordingObserver<>(); prefser.observe(givenKey, CustomClass[].class, defaultCustomClasses).subscribe(observer); prefser.put(givenKey, customClasses); CustomClass[] generated = observer.takeNext(); // then assertThat(generated[0]).isEqualTo(customClasses[0]); assertThat(generated[1]).isEqualTo(customClasses[1]); assertThat(generated[2]).isEqualTo(customClasses[2]); observer.assertNoMoreEvents(); } @Test public void testGetAndObserveArrayOfCustomObjects() { // given prefser.clear(); String givenKey = GIVEN_KEY; CustomClass defaultCustomObject = new CustomClass(0, "zero value"); CustomClass[] customClasses = { new CustomClass(1, "never gonna"), new CustomClass(2, "let you"), new CustomClass(3, "down") }; CustomClass[] defaultCustomClasses = { defaultCustomObject, defaultCustomObject, defaultCustomObject }; // when prefser.put(givenKey, customClasses); CustomClass[] generated = prefser.getAndObserve(givenKey, CustomClass[].class, defaultCustomClasses).blockingFirst(); // then assertThat(generated[0]).isEqualTo(customClasses[0]); assertThat(generated[1]).isEqualTo(customClasses[1]); assertThat(generated[2]).isEqualTo(customClasses[2]); } @Test public void testObservePreferencesOnPut() { // given prefser.clear(); String givenKey = GIVEN_KEY; String givenValue = GIVEN_STRING_VALUE; // when RecordingObserver<String> observer = new RecordingObserver<>(); prefser.observePreferences().subscribe(observer); prefser.put(givenKey, givenValue); // then assertThat(observer.takeNext()).isEqualTo(givenKey); observer.assertNoMoreEvents(); } @Test public void testObservePreferencesOnUpdate() { // given prefser.clear(); String givenKey = GIVEN_KEY; String givenValue = GIVEN_STRING_VALUE; String anotherGivenValue = "anotherGivenValue"; prefser.put(givenKey, givenValue); // when RecordingObserver<String> observer = new RecordingObserver<>(); prefser.observePreferences().subscribe(observer); prefser.put(givenKey, anotherGivenValue); // then assertThat(observer.takeNext()).isEqualTo(givenKey); observer.assertNoMoreEvents(); } @Test public void testObservePreferencesOnRemove() { // given prefser.clear(); String givenKey = GIVEN_KEY; String givenValue = GIVEN_STRING_VALUE; prefser.put(givenKey, givenValue); // when RecordingObserver<String> observer = new RecordingObserver<>(); prefser.observePreferences().subscribe(observer); prefser.remove(givenKey); // then assertThat(observer.takeNext()).isEqualTo(givenKey); observer.assertNoMoreEvents(); } @Test public void testObservePreferencesTwice() { // given prefser.clear(); String givenKey = GIVEN_KEY; String givenValue = GIVEN_STRING_VALUE; String anotherGivenValue = "anotherGivenValue"; String yetAnotherGivenValue = "yetAnotherGivenValue"; prefser.put(givenKey, givenValue); // when 1 RecordingObserver<String> observer1 = new RecordingObserver<>(); RecordingObserver<String> observer2 = new RecordingObserver<>(); Observable<String> preferencesObservable = prefser.observePreferences(); preferencesObservable.subscribe(observer1); preferencesObservable.subscribe(observer2); prefser.put(givenKey, anotherGivenValue); // then 1 assertThat(observer1.takeNext()).isEqualTo(givenKey); assertThat(observer2.takeNext()).isEqualTo(givenKey); // when 2 prefser.put(givenKey, yetAnotherGivenValue); // then 2 assertThat(observer1.takeNext()).isEqualTo(givenKey); assertThat(observer2.takeNext()).isEqualTo(givenKey); observer2.assertNoMoreEvents(); } @Test public void testShouldDisposeSubscriptionAndStopObservation() { // given prefser.clear(); // when Disposable disposable = prefser.observePreferences().subscribe(new Consumer<String>() { @Override public void accept(String s) throws Exception { } }); disposable.dispose(); // then assertThat(disposable.isDisposed()).isTrue(); } } <|start_filename|>library/src/main/java/com/github/pwittchen/prefser/library/rx2/TypeToken.java<|end_filename|> /* * Copyright (C) 2015 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pwittchen.prefser.library.rx2; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; // Inspired by Gson's TypeToken public abstract class TypeToken<T> { private final Type type; public TypeToken() { // Superclass of anonymous class retains its type parameter despite of type erasure. Type superclass = getClass().getGenericSuperclass(); if (superclass instanceof Class) { throw new RuntimeException("Missing type parameter."); } ParameterizedType parameterizedSuperclass = (ParameterizedType) superclass; type = parameterizedSuperclass.getActualTypeArguments()[0]; } private TypeToken(Class<?> classOfT) { if (classOfT == null) { throw new NullPointerException("classOfT == null"); } this.type = classOfT; } static <T> TypeToken<T> fromClass(Class<T> classForT) { return new TypeToken<T>(classForT) { }; } static <T> TypeToken<T> fromValue(T value) { return new TypeToken<T>(value.getClass()) { }; } public Type getType() { return type; } } <|start_filename|>app/src/main/java/com/github/pwittchen/prefser/app/MainActivity.java<|end_filename|> /* * Copyright (C) 2015 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.pwittchen.prefser.app; import android.app.Activity; import android.os.Bundle; import android.widget.EditText; import android.widget.Toast; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import com.github.pwittchen.prefser.R; import com.github.pwittchen.prefser.library.rx2.Prefser; import io.reactivex.Observer; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.annotations.NonNull; import io.reactivex.disposables.Disposable; import io.reactivex.schedulers.Schedulers; public class MainActivity extends Activity { private Prefser prefser; private final static String EMPTY_STRING = ""; private final static String MY_KEY = "MY_KEY"; private Disposable subscriptionForAllPreferences; private Disposable subscriptionForSinglePreference; @BindView(R.id.value) protected EditText value; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); prefser = new Prefser(this); } @Override protected void onResume() { super.onResume(); // in this project two subscriptions were created just for an example // in real life, one subscription should be enough for case like that createSubscriptionForAllPreferences(); createSubscriptionForSinglePreference(); } private void createSubscriptionForAllPreferences() { subscriptionForAllPreferences = prefser.observePreferences() .subscribeOn(Schedulers.io()) .filter(key -> key.equals(MY_KEY)) .observeOn(AndroidSchedulers.mainThread()) .subscribe(value -> Toast.makeText(MainActivity.this, String.format("global: Value in %s changed", MY_KEY), Toast.LENGTH_SHORT).show()); } private void createSubscriptionForSinglePreference() { // here, we created new Subscriber as an extended example, // but we can also use simple Action1 interface with call(String key) method // as in createSubscriptionForAllPreferences() method prefser.getAndObserve(MY_KEY, String.class, EMPTY_STRING) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<String>() { @Override public void onSubscribe(@NonNull Disposable d) { subscriptionForSinglePreference = d; } @Override public void onNext(@NonNull String s) { value.setText(String.valueOf(s)); Toast.makeText(MainActivity.this, String.format("single: Value in %s changed", MY_KEY), Toast.LENGTH_SHORT).show(); } @Override public void onError(@NonNull Throwable e) { Toast.makeText(MainActivity.this, String.format("Problem with accessing key %s", MY_KEY), Toast.LENGTH_SHORT).show(); } @Override public void onComplete() { } }); } @Override protected void onPause() { super.onPause(); if (!subscriptionForAllPreferences.isDisposed()) { subscriptionForAllPreferences.dispose(); } if (!subscriptionForSinglePreference.isDisposed()) { subscriptionForSinglePreference.dispose(); } } @OnClick(R.id.save) public void onSaveClicked() { prefser.put(MY_KEY, value.getText().toString()); } @OnClick(R.id.put_lenny_face) public void onPutNameClicked() { prefser.put(MY_KEY, "Hi! I'm Piotr!"); } @OnClick(R.id.remove) public void onRemoveClicked() { prefser.remove(MY_KEY); } }
ubuntudroid/prefser
<|start_filename|>example_basic_test.go<|end_filename|> // Copyright 2016 <NAME>. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package writ_test import ( "fmt" "github.com/bobziuchkovski/writ" "strings" ) type Greeter struct { HelpFlag bool `flag:"help" description:"Display this help message and exit"` Verbosity int `flag:"v, verbose" description:"Display verbose output"` Name string `option:"n, name" default:"Everyone" description:"The person or people to greet"` } // This example uses writ.New() to build a command from the Greeter's // struct fields. The resulting *writ.Command decodes and updates the // Greeter's fields in-place. The Command.ExitHelp() method is used to // display help content if --help is specified, or if invalid input // arguments are received. func Example_basic() { greeter := &Greeter{} cmd := writ.New("greeter", greeter) cmd.Help.Usage = "Usage: greeter [OPTION]... MESSAGE" cmd.Help.Header = "Greet users, displaying MESSAGE" // Use cmd.Decode(os.Args[1:]) in a real application _, positional, err := cmd.Decode([]string{"-vvv", "--name", "Sam", "How's it going?"}) if err != nil || greeter.HelpFlag { cmd.ExitHelp(err) } message := strings.Join(positional, " ") fmt.Printf("Hi %s! %s\n", greeter.Name, message) if greeter.Verbosity > 0 { fmt.Printf("I'm feeling re%slly chatty today!\n", strings.Repeat("a", greeter.Verbosity)) } // Output: // Hi Sam! How's it going? // I'm feeling reaaally chatty today! // Help Output: // Usage: greeter [OPTION]... MESSAGE // Greet users, displaying MESSAGE // // Available Options: // --help Display this help message and exit // -v, --verbose Display verbose output // -n, --name=ARG The person or people to greet } <|start_filename|>example_subcommand_test.go<|end_filename|> // Copyright 2016 <NAME>. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package writ_test import ( "errors" "github.com/bobziuchkovski/writ" "os" ) type GoBox struct { Link Link `command:"ln" alias:"link" description:"Create a soft or hard link"` List List `command:"ls" alias:"list" description:"List directory contents"` } type Link struct { HelpFlag bool `flag:"h, help" description:"Display this message and exit"` Symlink bool `flag:"s" description:"Create a symlink instead of a hard link"` } type List struct { HelpFlag bool `flag:"h, help" description:"Display this message and exit"` LongFormat bool `flag:"l" description:"Use long-format output"` } func (g *GoBox) Run(p writ.Path, positional []string) { // The user didn't specify a subcommand. Give them help. p.Last().ExitHelp(errors.New("COMMAND is required")) } func (l *Link) Run(p writ.Path, positional []string) { if l.HelpFlag { p.Last().ExitHelp(nil) } if len(positional) != 2 { p.Last().ExitHelp(errors.New("ln requires two arguments, OLD and NEW")) } // Link operation omitted for brevity. This would be os.Link or os.Symlink // based on the l.Symlink value. } func (l *List) Run(p writ.Path, positional []string) { if l.HelpFlag { p.Last().ExitHelp(nil) } // Listing operation omitted for brevity. This would be a call to ioutil.ReadDir // followed by conditional formatting based on the l.LongFormat value. } // This example demonstrates subcommands in a busybox style. There's no requirement // that subcommands implement the Run() method shown here. It's just an example of // how subcommands might be implemented. func Example_subcommand() { gobox := &GoBox{} cmd := writ.New("gobox", gobox) cmd.Help.Usage = "Usage: gobox COMMAND [OPTION]... [ARG]..." cmd.Subcommand("ln").Help.Usage = "Usage: gobox ln [-s] OLD NEW" cmd.Subcommand("ls").Help.Usage = "Usage: gobox ls [-l] [PATH]..." path, positional, err := cmd.Decode(os.Args[1:]) if err != nil { // Using path.Last() here ensures the user sees relevant help for their // command selection path.Last().ExitHelp(err) } // At this point, cmd.Decode() has already decoded option values into the gobox // struct, including subcommand values. We just need to dispatch the command. // path.String() is guaranteed to represent the user command selection. switch path.String() { case "gobox": gobox.Run(path, positional) case "gobox ln": gobox.Link.Run(path, positional) case "gobox ls": gobox.List.Run(path, positional) default: panic("BUG: Someone added a new command and forgot to add it's path here") } // Help output, gobox: // Usage: gobox COMMAND [OPTION]... [ARG]... // // Available Commands: // ln Create a soft or hard link // ls List directory contents // // Help output, gobox ln: // Usage: gobox ln [-s] OLD NEW // // Available Options: // -h, --help Display this message and exit // -s Create a symlink instead of a hard link // // Help output, gobox ls: // Usage: gobox ls [-l] [PATH]... // // Available Options: // -h, --help Display this message and exit // -l Use long-format output } <|start_filename|>option_test.go<|end_filename|> // Copyright (c) 2016 <NAME> // // 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. package writ import ( "fmt" "testing" ) /* * Much of the option testing occurs indirectly via command_test.go */ type noopDecoder struct{} func (d noopDecoder) Decode(arg string) error { return nil } var invalidOptionTests = []struct { Description string Option *Option }{ { Description: "Option must have a name 1", Option: &Option{Decoder: noopDecoder{}}, }, { Description: "Option must have a name 1", Option: &Option{Names: []string{}, Decoder: noopDecoder{}}, }, { Description: "Option names cannot be blank", Option: &Option{Names: []string{""}, Decoder: noopDecoder{}}, }, { Description: "Option names cannot begin with -", Option: &Option{Names: []string{"-option"}, Decoder: noopDecoder{}}, }, { Description: "Option names cannot have spaces 1", Option: &Option{Names: []string{" option"}, Decoder: noopDecoder{}}, }, { Description: "Option names cannot have spaces 2", Option: &Option{Names: []string{"option "}, Decoder: noopDecoder{}}, }, { Description: "Option names cannot have spaces 3", Option: &Option{Names: []string{"option spaces"}, Decoder: noopDecoder{}}, }, { Description: "Option must have a decoder", Option: &Option{Names: []string{"option"}}, }, } func TestDirectOptionValidation(t *testing.T) { for _, test := range invalidOptionTests { err := checkInvalidOption(test.Option) if err == nil { t.Errorf("Expected error validating option, but none received. Test: %s", test.Description) continue } } } func checkInvalidOption(opt *Option) (err error) { defer func() { r := recover() if r != nil { switch e := r.(type) { case commandError: err = e case optionError: err = e default: panic(e) } } }() opt.validate() return nil } func TestNilNewOptionDecoder(t *testing.T) { var nilptr *bool defer func() { r := recover() if r != nil { switch r.(type) { case commandError, optionError: // Intentionally blank default: panic(r) } } }() NewOptionDecoder(nilptr) t.Errorf("Expected NewOptionDecoder to panic on nil value, but this didn't happen") } func TestNonPointerNewOptionDecoder(t *testing.T) { val := true defer func() { r := recover() if r != nil { switch r.(type) { case commandError, optionError: // Intentionally blank default: panic(r) } } }() NewOptionDecoder(val) t.Errorf("Expected NewOptionDecoder to panic on non-pointer type, but this didn't happen") } func TestNilNewFlagDecoder(t *testing.T) { var nilptr *bool defer func() { r := recover() if r != nil { switch r.(type) { case commandError, optionError: // Intentionally blank default: panic(r) } } }() NewFlagDecoder(nilptr) t.Errorf("Expected NewFlagDecoder to panic on nil value, but this didn't happen") } /* * Misc coverage tests to ensure code doesn't panic */ func TestOptionError(t *testing.T) { err := optionError{fmt.Errorf("test")} if err.Error() != "test" { t.Errorf("Expected optionError to return underlying error string. Expected: %q, Received: %q", "test", err.Error()) } } // Ensure Option.String() doesn't panic. We make no guarantee // on the output formatting. func TestOptionString(t *testing.T) { opt := &Option{Names: []string{"o", "O", "opt", "Opt"}} if opt.String() == "" { t.Errorf("Option.String() returned an empty string") } } <|start_filename|>command_test.go<|end_filename|> // Copyright (c) 2016 <NAME> // // 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. package writ import ( "fmt" "io" "io/ioutil" "math" "os" "reflect" "strconv" "strings" "testing" ) func CompareField(structval interface{}, field string, value interface{}) (equal bool, fieldVal interface{}) { rval := reflect.ValueOf(structval) for rval.Kind() == reflect.Ptr { rval = rval.Elem() } f := rval.FieldByName(field) equal = reflect.DeepEqual(f.Interface(), value) fieldVal = f.Interface() return } /* * Test command and option routing for multi-tier commands */ type topSpec struct { MidSpec midSpec `command:"mid" alias:"second, 2nd" description:"a mid-level command"` HelpFlag bool `flag:"h, help" description:"help flag on a top-level command"` Top int `option:"t, topval" description:"an option on a top-level command"` } type midSpec struct { Mid int `option:"m, midval" description:"an option on a mid-level command"` HelpFlag bool `flag:"h, help" description:"help flag on a mid-level command"` BottomSpec bottomSpec `command:"bottom" alias:"third" description:"a bottom-level command"` } type bottomSpec struct { Bottom int `option:"b, bottomval" description:"an option on a bottom-level command"` HelpFlag bool `flag:"h, help" description:"help flag on a bottom-level command"` } type commandFieldTest struct { Args []string Valid bool Err string // TODO: rewrite all Valid: false cases with Err: message Path string Positional []string Field string Value interface{} SkipReason string } var commandFieldTests = []commandFieldTest{ // Path: top {Args: []string{}, Valid: true, Path: "top", Positional: []string{}}, {Args: []string{"-"}, Valid: true, Path: "top", Positional: []string{"-"}}, {Args: []string{"-", "mid"}, Valid: true, Path: "top", Positional: []string{"-", "mid"}}, {Args: []string{"--"}, Valid: true, Path: "top", Positional: []string{}}, {Args: []string{"--", "mid"}, Valid: true, Path: "top", Positional: []string{"mid"}}, {Args: []string{"-t", "1"}, Valid: true, Path: "top", Positional: []string{}, Field: "Top", Value: 1}, {Args: []string{"foo", "-t", "1"}, Valid: true, Path: "top", Positional: []string{"foo"}, Field: "Top", Value: 1}, {Args: []string{"-t", "1", "foo"}, Valid: true, Path: "top", Positional: []string{"foo"}, Field: "Top", Value: 1}, {Args: []string{"foo", "bar"}, Valid: true, Path: "top", Positional: []string{"foo", "bar"}}, {Args: []string{"foo", "-t", "1", "bar"}, Valid: true, Path: "top", Positional: []string{"foo", "bar"}, Field: "Top", Value: 1}, {Args: []string{"-t", "1", "foo", "bar"}, Valid: true, Path: "top", Positional: []string{"foo", "bar"}, Field: "Top", Value: 1}, {Args: []string{"--", "mid"}, Valid: true, Path: "top", Positional: []string{"mid"}}, {Args: []string{"-t", "1", "--", "mid"}, Valid: true, Path: "top", Positional: []string{"mid"}, Field: "Top", Value: 1}, {Args: []string{"-", "-t", "1", "--", "mid"}, Valid: true, Path: "top", Positional: []string{"-", "mid"}, Field: "Top", Value: 1}, {Args: []string{"--", "-t", "1", "mid"}, Valid: true, Path: "top", Positional: []string{"-t", "1", "mid"}, Field: "Top", Value: 0}, {Args: []string{"--", "-t", "1", "-", "mid"}, Valid: true, Path: "top", Positional: []string{"-t", "1", "-", "mid"}, Field: "Top", Value: 0}, {Args: []string{"bottom"}, Valid: true, Path: "top", Positional: []string{"bottom"}}, {Args: []string{"third"}, Valid: true, Path: "top", Positional: []string{"third"}}, {Args: []string{"bottom", "mid"}, Valid: true, Path: "top", Positional: []string{"bottom", "mid"}}, {Args: []string{"bottom", "second"}, Valid: true, Path: "top", Positional: []string{"bottom", "second"}}, {Args: []string{"bottom", "-", "second"}, Valid: true, Path: "top", Positional: []string{"bottom", "-", "second"}}, {Args: []string{"-m", "2"}, Valid: false}, {Args: []string{"--midval", "2"}, Valid: false}, {Args: []string{"-b", "3"}, Valid: false}, {Args: []string{"--bottomval", "3"}, Valid: false}, {Args: []string{"--bogus", "4"}, Valid: false}, {Args: []string{"--foo"}, Valid: false}, {Args: []string{"--foo=bar"}, Valid: false}, {Args: []string{"-f"}, Valid: false}, {Args: []string{"-f", "bar"}, Valid: false}, {Args: []string{"-fbar"}, Valid: false}, {Args: []string{"--help", "--help"}, Valid: false, Err: `option "--help" specified too many times`}, {Args: []string{"-h", "-h"}, Valid: false, Err: `option "-h" specified too many times`}, {Args: []string{"-hh"}, Valid: false, Err: `option "-h" specified too many times`}, // Path: top mid {Args: []string{"mid"}, Valid: true, Path: "top mid", Positional: []string{}}, {Args: []string{"mid", "-"}, Valid: true, Path: "top mid", Positional: []string{"-"}}, {Args: []string{"mid", "--"}, Valid: true, Path: "top mid", Positional: []string{}}, {Args: []string{"mid", "-", "bottom"}, Valid: true, Path: "top mid", Positional: []string{"-", "bottom"}}, {Args: []string{"mid", "--", "bottom"}, Valid: true, Path: "top mid", Positional: []string{"bottom"}}, {Args: []string{"mid", "-t", "1"}, Valid: true, Path: "top mid", Positional: []string{}, Field: "Top", Value: 1}, {Args: []string{"mid", "-", "-t", "1"}, Valid: true, Path: "top mid", Positional: []string{"-"}, Field: "Top", Value: 1}, {Args: []string{"mid", "--", "-t", "1"}, Valid: true, Path: "top mid", Positional: []string{"-t", "1"}, Field: "Top", Value: 0}, {Args: []string{"-t", "1", "mid"}, Valid: true, Path: "top mid", Positional: []string{}, Field: "Top", Value: 1}, {Args: []string{"mid", "foo", "-t", "1"}, Valid: true, Path: "top mid", Positional: []string{"foo"}, Field: "Top", Value: 1}, {Args: []string{"-t", "1", "mid", "foo"}, Valid: true, Path: "top mid", Positional: []string{"foo"}, Field: "Top", Value: 1}, {Args: []string{"mid", "-t", "1", "foo"}, Valid: true, Path: "top mid", Positional: []string{"foo"}, Field: "Top", Value: 1}, {Args: []string{"-t", "1", "mid", "foo"}, Valid: true, Path: "top mid", Positional: []string{"foo"}, Field: "Top", Value: 1}, {Args: []string{"mid", "foo", "-m", "2"}, Valid: true, Path: "top mid", Positional: []string{"foo"}, Field: "Mid", Value: 2}, {Args: []string{"mid", "-m", "2", "foo"}, Valid: true, Path: "top mid", Positional: []string{"foo"}, Field: "Mid", Value: 2}, {Args: []string{"mid", "foo", "bar"}, Valid: true, Path: "top mid", Positional: []string{"foo", "bar"}}, {Args: []string{"second", "foo", "bar"}, Valid: true, Path: "top mid", Positional: []string{"foo", "bar"}}, {Args: []string{"2nd", "foo", "bar"}, Valid: true, Path: "top mid", Positional: []string{"foo", "bar"}}, {Args: []string{"mid", "foo", "-t", "1", "bar"}, Valid: true, Path: "top mid", Positional: []string{"foo", "bar"}, Field: "Top", Value: 1}, {Args: []string{"mid", "-t", "1", "foo", "bar"}, Valid: true, Path: "top mid", Positional: []string{"foo", "bar"}, Field: "Top", Value: 1}, {Args: []string{"-t", "1", "mid", "foo", "bar"}, Valid: true, Path: "top mid", Positional: []string{"foo", "bar"}, Field: "Top", Value: 1}, {Args: []string{"mid", "foo", "-m", "2", "bar"}, Valid: true, Path: "top mid", Positional: []string{"foo", "bar"}, Field: "Mid", Value: 2}, {Args: []string{"-t", "1", "second", "foo", "bar"}, Valid: true, Path: "top mid", Positional: []string{"foo", "bar"}, Field: "Top", Value: 1}, {Args: []string{"second", "foo", "-m", "2", "bar"}, Valid: true, Path: "top mid", Positional: []string{"foo", "bar"}, Field: "Mid", Value: 2}, {Args: []string{"-t", "1", "2nd", "foo", "bar"}, Valid: true, Path: "top mid", Positional: []string{"foo", "bar"}, Field: "Top", Value: 1}, {Args: []string{"2nd", "foo", "-m", "2", "bar"}, Valid: true, Path: "top mid", Positional: []string{"foo", "bar"}, Field: "Mid", Value: 2}, {Args: []string{"mid", "-m", "2", "foo", "bar"}, Valid: true, Path: "top mid", Positional: []string{"foo", "bar"}, Field: "Mid", Value: 2}, {Args: []string{"mid", "-m", "2", "foo", "-t", "1", "bar"}, Valid: true, Path: "top mid", Positional: []string{"foo", "bar"}, Field: "Top", Value: 1}, {Args: []string{"mid", "-m", "2", "foo", "-t", "1", "bar"}, Valid: true, Field: "Mid", Value: 2}, {Args: []string{"mid", "-t", "1", "foo", "-m", "2", "bar"}, Valid: true, Path: "top mid", Positional: []string{"foo", "bar"}, Field: "Top", Value: 1}, {Args: []string{"mid", "-t", "1", "foo", "-m", "2", "bar"}, Valid: true, Field: "Mid", Value: 2}, {Args: []string{"-t", "1", "mid", "foo", "bar", "-m", "2"}, Valid: true, Path: "top mid", Positional: []string{"foo", "bar"}, Field: "Top", Value: 1}, {Args: []string{"-t", "1", "mid", "foo", "bar", "-m", "2"}, Valid: true, Field: "Mid", Value: 2}, {Args: []string{"mid", "-m", "2", "--"}, Valid: true, Path: "top mid", Positional: []string{}, Field: "Mid", Value: 2}, {Args: []string{"mid", "--", "-m", "2"}, Valid: true, Path: "top mid", Positional: []string{"-m", "2"}, Field: "Mid", Value: 0}, {Args: []string{"mid", "--", "bottom", "-b", "3"}, Valid: true, Path: "top mid", Positional: []string{"bottom", "-b", "3"}}, {Args: []string{"mid", "--", "bottom", "-b", "3", "--"}, Valid: true, Path: "top mid", Positional: []string{"bottom", "-b", "3", "--"}}, {Args: []string{"mid", "--", "bottom", "--", "-b", "3"}, Valid: true, Path: "top mid", Positional: []string{"bottom", "--", "-b", "3"}}, {Args: []string{"-m", "2", "mid"}, Valid: false}, {Args: []string{"--midval", "2", "mid"}, Valid: false}, {Args: []string{"-m", "2", "mid", "foo"}, Valid: false}, {Args: []string{"-b", "3", "mid"}, Valid: false}, {Args: []string{"-b", "3", "mid", "foo"}, Valid: false}, {Args: []string{"mid", "-b", "3"}, Valid: false}, {Args: []string{"mid", "-b", "3", "foo"}, Valid: false}, {Args: []string{"mid", "--bogus", "4"}, Valid: false}, {Args: []string{"mid", "--foo"}, Valid: false}, {Args: []string{"mid", "--foo=bar"}, Valid: false}, {Args: []string{"mid", "-f"}, Valid: false}, {Args: []string{"mid", "-f", "bar"}, Valid: false}, {Args: []string{"mid", "-fbar"}, Valid: false}, {Args: []string{"mid", "--help", "--help"}, Valid: false, Err: `option "--help" specified too many times`}, {Args: []string{"mid", "-h", "-h"}, Valid: false, Err: `option "-h" specified too many times`}, {Args: []string{"mid", "-hh"}, Valid: false, Err: `option "-h" specified too many times`}, // Path: top mid bottom {Args: []string{"mid", "bottom"}, Valid: true, Path: "top mid bottom", Positional: []string{}}, {Args: []string{"mid", "bottom", "-"}, Valid: true, Path: "top mid bottom", Positional: []string{"-"}}, {Args: []string{"mid", "bottom", "--"}, Valid: true, Path: "top mid bottom", Positional: []string{}}, {Args: []string{"mid", "bottom", "-t", "1"}, Valid: true, Path: "top mid bottom", Positional: []string{}, Field: "Top", Value: 1}, {Args: []string{"mid", "-t", "1", "bottom"}, Valid: true, Path: "top mid bottom", Positional: []string{}, Field: "Top", Value: 1}, {Args: []string{"-t", "1", "mid", "bottom"}, Valid: true, Path: "top mid bottom", Positional: []string{}, Field: "Top", Value: 1}, {Args: []string{"mid", "bottom", "foo", "-t", "1"}, Valid: true, Path: "top mid bottom", Positional: []string{"foo"}, Field: "Top", Value: 1}, {Args: []string{"mid", "-t", "1", "bottom", "foo"}, Valid: true, Path: "top mid bottom", Positional: []string{"foo"}, Field: "Top", Value: 1}, {Args: []string{"-t", "1", "mid", "bottom", "foo"}, Valid: true, Path: "top mid bottom", Positional: []string{"foo"}, Field: "Top", Value: 1}, {Args: []string{"mid", "bottom", "foo", "-b", "3"}, Valid: true, Path: "top mid bottom", Positional: []string{"foo"}, Field: "Bottom", Value: 3}, {Args: []string{"mid", "bottom", "-b", "3", "foo"}, Valid: true, Path: "top mid bottom", Positional: []string{"foo"}, Field: "Bottom", Value: 3}, {Args: []string{"mid", "bottom", "foo", "bar"}, Valid: true, Path: "top mid bottom", Positional: []string{"foo", "bar"}}, {Args: []string{"mid", "third", "-b", "3", "foo"}, Valid: true, Path: "top mid bottom", Positional: []string{"foo"}, Field: "Bottom", Value: 3}, {Args: []string{"2nd", "third", "foo", "bar"}, Valid: true, Path: "top mid bottom", Positional: []string{"foo", "bar"}}, {Args: []string{"-t", "1", "mid", "bottom", "foo", "bar"}, Valid: true, Path: "top mid bottom", Positional: []string{"foo", "bar"}, Field: "Top", Value: 1}, {Args: []string{"mid", "bottom", "foo", "-b", "3", "bar"}, Valid: true, Path: "top mid bottom", Positional: []string{"foo", "bar"}, Field: "Bottom", Value: 3}, {Args: []string{"mid", "bottom", "-b", "3", "foo", "bar"}, Valid: true, Path: "top mid bottom", Positional: []string{"foo", "bar"}, Field: "Bottom", Value: 3}, {Args: []string{"mid", "-t", "1", "bottom", "-b", "3", "foo", "bar"}, Valid: true, Path: "top mid bottom", Positional: []string{"foo", "bar"}, Field: "Bottom", Value: 3}, {Args: []string{"mid", "-t", "1", "bottom", "-b", "3", "foo", "bar"}, Valid: true, Field: "Top", Value: 1}, {Args: []string{"mid", "-m", "2", "bottom", "foo", "-b", "3", "bar"}, Valid: true, Path: "top mid bottom", Positional: []string{"foo", "bar"}, Field: "Bottom", Value: 3}, {Args: []string{"mid", "-m", "2", "bottom", "foo", "-b", "3", "bar"}, Valid: true, Field: "Mid", Value: 2}, {Args: []string{"-t", "1", "mid", "bottom", "foo", "bar", "-b", "3"}, Valid: true, Path: "top mid bottom", Positional: []string{"foo", "bar"}, Field: "Bottom", Value: 3}, {Args: []string{"-t", "1", "mid", "bottom", "foo", "bar", "-b", "3"}, Valid: true, Field: "Top", Value: 1}, {Args: []string{"-t", "1", "2nd", "bottom", "foo", "bar", "-b", "3"}, Valid: true, Path: "top mid bottom", Positional: []string{"foo", "bar"}, Field: "Bottom", Value: 3}, {Args: []string{"-t", "1", "2nd", "bottom", "foo", "bar", "-b", "3"}, Valid: true, Field: "Top", Value: 1}, {Args: []string{"-t", "1", "mid", "third", "foo", "bar", "-b", "3"}, Valid: true, Path: "top mid bottom", Positional: []string{"foo", "bar"}, Field: "Bottom", Value: 3}, {Args: []string{"-t", "1", "mid", "third", "foo", "bar", "-b", "3"}, Valid: true, Field: "Top", Value: 1}, {Args: []string{"-t", "1", "second", "third", "foo", "bar", "-b", "3"}, Valid: true, Path: "top mid bottom", Positional: []string{"foo", "bar"}, Field: "Bottom", Value: 3}, {Args: []string{"-t", "1", "second", "third", "foo", "bar", "-b", "3"}, Valid: true, Field: "Top", Value: 1}, {Args: []string{"mid", "bottom", "-b", "3", "--"}, Valid: true, Path: "top mid bottom", Positional: []string{}, Field: "Bottom", Value: 3}, {Args: []string{"mid", "bottom", "-", "-b", "3", "--"}, Valid: true, Path: "top mid bottom", Positional: []string{"-"}, Field: "Bottom", Value: 3}, {Args: []string{"mid", "bottom", "--", "-b", "3"}, Valid: true, Path: "top mid bottom", Positional: []string{"-b", "3"}, Field: "Bottom", Value: 0}, {Args: []string{"mid", "bottom", "-", "--", "-b", "3"}, Valid: true, Path: "top mid bottom", Positional: []string{"-", "-b", "3"}, Field: "Bottom", Value: 0}, {Args: []string{"mid", "-b", "3", "bottom"}, Valid: false}, {Args: []string{"bottom", "-b", "3"}, Valid: false}, {Args: []string{"-b", "3", "bottom"}, Valid: false}, {Args: []string{"-b", "3", "mid", "bottom"}, Valid: false}, {Args: []string{"mid", "--help", "--help", "bottom"}, Valid: false, Err: `option "--help" specified too many times`}, {Args: []string{"mid", "-h", "-h", "bottom"}, Valid: false, Err: `option "-h" specified too many times`}, {Args: []string{"mid", "-hh", "bottom"}, Valid: false, Err: `option "-h" specified too many times`}, // Duplicate option routing (HelpFlag) {Args: []string{"-h"}, Valid: true, Path: "top", Positional: []string{}, Field: "HelpFlagTop", Value: true}, {Args: []string{"-h"}, Valid: true, Field: "HelpFlagMid", Value: false}, {Args: []string{"-h"}, Valid: true, Field: "HelpFlagBottom", Value: false}, {Args: []string{"-h", "mid"}, Valid: true, Path: "top mid", Positional: []string{}, Field: "HelpFlagTop", Value: true}, {Args: []string{"-h", "mid"}, Valid: true, Field: "HelpFlagMid", Value: false}, {Args: []string{"-h", "mid"}, Valid: true, Field: "HelpFlagBottom", Value: false}, {Args: []string{"mid", "-h"}, Valid: true, Path: "top mid", Positional: []string{}, Field: "HelpFlagMid", Value: true}, {Args: []string{"mid", "-h"}, Valid: true, Field: "HelpFlagTop", Value: false}, {Args: []string{"mid", "-h"}, Valid: true, Field: "HelpFlagBottom", Value: false}, {Args: []string{"mid", "-h", "bottom"}, Valid: true, Path: "top mid bottom", Positional: []string{}, Field: "HelpFlagMid", Value: true}, {Args: []string{"mid", "-h", "bottom"}, Valid: true, Field: "HelpFlagTop", Value: false}, {Args: []string{"mid", "-h", "bottom"}, Valid: true, Field: "HelpFlagBottom", Value: false}, {Args: []string{"mid", "bottom", "-h"}, Valid: true, Path: "top mid bottom", Positional: []string{}, Field: "HelpFlagBottom", Value: true}, {Args: []string{"mid", "bottom", "-h"}, Valid: true, Field: "HelpFlagTop", Value: false}, {Args: []string{"mid", "bottom", "-h"}, Valid: true, Field: "HelpFlagMid", Value: false}, } func TestCommandFields(t *testing.T) { for _, test := range commandFieldTests { spec := &topSpec{} runCommandFieldTest(t, spec, test) } } func runCommandFieldTest(t *testing.T, spec *topSpec, test commandFieldTest) { if test.SkipReason != "" { t.Logf("Test skipped. Args: %q, Field: %s, Reason: %s", test.Args, test.Field, test.SkipReason) return } cmd := New("top", spec) path, positional, err := cmd.Decode(test.Args) values := map[string]interface{}{ "Top": spec.Top, "Mid": spec.MidSpec.Mid, "Bottom": spec.MidSpec.BottomSpec.Bottom, "HelpFlagTop": spec.HelpFlag, "HelpFlagMid": spec.MidSpec.HelpFlag, "HelpFlagBottom": spec.MidSpec.BottomSpec.HelpFlag, } if !test.Valid { if err == nil { t.Errorf("Expected error but none received. Args: %q", test.Args) } if test.Err != "" && err.Error() != test.Err { t.Errorf("Invalid error message. Expected: %s, Received: %s", test.Err, err.Error()) } return } if err != nil { t.Errorf("Received unexpected error. Field: %s, Args: %q, Error: %s", test.Field, test.Args, err) return } if test.Positional != nil && !reflect.DeepEqual(positional, test.Positional) { t.Errorf("Positional args are incorrect. Args: %q, Expected: %s, Received: %s", test.Args, test.Positional, positional) return } if test.Field != "" && !reflect.DeepEqual(values[test.Field], test.Value) { t.Errorf("Decoded value is incorrect. Field: %s, Args: %q, Expected: %#v, Received: %#v", test.Field, test.Args, test.Value, values[test.Field]) return } if path.First() != cmd { t.Errorf("Expected first command in path to be top-level command, but got %s instead.", path.First().Name) return } if test.Path != "" && path.String() != test.Path { t.Errorf("Command path is incorrect. Args: %q, Expected: %s, Received: %s", test.Args, test.Path, path) return } } func TestCommandString(t *testing.T) { cmd := New("top", &topSpec{}) if cmd.String() != "top" { t.Errorf("Invalid Command.String() value. Expected: %q, received: %q", "top", cmd.String()) } if cmd.Subcommand("mid").String() != "mid" { t.Errorf("Invalid Command.String() value. Expected: %q, received: %q", "mid", cmd.Subcommand("mid").String()) } if cmd.Subcommand("mid").Subcommand("bottom").String() != "bottom" { t.Errorf("Invalid Command.String() value. Expected: %q, received: %q", "bottom", cmd.Subcommand("mid").Subcommand("bottom").String()) } } /* * Test parsing of description metadata */ func TestSpecDescriptions(t *testing.T) { type Spec struct { Flag bool `flag:"flag" description:"a flag"` Option int `option:"option" description:"an option"` Command struct{} `command:"command" description:"a command"` } cmd := New("test", &Spec{}) if cmd.Option("flag").Description != "a flag" { t.Errorf("Flag description is incorrect. Expected: %q, Received: %q", "a flag", cmd.Option("flag").Description) } if cmd.Option("option").Description != "an option" { t.Errorf("Option description is incorrect. Expected: %q, Received: %q", "an option", cmd.Option("option").Description) } if cmd.Subcommand("command").Description != "a command" { t.Errorf("Command description is incorrect. Expected: %q, Received: %q", "a command", cmd.Subcommand("command").Description) } } /* * Test parsing of placeholder metadata */ func TestSpecPlaceholders(t *testing.T) { type Spec struct { Option int `option:"option" description:"an option" placeholder:"VALUE"` } cmd := New("test", &Spec{}) if cmd.Option("option").Placeholder != "VALUE" { t.Errorf("Option placeholder is incorrect. Expected: %q, Received: %q", "VALUE", cmd.Option("option").Placeholder) } } /* * Test default values on fields */ type defaultFieldSpec struct { Default int `option:"d" description:"An int field with a default" default:"42"` EnvDefault int `option:"e" description:"An int field with an environment default" env:"ENV_DEFAULT"` StackedDefault int `option:"s" description:"An int field with both a default and environment default" default:"84" env:"STACKED_DEFAULT"` } type defaultFieldTest struct { Args []string Valid bool Field string Value interface{} EnvKey string EnvValue string SkipReason string } var defaultFieldTests = []defaultFieldTest{ // Field with a default value {Args: []string{""}, Valid: true, Field: "Default", Value: 42}, {Args: []string{"-d", "2"}, Valid: true, Field: "Default", Value: 2}, {Args: []string{"-d", "foo"}, Valid: false}, // Field with an environment default {Args: []string{""}, Valid: true, Field: "EnvDefault", Value: 0}, {Args: []string{""}, Valid: true, EnvKey: "ENV_DEFAULT", EnvValue: "2", Field: "EnvDefault", Value: 2}, {Args: []string{""}, Valid: true, EnvKey: "ENV_DEFAULT", EnvValue: "foo", Field: "EnvDefault", Value: 0}, {Args: []string{"-e", "4"}, Valid: true, EnvKey: "ENV_DEFAULT", EnvValue: "2", Field: "EnvDefault", Value: 4}, {Args: []string{"-e", "4"}, Valid: true, EnvKey: "ENV_DEFAULT", EnvValue: "foo", Field: "EnvDefault", Value: 4}, {Args: []string{"-e", "foo"}, Valid: false, EnvKey: "ENV_DEFAULT", EnvValue: "2"}, // Field with both a default value and an environment default {Args: []string{""}, Valid: true, Field: "StackedDefault", Value: 84}, {Args: []string{""}, Valid: true, EnvKey: "STACKED_DEFAULT", EnvValue: "2", Field: "StackedDefault", Value: 2}, {Args: []string{""}, Valid: true, EnvKey: "STACKED_DEFAULT", EnvValue: "foo", Field: "StackedDefault", Value: 84}, {Args: []string{"-s", "4"}, Valid: true, EnvKey: "STACKED_DEFAULT", EnvValue: "2", Field: "StackedDefault", Value: 4}, {Args: []string{"-s", "4"}, Valid: true, EnvKey: "STACKED_DEFAULT", EnvValue: "foo", Field: "StackedDefault", Value: 4}, {Args: []string{"-s", "foo"}, Valid: false, EnvKey: "STACKED_DEFAULT", EnvValue: "foo"}, {Args: []string{"-s", "foo"}, Valid: false}, } func TestDefaultFields(t *testing.T) { for _, test := range defaultFieldTests { spec := &defaultFieldSpec{} runDefaultFieldTest(t, spec, test) } } func runDefaultFieldTest(t *testing.T, spec interface{}, test defaultFieldTest) { if test.SkipReason != "" { t.Logf("Test skipped. Args: %q, Field: %s, Reason: %s", test.Args, test.Field, test.SkipReason) return } if test.EnvKey != "" { realval := os.Getenv(test.EnvKey) defer (func() { os.Setenv(test.EnvKey, realval) })() os.Setenv(test.EnvKey, test.EnvValue) } cmd := New("test", spec) _, _, err := cmd.Decode(test.Args) if !test.Valid { if err == nil { t.Errorf("Expected error but none received. Args: %q", test.Args) } return } if err != nil { t.Errorf("Received unexpected error. Field: %s, Args: %q, Error: %s", test.Field, test.Args, err) return } equal, fieldval := CompareField(spec, test.Field, test.Value) if !equal { t.Errorf("Decoded value is incorrect. Field: %s, Args: %q, Expected: %#v, Received: %#v", test.Field, test.Args, test.Value, fieldval) return } } func TestBogusDefaultField(t *testing.T) { var spec = &struct { BogusDefault int `option:"b" description:"An int field with a bogus default" default:"bogus"` }{} defer func() { r := recover() if r != nil { switch r.(type) { case commandError, optionError: // Intentional No-op default: panic(r) } } }() cmd := New("test", spec) cmd.Decode([]string{}) t.Errorf("Expected decoding to panic on bogus default value, but this didn't happen.") } /* * Generic field test helpers */ type fieldTest struct { Args []string Valid bool Field string Value interface{} SkipReason string } func runFieldTest(t *testing.T, spec interface{}, test fieldTest) { if test.SkipReason != "" { t.Logf("Test skipped. Args: %q, Field: %s, Reason: %s", test.Args, test.Field, test.SkipReason) return } cmd := New("test", spec) _, _, err := cmd.Decode(test.Args) if !test.Valid { if err == nil { t.Errorf("Expected error but none received. Args: %q", test.Args) } return } if err != nil { t.Errorf("Received unexpected error. Field: %s, Args: %q, Error: %s", test.Field, test.Args, err) return } equal, fieldval := CompareField(spec, test.Field, test.Value) if !equal { t.Errorf("Decoded value is incorrect. Field: %s, Args: %q, Expected: %#v, Received: %#v", test.Field, test.Args, test.Value, fieldval) return } } /* * Test option name variations */ type optNameSpec struct { Bool bool `flag:" b, bool" description:"A bool flag"` Accumulator int `flag:"a,acc,A, accum" description:"An accumulator field"` Int int `option:"int, I" description:"An int field"` Float float32 `option:" float,F, FloaT, f " description:"A float field"` } var optNameTests = []fieldTest{ // Bool Flag {Args: []string{"-b"}, Valid: true, Field: "Bool", Value: true}, {Args: []string{"--bool"}, Valid: true, Field: "Bool", Value: true}, // Accumulator Flag {Args: []string{"-A", "--accum", "-a", "--acc", "-Aa", "-aA"}, Valid: true, Field: "Accumulator", Value: 8}, // Int Option {Args: []string{"-I2"}, Valid: true, Field: "Int", Value: 2}, {Args: []string{"-I", "2"}, Valid: true, Field: "Int", Value: 2}, {Args: []string{"--int", "2"}, Valid: true, Field: "Int", Value: 2}, {Args: []string{"--int=2"}, Valid: true, Field: "Int", Value: 2}, // Float Option {Args: []string{"-F2"}, Valid: true, Field: "Float", Value: float32(2.0)}, {Args: []string{"-F2.5"}, Valid: true, Field: "Float", Value: float32(2.5)}, {Args: []string{"-F", "2"}, Valid: true, Field: "Float", Value: float32(2.0)}, {Args: []string{"-F", "2.5"}, Valid: true, Field: "Float", Value: float32(2.5)}, {Args: []string{"-f2"}, Valid: true, Field: "Float", Value: float32(2.0)}, {Args: []string{"-f2.5"}, Valid: true, Field: "Float", Value: float32(2.5)}, {Args: []string{"-f", "2"}, Valid: true, Field: "Float", Value: float32(2.0)}, {Args: []string{"-f", "2.5"}, Valid: true, Field: "Float", Value: float32(2.5)}, {Args: []string{"--FloaT", "2"}, Valid: true, Field: "Float", Value: float32(2.0)}, {Args: []string{"--FloaT", "2.5"}, Valid: true, Field: "Float", Value: float32(2.5)}, {Args: []string{"--FloaT=2"}, Valid: true, Field: "Float", Value: float32(2.0)}, {Args: []string{"--FloaT=2.5"}, Valid: true, Field: "Float", Value: float32(2.5)}, {Args: []string{"--float", "2"}, Valid: true, Field: "Float", Value: float32(2.0)}, {Args: []string{"--float", "2.5"}, Valid: true, Field: "Float", Value: float32(2.5)}, {Args: []string{"--float=2"}, Valid: true, Field: "Float", Value: float32(2.0)}, {Args: []string{"--float=2.5"}, Valid: true, Field: "Float", Value: float32(2.5)}, } func TestOptionNames(t *testing.T) { for _, test := range optNameTests { spec := &optNameSpec{} runFieldTest(t, spec, test) } } /* * Test flag fields */ type flagFieldSpec struct { Bool bool `flag:"b, bool" description:"A bool flag"` Accumulator int `flag:"a, acc" description:"An accumulator flag"` } var flagTests = []fieldTest{ // Bool flag {Args: []string{}, Valid: true, Field: "Bool", Value: false}, {Args: []string{"-b"}, Valid: true, Field: "Bool", Value: true}, {Args: []string{"--bool"}, Valid: true, Field: "Bool", Value: true}, {Args: []string{"-b", "-b"}, Valid: false}, {Args: []string{"-b2"}, Valid: false}, {Args: []string{"--bool=2"}, Valid: false}, // Accumulator flag {Args: []string{}, Valid: true, Field: "Accumulator", Value: 0}, {Args: []string{"-a"}, Valid: true, Field: "Accumulator", Value: 1}, {Args: []string{"-a", "-a"}, Valid: true, Field: "Accumulator", Value: 2}, {Args: []string{"-aaa"}, Valid: true, Field: "Accumulator", Value: 3}, {Args: []string{"--acc", "-a"}, Valid: true, Field: "Accumulator", Value: 2}, {Args: []string{"-a", "--acc", "-aa"}, Valid: true, Field: "Accumulator", Value: 4}, {Args: []string{"-a3"}, Valid: false}, {Args: []string{"--acc=3"}, Valid: false}, } func TestFlagFields(t *testing.T) { for _, test := range flagTests { spec := &flagFieldSpec{} runFieldTest(t, spec, test) } } /* * Test map and slice field types */ type mapSliceFieldSpec struct { StringSlice []string `option:"s" description:"A string slice option" placeholder:"STRINGSLICE"` StringMap map[string]string `option:"m" description:"A map of strings option" placeholder:"KEY=VALUE"` } var mapSliceFieldTests = []fieldTest{ // String Slice {Args: []string{"-s", "1", "-s", "-1", "-s", "+1"}, Valid: true, Field: "StringSlice", Value: []string{"1", "-1", "+1"}}, {Args: []string{"-s", " a b", "-s", "\n", "-s", "\t"}, Valid: true, Field: "StringSlice", Value: []string{" a b", "\n", "\t"}}, {Args: []string{"-s", "日本", "-s", "-日本", "-s", "--日本"}, Valid: true, Field: "StringSlice", Value: []string{"日本", "-日本", "--日本"}}, {Args: []string{"-s", "1"}, Valid: true, Field: "StringSlice", Value: []string{"1"}}, {Args: []string{"-s", "-1"}, Valid: true, Field: "StringSlice", Value: []string{"-1"}}, {Args: []string{"-s", "+1"}, Valid: true, Field: "StringSlice", Value: []string{"+1"}}, {Args: []string{"-s", "1.0"}, Valid: true, Field: "StringSlice", Value: []string{"1.0"}}, {Args: []string{"-s", "0x01"}, Valid: true, Field: "StringSlice", Value: []string{"0x01"}}, {Args: []string{"-s", "-"}, Valid: true, Field: "StringSlice", Value: []string{"-"}}, {Args: []string{"-s", "-a"}, Valid: true, Field: "StringSlice", Value: []string{"-a"}}, {Args: []string{"-s", "--"}, Valid: true, Field: "StringSlice", Value: []string{"--"}}, {Args: []string{"-s", "--a"}, Valid: true, Field: "StringSlice", Value: []string{"--a"}}, {Args: []string{"-s", ""}, Valid: true, Field: "StringSlice", Value: []string{""}}, {Args: []string{"-s", " "}, Valid: true, Field: "StringSlice", Value: []string{" "}}, {Args: []string{"-s", " a"}, Valid: true, Field: "StringSlice", Value: []string{" a"}}, {Args: []string{"-s", "a "}, Valid: true, Field: "StringSlice", Value: []string{"a "}}, {Args: []string{"-s", "a b "}, Valid: true, Field: "StringSlice", Value: []string{"a b "}}, {Args: []string{"-s", " a b"}, Valid: true, Field: "StringSlice", Value: []string{" a b"}}, {Args: []string{"-s", "\n"}, Valid: true, Field: "StringSlice", Value: []string{"\n"}}, {Args: []string{"-s", "\t"}, Valid: true, Field: "StringSlice", Value: []string{"\t"}}, {Args: []string{"-s", "日本"}, Valid: true, Field: "StringSlice", Value: []string{"日本"}}, {Args: []string{"-s", "-日本"}, Valid: true, Field: "StringSlice", Value: []string{"-日本"}}, {Args: []string{"-s", "--日本"}, Valid: true, Field: "StringSlice", Value: []string{"--日本"}}, {Args: []string{"-s", " 日本"}, Valid: true, Field: "StringSlice", Value: []string{" 日本"}}, {Args: []string{"-s", "日本 "}, Valid: true, Field: "StringSlice", Value: []string{"日本 "}}, {Args: []string{"-s", "日 本"}, Valid: true, Field: "StringSlice", Value: []string{"日 本"}}, {Args: []string{"-s", "A relatively long string to make sure we aren't doing any silly truncation anywhere, since that would be bad..."}, Valid: true, Field: "StringSlice", Value: []string{"A relatively long string to make sure we aren't doing any silly truncation anywhere, since that would be bad..."}}, {Args: []string{"-s"}, Valid: false}, // String Map {Args: []string{"-m", "a=b"}, Valid: true, Field: "StringMap", Value: map[string]string{"a": "b"}}, {Args: []string{"-m", "a=b=c"}, Valid: true, Field: "StringMap", Value: map[string]string{"a": "b=c"}}, {Args: []string{"-m", "a=b "}, Valid: true, Field: "StringMap", Value: map[string]string{"a": "b "}}, {Args: []string{"-m", "a= b"}, Valid: true, Field: "StringMap", Value: map[string]string{"a": " b"}}, {Args: []string{"-m", "a =b"}, Valid: true, Field: "StringMap", Value: map[string]string{"a ": "b"}}, {Args: []string{"-m", " a=b"}, Valid: true, Field: "StringMap", Value: map[string]string{" a": "b"}}, {Args: []string{"-m", " a=b "}, Valid: true, Field: "StringMap", Value: map[string]string{" a": "b "}}, {Args: []string{"-m", "a = b "}, Valid: true, Field: "StringMap", Value: map[string]string{"a ": " b "}}, {Args: []string{"-m", " a = b "}, Valid: true, Field: "StringMap", Value: map[string]string{" a ": " b "}}, {Args: []string{"-m", "a=b", "-m", "a=c"}, Valid: true, Field: "StringMap", Value: map[string]string{"a": "c"}}, {Args: []string{"-m", "a=b", "-m", "c=d"}, Valid: true, Field: "StringMap", Value: map[string]string{"a": "b", "c": "d"}}, {Args: []string{"-m", "日=本", "-m", "-日=本", "-m", "--日=--本"}, Valid: true, Field: "StringMap", Value: map[string]string{"日": "本", "-日": "本", "--日": "--本"}}, {Args: []string{"-m", "a", "=b"}, Valid: false}, {Args: []string{"-m", "a", "b"}, Valid: false}, {Args: []string{"-m", "foo"}, Valid: false}, {Args: []string{"-m", "a:b"}, Valid: false}, {Args: []string{"-m"}, Valid: false}, } func TestMapSliceFields(t *testing.T) { for _, test := range mapSliceFieldTests { spec := &mapSliceFieldSpec{} runFieldTest(t, spec, test) } } /* * Test io field types */ const ioTestText = "test IO" type ioFieldSpec struct { Reader io.Reader `option:"reader" description:"An io.Reader input option"` ReadCloser io.ReadCloser `option:"readcloser" description:"An io.ReadCloser input option"` Writer io.Writer `option:"writer" description:"An io.Writer output option"` WriteCloser io.WriteCloser `option:"writecloser" description:"An io.WriteCloser output option"` } func (r *ioFieldSpec) PerformIO() error { input := []io.Reader{r.Reader, r.ReadCloser} for _, in := range input { if in != nil { bytes, err := ioutil.ReadAll(in) if err != nil { return err } if string(bytes) != ioTestText { return fmt.Errorf("Expected to read %q. Read %q instead.", ioTestText, string(bytes)) } closer, ok := in.(io.Closer) if ok { err = closer.Close() if err != nil { return err } } } } output := []io.Writer{r.Writer, r.WriteCloser} for _, out := range output { if out != nil { _, err := io.WriteString(out, ioTestText) if err != nil { return err } closer, ok := out.(io.Closer) if ok { err = closer.Close() if err != nil { return err } } } } return nil } type ioFieldTest struct { Args []string Valid bool Field string InFiles []string OutFiles []string SkipReason string } var ioFieldTests = []ioFieldTest{ // No-op {Args: []string{}, Valid: true, InFiles: []string{}, OutFiles: []string{}}, // io.Reader {Args: []string{"--reader", "-"}, Valid: true, Field: "Reader", InFiles: []string{"stdin"}, OutFiles: []string{}}, {Args: []string{"--reader", "infile"}, Valid: true, Field: "Reader", InFiles: []string{"infile"}, OutFiles: []string{}}, {Args: []string{"--reader", "bogus/infile"}, Valid: false}, {Args: []string{"--reader", ""}, Valid: false}, {Args: []string{"--reader", "infile1", "--reader", "intput2"}, Valid: false}, {Args: []string{"--reader", "-", "--reader", "intput"}, Valid: false}, {Args: []string{"--reader", "infile", "--reader", "-"}, Valid: false}, {Args: []string{"--reader"}, Valid: false}, // io.ReadCloser {Args: []string{"--readcloser", "-"}, Valid: true, Field: "ReadCloser", InFiles: []string{"stdin"}, OutFiles: []string{}}, {Args: []string{"--readcloser", "infile"}, Valid: true, Field: "ReadCloser", InFiles: []string{"infile"}, OutFiles: []string{}}, {Args: []string{"--readcloser", "bogus/infile"}, Valid: false}, {Args: []string{"--readcloser", ""}, Valid: false}, {Args: []string{"--readcloser", "infile1", "--readcloser", "intput2"}, Valid: false}, {Args: []string{"--readcloser", "-", "--readcloser", "intput"}, Valid: false}, {Args: []string{"--readcloser", "infile", "--readcloser", "-"}, Valid: false}, {Args: []string{"--readcloser"}, Valid: false}, // io.Writer {Args: []string{"--writer", "-"}, Valid: true, Field: "Writer", InFiles: []string{}, OutFiles: []string{"stdout"}}, {Args: []string{"--writer", "outfile"}, Valid: true, Field: "Writer", InFiles: []string{}, OutFiles: []string{"outfile"}}, {Args: []string{"--writer", ""}, Valid: false}, {Args: []string{"--writer", "bogus/outfile"}, Valid: false}, {Args: []string{"--writer", "outfile1", "--writer", "outfile2"}, Valid: false}, {Args: []string{"--writer", "-", "--writer", "outfile"}, Valid: false}, {Args: []string{"--writer", "outfile", "--writer", "-"}, Valid: false}, {Args: []string{"--writer"}, Valid: false}, // io.WriteCloser {Args: []string{"--writecloser", "-"}, Valid: true, Field: "WriteCloser", InFiles: []string{}, OutFiles: []string{"stdout"}}, {Args: []string{"--writecloser", "outfile"}, Valid: true, Field: "WriteCloser", InFiles: []string{}, OutFiles: []string{"outfile"}}, {Args: []string{"--writecloser", ""}, Valid: false}, {Args: []string{"--writecloser", "bogus/outfile"}, Valid: false}, {Args: []string{"--writecloser", "outfile1", "--writecloser", "outfile2"}, Valid: false}, {Args: []string{"--writecloser", "-", "--writecloser", "outfile"}, Valid: false}, {Args: []string{"--writecloser", "outfile", "--writecloser", "-"}, Valid: false}, {Args: []string{"--writecloser"}, Valid: false}, } func TestIOFields(t *testing.T) { for _, test := range ioFieldTests { spec := &ioFieldSpec{} runIOFieldTest(t, spec, test) } } func runIOFieldTest(t *testing.T, spec *ioFieldSpec, test ioFieldTest) { if test.SkipReason != "" { t.Logf("Test skipped. Args: %q, Field: %s, Reason: %s", test.Args, test.Field, test.SkipReason) return } realin, realout := os.Stdin, os.Stdout defer restoreStdinStdout(realin, realout) realdir, err := os.Getwd() if err != nil { t.Errorf("Failed to get working dir. Args: %q, Field: %s, Error: %s", test.Args, test.Field, err) return } defer restoreWorkingDir(realdir) err = setupIOFieldTest(test) if err != nil { t.Errorf("Failed to setup test. Args: %q, Field: %s, Error: %s", test.Args, test.Field, err) return } cmd := New("test", spec) _, _, err = cmd.Decode(test.Args) if !test.Valid { if err == nil { t.Errorf("Expected error but none received. Args: %q", test.Args) } return } if err != nil { t.Errorf("Received unexpected decode error. Args: %q, Field: %s, Error: %s", test.Args, test.Field, err) return } err = validateIOFieldTest(spec, test) if err != nil { t.Errorf("Validation failed during IO field test. Args: %q, Field: %s, Error: %s", test.Args, test.Field, err) return } } func restoreStdinStdout(stdin *os.File, stdout *os.File) { os.Stdin = stdin os.Stdout = stdout } func restoreWorkingDir(dir string) { err := os.Chdir(dir) if err != nil { panic(fmt.Sprintf("Failed to restore working dir. Dir: %q, Error: %s", dir, err)) } } func setupIOFieldTest(test ioFieldTest) error { tmpdir, err := ioutil.TempDir("", "writ-iofieldtest") if err != nil { return err } err = os.Chdir(tmpdir) if err != nil { return err } for _, name := range test.InFiles { f, err := os.Create(name) if err != nil { return err } _, err = io.WriteString(f, ioTestText) if err != nil { return err } err = f.Close() if err != nil { return err } if name == "stdin" { in, err := os.Open(name) if err != nil { return err } os.Stdin = in } } for _, name := range test.OutFiles { if name == "stdout" { out, err := os.Create(name) if err != nil { return err } os.Stdout = out } } return nil } func validateIOFieldTest(spec *ioFieldSpec, test ioFieldTest) error { err := spec.PerformIO() if err != nil { return err } for _, name := range test.OutFiles { in, err := os.Open(name) if err != nil { return err } bytes, err := ioutil.ReadAll(in) if err != nil { return err } if string(bytes) != ioTestText { return fmt.Errorf("Expected to read %q. Read %q instead.", ioTestText, string(bytes)) } err = in.Close() if err != nil { return err } } return nil } /* * Test custom flag and option decoders */ type customTestFlag struct { val *bool } func (d customTestFlag) Decode(arg string) error { *d.val = true return nil } type customTestFlagPtr struct { val bool } func (d *customTestFlagPtr) Decode(arg string) error { d.val = true return nil } type customTestOption struct { val *string } func (d customTestOption) Decode(arg string) error { if strings.HasPrefix(arg, "foo") { *d.val = arg return nil } return fmt.Errorf("customTestOption values must begin with foo") } type customTestOptionPtr struct { val string } func (d *customTestOptionPtr) Decode(arg string) error { if strings.HasPrefix(arg, "foo") { d.val = arg return nil } return fmt.Errorf("customTestOptionPtr values must begin with foo") } type customDecoderFieldSpec struct { CustomFlag customTestFlag `flag:"flag" description:"a custom flag field"` CustomFlagPtr customTestFlagPtr `flag:"flagptr" description:"a custom flag field with pointer receiver"` CustomOption customTestOption `option:"opt" description:"a custom option field"` CustomOptionPtr customTestOptionPtr `option:"optptr" description:"a custom option field with pointer receiver"` } var trueval = true var foobarval = "foobar" var customDecoderFieldTests = []fieldTest{ // Custom flag {Args: []string{"--flag"}, Valid: true, Field: "CustomFlag", Value: customTestFlag{val: &trueval}}, {Args: []string{"--flag", "--flag"}, Valid: false}, // Plural must be set explicitly // Custom flag with pointer receiver {Args: []string{"--flagptr"}, Valid: true, Field: "CustomFlagPtr", Value: customTestFlagPtr{val: true}}, {Args: []string{"--flagptr", "--flagptr"}, Valid: false}, // Plural must be set explicitly // Custom option {Args: []string{"--opt", "foobar"}, Valid: true, Field: "CustomOption", Value: customTestOption{val: &foobarval}}, {Args: []string{"--opt=foobar"}, Valid: true, Field: "CustomOption", Value: customTestOption{val: &foobarval}}, {Args: []string{"-opt=puppies"}, Valid: false}, {Args: []string{"-opt", "puppies"}, Valid: false}, {Args: []string{"--opt"}, Valid: false}, {Args: []string{"--opt", "foobar", "-opt", "foobar"}, Valid: false}, // Plural must be set explicitly // Custom option with pointer receiver {Args: []string{"--optptr", "foobar"}, Valid: true, Field: "CustomOptionPtr", Value: customTestOptionPtr{val: "foobar"}}, {Args: []string{"--optptr=foobar"}, Valid: true, Field: "CustomOptionPtr", Value: customTestOptionPtr{val: "foobar"}}, {Args: []string{"-optptr=puppies"}, Valid: false}, {Args: []string{"-optptr", "puppies"}, Valid: false}, {Args: []string{"--optptr"}, Valid: false}, {Args: []string{"--optptr", "foobar", "-optptr", "foobar"}, Valid: false}, // Plural must be set explicitly } func TestCustomDecoderFields(t *testing.T) { for _, test := range customDecoderFieldTests { var flagval bool var optval string spec := &customDecoderFieldSpec{ CustomFlag: customTestFlag{&flagval}, CustomOption: customTestOption{&optval}, } runFieldTest(t, spec, test) } } /* * Test basic field types */ type basicFieldSpec struct { Int int `option:"int" description:"An int option" placeholder:"INT"` Int8 int8 `option:"int8" description:"An int8 option" placeholder:"INT8"` Int16 int16 `option:"int16" description:"An int16 option" placeholder:"INT16"` Int32 int32 `option:"int32" description:"An int32 option" placeholder:"INT32"` Int64 int64 `option:"int64" description:"An int64 option" placeholder:"INT64"` Uint uint `option:"uint" description:"A uint option" placeholder:"UINT"` Uint8 uint8 `option:"uint8" description:"A uint8 option" placeholder:"UINT8"` Uint16 uint16 `option:"uint16" description:"A uint16 option" placeholder:"UINT16"` Uint32 uint32 `option:"uint32" description:"A uint32 option" placeholder:"UINT32"` Uint64 uint64 `option:"uint64" description:"A uint64 option" placeholder:"UINT64"` Float32 float32 `option:"float32" description:"A float32 option" placeholder:"FLOAT32"` Float64 float64 `option:"float64" description:"A float64 option" placeholder:"FLOAT64"` String string `option:"string" description:"A string option" placeholder:"STRING"` } var basicFieldTests = []fieldTest{ // String {Args: []string{"--string", "1"}, Valid: true, Field: "String", Value: "1"}, {Args: []string{"--string", "-1"}, Valid: true, Field: "String", Value: "-1"}, {Args: []string{"--string", "+1"}, Valid: true, Field: "String", Value: "+1"}, {Args: []string{"--string", "1.0"}, Valid: true, Field: "String", Value: "1.0"}, {Args: []string{"--string", "0x01"}, Valid: true, Field: "String", Value: "0x01"}, {Args: []string{"--string", "-"}, Valid: true, Field: "String", Value: "-"}, {Args: []string{"--string", "-a"}, Valid: true, Field: "String", Value: "-a"}, {Args: []string{"--string", "--"}, Valid: true, Field: "String", Value: "--"}, {Args: []string{"--string", "--a"}, Valid: true, Field: "String", Value: "--a"}, {Args: []string{"--string", ""}, Valid: true, Field: "String", Value: ""}, {Args: []string{"--string", " "}, Valid: true, Field: "String", Value: " "}, {Args: []string{"--string", " a"}, Valid: true, Field: "String", Value: " a"}, {Args: []string{"--string", "a "}, Valid: true, Field: "String", Value: "a "}, {Args: []string{"--string", "a b "}, Valid: true, Field: "String", Value: "a b "}, {Args: []string{"--string", " a b"}, Valid: true, Field: "String", Value: " a b"}, {Args: []string{"--string", "\n"}, Valid: true, Field: "String", Value: "\n"}, {Args: []string{"--string", "\t"}, Valid: true, Field: "String", Value: "\t"}, {Args: []string{"--string", "日本"}, Valid: true, Field: "String", Value: "日本"}, {Args: []string{"--string", "-日本"}, Valid: true, Field: "String", Value: "-日本"}, {Args: []string{"--string", "--日本"}, Valid: true, Field: "String", Value: "--日本"}, {Args: []string{"--string", " 日本"}, Valid: true, Field: "String", Value: " 日本"}, {Args: []string{"--string", "日本 "}, Valid: true, Field: "String", Value: "日本 "}, {Args: []string{"--string", "日 本"}, Valid: true, Field: "String", Value: "日 本"}, {Args: []string{"--string", "A relatively long string to make sure we aren't doing any silly truncation anywhere, since that would be bad..."}, Valid: true, Field: "String", Value: "A relatively long string to make sure we aren't doing any silly truncation anywhere, since that would be bad..."}, {Args: []string{"--string", "a", "--string", "b"}, Valid: false}, {Args: []string{"--string"}, Valid: false}, // Int8 {Args: []string{"--int8", fmt.Sprintf("%d", int64(math.MinInt8))}, Valid: true, Field: "Int8", Value: int8(math.MinInt8)}, {Args: []string{"--int8", fmt.Sprintf("%d", int64(math.MaxInt8))}, Valid: true, Field: "Int8", Value: int8(math.MaxInt8)}, {Args: []string{"--int8", fmt.Sprintf("%d", int64(math.MinInt8-1))}, Valid: false}, {Args: []string{"--int8", fmt.Sprintf("%d", int64(math.MaxInt8+1))}, Valid: false}, {Args: []string{"--int8", fmt.Sprintf("%d", int64(math.MinInt16))}, Valid: false}, {Args: []string{"--int8", fmt.Sprintf("%d", int64(math.MinInt16-1))}, Valid: false}, {Args: []string{"--int8", fmt.Sprintf("%d", int64(math.MaxInt16))}, Valid: false}, {Args: []string{"--int8", fmt.Sprintf("%d", int64(math.MaxInt16+1))}, Valid: false}, {Args: []string{"--int8", fmt.Sprintf("%d", int64(math.MinInt32))}, Valid: false}, {Args: []string{"--int8", fmt.Sprintf("%d", int64(math.MinInt32-1))}, Valid: false}, {Args: []string{"--int8", fmt.Sprintf("%d", int64(math.MaxInt32))}, Valid: false}, {Args: []string{"--int8", fmt.Sprintf("%d", int64(math.MaxInt32+1))}, Valid: false}, {Args: []string{"--int8", fmt.Sprintf("%d", int64(math.MinInt64))}, Valid: false}, {Args: []string{"--int8", fmt.Sprintf("%d", int64(math.MaxInt64))}, Valid: false}, {Args: []string{"--int8", fmt.Sprintf("%d", uint64(math.MaxInt64+1))}, Valid: false}, {Args: []string{"--int8", fmt.Sprintf("%d", uint64(math.MaxUint8))}, Valid: false}, {Args: []string{"--int8", fmt.Sprintf("%d", uint64(math.MaxUint8+1))}, Valid: false}, {Args: []string{"--int8", fmt.Sprintf("%d", uint64(math.MaxUint16))}, Valid: false}, {Args: []string{"--int8", fmt.Sprintf("%d", uint64(math.MaxUint16+1))}, Valid: false}, {Args: []string{"--int8", fmt.Sprintf("%d", uint64(math.MaxUint32))}, Valid: false}, {Args: []string{"--int8", fmt.Sprintf("%d", uint64(math.MaxUint32+1))}, Valid: false}, {Args: []string{"--int8", fmt.Sprintf("%d", uint64(math.MaxUint64))}, Valid: false}, {Args: []string{"--int8", fmt.Sprintf("%d", uint64(math.MaxUint64))}, Valid: false}, {Args: []string{"--int8", "1", "--int8", "2"}, Valid: false}, {Args: []string{"--int8", "1.0"}, Valid: false}, {Args: []string{"--int8", ""}, Valid: false}, {Args: []string{"--int8"}, Valid: false}, // Int16 {Args: []string{"--int16", fmt.Sprintf("%d", int64(math.MinInt8))}, Valid: true, Field: "Int16", Value: int16(math.MinInt8)}, {Args: []string{"--int16", fmt.Sprintf("%d", int64(math.MinInt8-1))}, Valid: true, Field: "Int16", Value: int16(math.MinInt8 - 1)}, {Args: []string{"--int16", fmt.Sprintf("%d", int64(math.MaxInt8))}, Valid: true, Field: "Int16", Value: int16(math.MaxInt8)}, {Args: []string{"--int16", fmt.Sprintf("%d", int64(math.MaxInt8+1))}, Valid: true, Field: "Int16", Value: int16(math.MaxInt8 + 1)}, {Args: []string{"--int16", fmt.Sprintf("%d", int64(math.MinInt16))}, Valid: true, Field: "Int16", Value: int16(math.MinInt16)}, {Args: []string{"--int16", fmt.Sprintf("%d", int64(math.MaxInt16))}, Valid: true, Field: "Int16", Value: int16(math.MaxInt16)}, {Args: []string{"--int16", fmt.Sprintf("%d", uint64(math.MaxUint8))}, Valid: true, Field: "Int16", Value: int16(math.MaxUint8)}, {Args: []string{"--int16", fmt.Sprintf("%d", uint64(math.MaxUint8+1))}, Valid: true, Field: "Int16", Value: int16(math.MaxUint8 + 1)}, {Args: []string{"--int16", fmt.Sprintf("%d", int64(math.MinInt16-1))}, Valid: false}, {Args: []string{"--int16", fmt.Sprintf("%d", int64(math.MaxInt16+1))}, Valid: false}, {Args: []string{"--int16", fmt.Sprintf("%d", int64(math.MinInt32))}, Valid: false}, {Args: []string{"--int16", fmt.Sprintf("%d", int64(math.MinInt32-1))}, Valid: false}, {Args: []string{"--int16", fmt.Sprintf("%d", int64(math.MaxInt32))}, Valid: false}, {Args: []string{"--int16", fmt.Sprintf("%d", int64(math.MaxInt32+1))}, Valid: false}, {Args: []string{"--int16", fmt.Sprintf("%d", int64(math.MinInt64))}, Valid: false}, {Args: []string{"--int16", fmt.Sprintf("%d", int64(math.MaxInt64))}, Valid: false}, {Args: []string{"--int16", fmt.Sprintf("%d", uint64(math.MaxInt64+1))}, Valid: false}, {Args: []string{"--int16", fmt.Sprintf("%d", uint64(math.MaxUint16))}, Valid: false}, {Args: []string{"--int16", fmt.Sprintf("%d", uint64(math.MaxUint16+1))}, Valid: false}, {Args: []string{"--int16", fmt.Sprintf("%d", uint64(math.MaxUint32))}, Valid: false}, {Args: []string{"--int16", fmt.Sprintf("%d", uint64(math.MaxUint32+1))}, Valid: false}, {Args: []string{"--int16", fmt.Sprintf("%d", uint64(math.MaxUint64))}, Valid: false}, {Args: []string{"--int16", fmt.Sprintf("%d", uint64(math.MaxUint64))}, Valid: false}, {Args: []string{"--int16", "1", "--int16", "2"}, Valid: false}, {Args: []string{"--int16", "1.0"}, Valid: false}, {Args: []string{"--int16", ""}, Valid: false}, {Args: []string{"--int16"}, Valid: false}, // Int32 {Args: []string{"--int32", fmt.Sprintf("%d", int64(math.MinInt8))}, Valid: true, Field: "Int32", Value: int32(math.MinInt8)}, {Args: []string{"--int32", fmt.Sprintf("%d", int64(math.MinInt8-1))}, Valid: true, Field: "Int32", Value: int32(math.MinInt8 - 1)}, {Args: []string{"--int32", fmt.Sprintf("%d", int64(math.MaxInt8))}, Valid: true, Field: "Int32", Value: int32(math.MaxInt8)}, {Args: []string{"--int32", fmt.Sprintf("%d", int64(math.MaxInt8+1))}, Valid: true, Field: "Int32", Value: int32(math.MaxInt8 + 1)}, {Args: []string{"--int32", fmt.Sprintf("%d", int64(math.MinInt16))}, Valid: true, Field: "Int32", Value: int32(math.MinInt16)}, {Args: []string{"--int32", fmt.Sprintf("%d", int64(math.MinInt16-1))}, Valid: true, Field: "Int32", Value: int32(math.MinInt16 - 1)}, {Args: []string{"--int32", fmt.Sprintf("%d", int64(math.MaxInt16))}, Valid: true, Field: "Int32", Value: int32(math.MaxInt16)}, {Args: []string{"--int32", fmt.Sprintf("%d", int64(math.MaxInt16+1))}, Valid: true, Field: "Int32", Value: int32(math.MaxInt16 + 1)}, {Args: []string{"--int32", fmt.Sprintf("%d", int64(math.MinInt32))}, Valid: true, Field: "Int32", Value: int32(math.MinInt32)}, {Args: []string{"--int32", fmt.Sprintf("%d", int64(math.MaxInt32))}, Valid: true, Field: "Int32", Value: int32(math.MaxInt32)}, {Args: []string{"--int32", fmt.Sprintf("%d", uint64(math.MaxUint8))}, Valid: true, Field: "Int32", Value: int32(math.MaxUint8)}, {Args: []string{"--int32", fmt.Sprintf("%d", uint64(math.MaxUint8+1))}, Valid: true, Field: "Int32", Value: int32(math.MaxUint8 + 1)}, {Args: []string{"--int32", fmt.Sprintf("%d", uint64(math.MaxUint16))}, Valid: true, Field: "Int32", Value: int32(math.MaxUint16)}, {Args: []string{"--int32", fmt.Sprintf("%d", uint64(math.MaxUint16+1))}, Valid: true, Field: "Int32", Value: int32(math.MaxUint16 + 1)}, {Args: []string{"--int32", fmt.Sprintf("%d", int64(math.MinInt32-1))}, Valid: false}, {Args: []string{"--int32", fmt.Sprintf("%d", int64(math.MaxInt32+1))}, Valid: false}, {Args: []string{"--int32", fmt.Sprintf("%d", int64(math.MinInt64))}, Valid: false}, {Args: []string{"--int32", fmt.Sprintf("%d", int64(math.MaxInt64))}, Valid: false}, {Args: []string{"--int32", fmt.Sprintf("%d", uint64(math.MaxInt64+1))}, Valid: false}, {Args: []string{"--int32", fmt.Sprintf("%d", uint64(math.MaxUint32))}, Valid: false}, {Args: []string{"--int32", fmt.Sprintf("%d", uint64(math.MaxUint32+1))}, Valid: false}, {Args: []string{"--int32", fmt.Sprintf("%d", uint64(math.MaxUint64))}, Valid: false}, {Args: []string{"--int32", fmt.Sprintf("%d", uint64(math.MaxUint64))}, Valid: false}, {Args: []string{"--int32", "1", "--int32", "2"}, Valid: false}, {Args: []string{"--int32", "1.0"}, Valid: false}, {Args: []string{"--int32", ""}, Valid: false}, {Args: []string{"--int32"}, Valid: false}, // Int64 {Args: []string{"--int64", fmt.Sprintf("%d", int64(math.MinInt8))}, Valid: true, Field: "Int64", Value: int64(math.MinInt8)}, {Args: []string{"--int64", fmt.Sprintf("%d", int64(math.MinInt8-1))}, Valid: true, Field: "Int64", Value: int64(math.MinInt8 - 1)}, {Args: []string{"--int64", fmt.Sprintf("%d", int64(math.MaxInt8))}, Valid: true, Field: "Int64", Value: int64(math.MaxInt8)}, {Args: []string{"--int64", fmt.Sprintf("%d", int64(math.MaxInt8+1))}, Valid: true, Field: "Int64", Value: int64(math.MaxInt8 + 1)}, {Args: []string{"--int64", fmt.Sprintf("%d", int64(math.MinInt16))}, Valid: true, Field: "Int64", Value: int64(math.MinInt16)}, {Args: []string{"--int64", fmt.Sprintf("%d", int64(math.MinInt16-1))}, Valid: true, Field: "Int64", Value: int64(math.MinInt16 - 1)}, {Args: []string{"--int64", fmt.Sprintf("%d", int64(math.MaxInt16))}, Valid: true, Field: "Int64", Value: int64(math.MaxInt16)}, {Args: []string{"--int64", fmt.Sprintf("%d", int64(math.MaxInt16+1))}, Valid: true, Field: "Int64", Value: int64(math.MaxInt16 + 1)}, {Args: []string{"--int64", fmt.Sprintf("%d", int64(math.MinInt32))}, Valid: true, Field: "Int64", Value: int64(math.MinInt32)}, {Args: []string{"--int64", fmt.Sprintf("%d", int64(math.MinInt32-1))}, Valid: true, Field: "Int64", Value: int64(math.MinInt32 - 1)}, {Args: []string{"--int64", fmt.Sprintf("%d", int64(math.MaxInt32))}, Valid: true, Field: "Int64", Value: int64(math.MaxInt32)}, {Args: []string{"--int64", fmt.Sprintf("%d", int64(math.MaxInt32+1))}, Valid: true, Field: "Int64", Value: int64(math.MaxInt32 + 1)}, {Args: []string{"--int64", fmt.Sprintf("%d", int64(math.MinInt64))}, Valid: true, Field: "Int64", Value: int64(math.MinInt64)}, {Args: []string{"--int64", fmt.Sprintf("%d", int64(math.MaxInt64))}, Valid: true, Field: "Int64", Value: int64(math.MaxInt64)}, {Args: []string{"--int64", fmt.Sprintf("%d", uint64(math.MaxUint8))}, Valid: true, Field: "Int64", Value: int64(math.MaxUint8)}, {Args: []string{"--int64", fmt.Sprintf("%d", uint64(math.MaxUint8+1))}, Valid: true, Field: "Int64", Value: int64(math.MaxUint8 + 1)}, {Args: []string{"--int64", fmt.Sprintf("%d", uint64(math.MaxUint16))}, Valid: true, Field: "Int64", Value: int64(math.MaxUint16)}, {Args: []string{"--int64", fmt.Sprintf("%d", uint64(math.MaxUint16+1))}, Valid: true, Field: "Int64", Value: int64(math.MaxUint16 + 1)}, {Args: []string{"--int64", fmt.Sprintf("%d", uint64(math.MaxUint32))}, Valid: true, Field: "Int64", Value: int64(math.MaxUint32)}, {Args: []string{"--int64", fmt.Sprintf("%d", uint64(math.MaxUint32+1))}, Valid: true, Field: "Int64", Value: int64(math.MaxUint32 + 1)}, {Args: []string{"--int64", fmt.Sprintf("%d", uint64(math.MaxInt64+1))}, Valid: false}, {Args: []string{"--int64", fmt.Sprintf("%d", uint64(math.MaxUint64))}, Valid: false}, {Args: []string{"--int64", fmt.Sprintf("%d", uint64(math.MaxUint64))}, Valid: false}, {Args: []string{"--int64", "1", "--int64", "2"}, Valid: false}, {Args: []string{"--int64", "1.0"}, Valid: false}, {Args: []string{"--int64", ""}, Valid: false}, {Args: []string{"--int64"}, Valid: false}, // Int {Args: []string{"--int", fmt.Sprintf("%d", int64(math.MinInt8))}, Valid: true, Field: "Int", Value: int(math.MinInt8)}, {Args: []string{"--int", fmt.Sprintf("%d", int64(math.MinInt8-1))}, Valid: true, Field: "Int", Value: int(math.MinInt8 - 1)}, {Args: []string{"--int", fmt.Sprintf("%d", int64(math.MaxInt8))}, Valid: true, Field: "Int", Value: int(math.MaxInt8)}, {Args: []string{"--int", fmt.Sprintf("%d", int64(math.MaxInt8+1))}, Valid: true, Field: "Int", Value: int(math.MaxInt8 + 1)}, {Args: []string{"--int", fmt.Sprintf("%d", int64(math.MinInt16))}, Valid: true, Field: "Int", Value: int(math.MinInt16)}, {Args: []string{"--int", fmt.Sprintf("%d", int64(math.MinInt16-1))}, Valid: true, Field: "Int", Value: int(math.MinInt16 - 1)}, {Args: []string{"--int", fmt.Sprintf("%d", int64(math.MaxInt16))}, Valid: true, Field: "Int", Value: int(math.MaxInt16)}, {Args: []string{"--int", fmt.Sprintf("%d", int64(math.MaxInt16+1))}, Valid: true, Field: "Int", Value: int(math.MaxInt16 + 1)}, {Args: []string{"--int", fmt.Sprintf("%d", int64(math.MinInt32))}, Valid: true, Field: "Int", Value: int(math.MinInt32)}, {Args: []string{"--int", fmt.Sprintf("%d", int64(math.MaxInt32))}, Valid: true, Field: "Int", Value: int(math.MaxInt32)}, {Args: []string{"--int", fmt.Sprintf("%d", uint64(math.MaxUint8))}, Valid: true, Field: "Int", Value: int(math.MaxUint8)}, {Args: []string{"--int", fmt.Sprintf("%d", uint64(math.MaxUint8+1))}, Valid: true, Field: "Int", Value: int(math.MaxUint8 + 1)}, {Args: []string{"--int", fmt.Sprintf("%d", uint64(math.MaxUint16))}, Valid: true, Field: "Int", Value: int(math.MaxUint16)}, {Args: []string{"--int", fmt.Sprintf("%d", uint64(math.MaxUint16+1))}, Valid: true, Field: "Int", Value: int(math.MaxUint16 + 1)}, {Args: []string{"--int", fmt.Sprintf("%d", uint64(math.MaxInt64+1))}, Valid: false}, {Args: []string{"--int", fmt.Sprintf("%d", uint64(math.MaxUint64))}, Valid: false}, {Args: []string{"--int", fmt.Sprintf("%d", uint64(math.MaxUint64))}, Valid: false}, {Args: []string{"--int", "1", "--int", "2"}, Valid: false}, {Args: []string{"--int", "1.0"}, Valid: false}, {Args: []string{"--int", ""}, Valid: false}, {Args: []string{"--int"}, Valid: false}, // Uint8 {Args: []string{"--uint8", fmt.Sprintf("%d", int64(math.MaxInt8))}, Valid: true, Field: "Uint8", Value: uint8(math.MaxInt8)}, {Args: []string{"--uint8", fmt.Sprintf("%d", int64(math.MaxInt8+1))}, Valid: true, Field: "Uint8", Value: uint8(math.MaxInt8 + 1)}, {Args: []string{"--uint8", fmt.Sprintf("%d", uint64(math.MaxUint8))}, Valid: true, Field: "Uint8", Value: uint8(math.MaxUint8)}, {Args: []string{"--uint8", fmt.Sprintf("%d", int64(math.MinInt8))}, Valid: false}, {Args: []string{"--uint8", fmt.Sprintf("%d", int64(math.MinInt8-1))}, Valid: false}, {Args: []string{"--uint8", fmt.Sprintf("%d", int64(math.MinInt16))}, Valid: false}, {Args: []string{"--uint8", fmt.Sprintf("%d", int64(math.MinInt16-1))}, Valid: false}, {Args: []string{"--uint8", fmt.Sprintf("%d", int64(math.MaxInt16))}, Valid: false}, {Args: []string{"--uint8", fmt.Sprintf("%d", int64(math.MaxInt16+1))}, Valid: false}, {Args: []string{"--uint8", fmt.Sprintf("%d", int64(math.MinInt32))}, Valid: false}, {Args: []string{"--uint8", fmt.Sprintf("%d", int64(math.MinInt32-1))}, Valid: false}, {Args: []string{"--uint8", fmt.Sprintf("%d", int64(math.MaxInt32))}, Valid: false}, {Args: []string{"--uint8", fmt.Sprintf("%d", int64(math.MaxInt32+1))}, Valid: false}, {Args: []string{"--uint8", fmt.Sprintf("%d", int64(math.MinInt64))}, Valid: false}, {Args: []string{"--uint8", fmt.Sprintf("%d", int64(math.MaxInt64))}, Valid: false}, {Args: []string{"--uint8", fmt.Sprintf("%d", uint64(math.MaxInt64+1))}, Valid: false}, {Args: []string{"--uint8", fmt.Sprintf("%d", uint64(math.MaxUint8+1))}, Valid: false}, {Args: []string{"--uint8", fmt.Sprintf("%d", uint64(math.MaxUint16))}, Valid: false}, {Args: []string{"--uint8", fmt.Sprintf("%d", uint64(math.MaxUint16+1))}, Valid: false}, {Args: []string{"--uint8", fmt.Sprintf("%d", uint64(math.MaxUint32))}, Valid: false}, {Args: []string{"--uint8", fmt.Sprintf("%d", uint64(math.MaxUint32+1))}, Valid: false}, {Args: []string{"--uint8", fmt.Sprintf("%d", uint64(math.MaxUint64))}, Valid: false}, {Args: []string{"--uint8", fmt.Sprintf("%d", uint64(math.MaxUint64))}, Valid: false}, {Args: []string{"--uint8", "1", "--uint8", "2"}, Valid: false}, {Args: []string{"--uint8", "1.0"}, Valid: false}, {Args: []string{"--uint8", ""}, Valid: false}, {Args: []string{"--uint8"}, Valid: false}, // Uint16 {Args: []string{"--uint16", fmt.Sprintf("%d", int64(math.MaxInt8))}, Valid: true, Field: "Uint16", Value: uint16(math.MaxInt8)}, {Args: []string{"--uint16", fmt.Sprintf("%d", int64(math.MaxInt8+1))}, Valid: true, Field: "Uint16", Value: uint16(math.MaxInt8 + 1)}, {Args: []string{"--uint16", fmt.Sprintf("%d", int64(math.MaxInt16))}, Valid: true, Field: "Uint16", Value: uint16(math.MaxInt16)}, {Args: []string{"--uint16", fmt.Sprintf("%d", int64(math.MaxInt16+1))}, Valid: true, Field: "Uint16", Value: uint16(math.MaxInt16 + 1)}, {Args: []string{"--uint16", fmt.Sprintf("%d", uint64(math.MaxUint8))}, Valid: true, Field: "Uint16", Value: uint16(math.MaxUint8)}, {Args: []string{"--uint16", fmt.Sprintf("%d", uint64(math.MaxUint8+1))}, Valid: true, Field: "Uint16", Value: uint16(math.MaxUint8 + 1)}, {Args: []string{"--uint16", fmt.Sprintf("%d", uint64(math.MaxUint16))}, Valid: true, Field: "Uint16", Value: uint16(math.MaxUint16)}, {Args: []string{"--uint16", fmt.Sprintf("%d", int64(math.MinInt8))}, Valid: false}, {Args: []string{"--uint16", fmt.Sprintf("%d", int64(math.MinInt8-1))}, Valid: false}, {Args: []string{"--uint16", fmt.Sprintf("%d", int64(math.MinInt16))}, Valid: false}, {Args: []string{"--uint16", fmt.Sprintf("%d", int64(math.MinInt16-1))}, Valid: false}, {Args: []string{"--uint16", fmt.Sprintf("%d", int64(math.MinInt32))}, Valid: false}, {Args: []string{"--uint16", fmt.Sprintf("%d", int64(math.MinInt32-1))}, Valid: false}, {Args: []string{"--uint16", fmt.Sprintf("%d", int64(math.MaxInt32))}, Valid: false}, {Args: []string{"--uint16", fmt.Sprintf("%d", int64(math.MaxInt32+1))}, Valid: false}, {Args: []string{"--uint16", fmt.Sprintf("%d", int64(math.MinInt64))}, Valid: false}, {Args: []string{"--uint16", fmt.Sprintf("%d", int64(math.MaxInt64))}, Valid: false}, {Args: []string{"--uint16", fmt.Sprintf("%d", uint64(math.MaxInt64+1))}, Valid: false}, {Args: []string{"--uint16", fmt.Sprintf("%d", uint64(math.MaxUint16+1))}, Valid: false}, {Args: []string{"--uint16", fmt.Sprintf("%d", uint64(math.MaxUint32))}, Valid: false}, {Args: []string{"--uint16", fmt.Sprintf("%d", uint64(math.MaxUint32+1))}, Valid: false}, {Args: []string{"--uint16", fmt.Sprintf("%d", uint64(math.MaxUint64))}, Valid: false}, {Args: []string{"--uint16", fmt.Sprintf("%d", uint64(math.MaxUint64))}, Valid: false}, {Args: []string{"--uint16", "1", "--uint16", "2"}, Valid: false}, {Args: []string{"--uint16", "1.0"}, Valid: false}, {Args: []string{"--uint16", ""}, Valid: false}, {Args: []string{"--uint16"}, Valid: false}, // Uint32 {Args: []string{"--uint32", fmt.Sprintf("%d", int64(math.MaxInt8))}, Valid: true, Field: "Uint32", Value: uint32(math.MaxInt8)}, {Args: []string{"--uint32", fmt.Sprintf("%d", int64(math.MaxInt8+1))}, Valid: true, Field: "Uint32", Value: uint32(math.MaxInt8 + 1)}, {Args: []string{"--uint32", fmt.Sprintf("%d", int64(math.MaxInt16))}, Valid: true, Field: "Uint32", Value: uint32(math.MaxInt16)}, {Args: []string{"--uint32", fmt.Sprintf("%d", int64(math.MaxInt16+1))}, Valid: true, Field: "Uint32", Value: uint32(math.MaxInt16 + 1)}, {Args: []string{"--uint32", fmt.Sprintf("%d", int64(math.MaxInt32))}, Valid: true, Field: "Uint32", Value: uint32(math.MaxInt32)}, {Args: []string{"--uint32", fmt.Sprintf("%d", int64(math.MaxInt32+1))}, Valid: true, Field: "Uint32", Value: uint32(math.MaxInt32 + 1)}, {Args: []string{"--uint32", fmt.Sprintf("%d", uint64(math.MaxUint8))}, Valid: true, Field: "Uint32", Value: uint32(math.MaxUint8)}, {Args: []string{"--uint32", fmt.Sprintf("%d", uint64(math.MaxUint8+1))}, Valid: true, Field: "Uint32", Value: uint32(math.MaxUint8 + 1)}, {Args: []string{"--uint32", fmt.Sprintf("%d", uint64(math.MaxUint16))}, Valid: true, Field: "Uint32", Value: uint32(math.MaxUint16)}, {Args: []string{"--uint32", fmt.Sprintf("%d", uint64(math.MaxUint16+1))}, Valid: true, Field: "Uint32", Value: uint32(math.MaxUint16 + 1)}, {Args: []string{"--uint32", fmt.Sprintf("%d", uint64(math.MaxUint32))}, Valid: true, Field: "Uint32", Value: uint32(math.MaxUint32)}, {Args: []string{"--uint32", fmt.Sprintf("%d", int64(math.MinInt8))}, Valid: false}, {Args: []string{"--uint32", fmt.Sprintf("%d", int64(math.MinInt8-1))}, Valid: false}, {Args: []string{"--uint32", fmt.Sprintf("%d", int64(math.MinInt16))}, Valid: false}, {Args: []string{"--uint32", fmt.Sprintf("%d", int64(math.MinInt16-1))}, Valid: false}, {Args: []string{"--uint32", fmt.Sprintf("%d", int64(math.MinInt32))}, Valid: false}, {Args: []string{"--uint32", fmt.Sprintf("%d", int64(math.MinInt32-1))}, Valid: false}, {Args: []string{"--uint32", fmt.Sprintf("%d", int64(math.MinInt64))}, Valid: false}, {Args: []string{"--uint32", fmt.Sprintf("%d", int64(math.MaxInt64))}, Valid: false}, {Args: []string{"--uint32", fmt.Sprintf("%d", uint64(math.MaxInt64+1))}, Valid: false}, {Args: []string{"--uint32", fmt.Sprintf("%d", uint64(math.MaxUint32+1))}, Valid: false}, {Args: []string{"--uint32", fmt.Sprintf("%d", uint64(math.MaxUint64))}, Valid: false}, {Args: []string{"--uint32", fmt.Sprintf("%d", uint64(math.MaxUint64))}, Valid: false}, {Args: []string{"--uint32", "1", "--uint32", "1"}, Valid: false}, {Args: []string{"--uint32", "1.0"}, Valid: false}, {Args: []string{"--uint32", ""}, Valid: false}, {Args: []string{"--uint32"}, Valid: false}, // Uint64 {Args: []string{"--uint64", fmt.Sprintf("%d", int64(math.MaxInt8))}, Valid: true, Field: "Uint64", Value: uint64(math.MaxInt8)}, {Args: []string{"--uint64", fmt.Sprintf("%d", int64(math.MaxInt8+1))}, Valid: true, Field: "Uint64", Value: uint64(math.MaxInt8 + 1)}, {Args: []string{"--uint64", fmt.Sprintf("%d", int64(math.MaxInt16))}, Valid: true, Field: "Uint64", Value: uint64(math.MaxInt16)}, {Args: []string{"--uint64", fmt.Sprintf("%d", int64(math.MaxInt16+1))}, Valid: true, Field: "Uint64", Value: uint64(math.MaxInt16 + 1)}, {Args: []string{"--uint64", fmt.Sprintf("%d", int64(math.MaxInt32))}, Valid: true, Field: "Uint64", Value: uint64(math.MaxInt32)}, {Args: []string{"--uint64", fmt.Sprintf("%d", int64(math.MaxInt32+1))}, Valid: true, Field: "Uint64", Value: uint64(math.MaxInt32 + 1)}, {Args: []string{"--uint64", fmt.Sprintf("%d", int64(math.MaxInt64))}, Valid: true, Field: "Uint64", Value: uint64(math.MaxInt64)}, {Args: []string{"--uint64", fmt.Sprintf("%d", uint64(math.MaxInt64+1))}, Valid: true, Field: "Uint64", Value: uint64(math.MaxInt64 + 1)}, {Args: []string{"--uint64", fmt.Sprintf("%d", uint64(math.MaxUint8))}, Valid: true, Field: "Uint64", Value: uint64(math.MaxUint8)}, {Args: []string{"--uint64", fmt.Sprintf("%d", uint64(math.MaxUint8+1))}, Valid: true, Field: "Uint64", Value: uint64(math.MaxUint8 + 1)}, {Args: []string{"--uint64", fmt.Sprintf("%d", uint64(math.MaxUint16))}, Valid: true, Field: "Uint64", Value: uint64(math.MaxUint16)}, {Args: []string{"--uint64", fmt.Sprintf("%d", uint64(math.MaxUint16+1))}, Valid: true, Field: "Uint64", Value: uint64(math.MaxUint16 + 1)}, {Args: []string{"--uint64", fmt.Sprintf("%d", uint64(math.MaxUint32))}, Valid: true, Field: "Uint64", Value: uint64(math.MaxUint32)}, {Args: []string{"--uint64", fmt.Sprintf("%d", uint64(math.MaxUint32+1))}, Valid: true, Field: "Uint64", Value: uint64(math.MaxUint32 + 1)}, {Args: []string{"--uint64", fmt.Sprintf("%d", uint64(math.MaxUint64))}, Valid: true, Field: "Uint64", Value: uint64(math.MaxUint64)}, {Args: []string{"--uint64", fmt.Sprintf("%d", int64(math.MinInt8))}, Valid: false}, {Args: []string{"--uint64", fmt.Sprintf("%d", int64(math.MinInt8-1))}, Valid: false}, {Args: []string{"--uint64", fmt.Sprintf("%d", int64(math.MinInt16))}, Valid: false}, {Args: []string{"--uint64", fmt.Sprintf("%d", int64(math.MinInt16-1))}, Valid: false}, {Args: []string{"--uint64", fmt.Sprintf("%d", int64(math.MinInt32))}, Valid: false}, {Args: []string{"--uint64", fmt.Sprintf("%d", int64(math.MinInt32-1))}, Valid: false}, {Args: []string{"--uint64", fmt.Sprintf("%d", int64(math.MinInt64))}, Valid: false}, {Args: []string{"--uint64", fmt.Sprintf("%d", int64(math.MinInt64))}, Valid: false}, {Args: []string{"--uint64", "1", "--uint64", "1"}, Valid: false}, {Args: []string{"--uint64", "1.0"}, Valid: false}, {Args: []string{"--uint64", ""}, Valid: false}, {Args: []string{"--uint64"}, Valid: false}, // Uint {Args: []string{"--uint", fmt.Sprintf("%d", int64(math.MaxInt8))}, Valid: true, Field: "Uint", Value: uint(math.MaxInt8)}, {Args: []string{"--uint", fmt.Sprintf("%d", int64(math.MaxInt8+1))}, Valid: true, Field: "Uint", Value: uint(math.MaxInt8 + 1)}, {Args: []string{"--uint", fmt.Sprintf("%d", int64(math.MaxInt16))}, Valid: true, Field: "Uint", Value: uint(math.MaxInt16)}, {Args: []string{"--uint", fmt.Sprintf("%d", int64(math.MaxInt16+1))}, Valid: true, Field: "Uint", Value: uint(math.MaxInt16 + 1)}, {Args: []string{"--uint", fmt.Sprintf("%d", int64(math.MaxInt32))}, Valid: true, Field: "Uint", Value: uint(math.MaxInt32)}, {Args: []string{"--uint", fmt.Sprintf("%d", int64(math.MaxInt32+1))}, Valid: true, Field: "Uint", Value: uint(math.MaxInt32 + 1)}, {Args: []string{"--uint", fmt.Sprintf("%d", uint64(math.MaxUint8))}, Valid: true, Field: "Uint", Value: uint(math.MaxUint8)}, {Args: []string{"--uint", fmt.Sprintf("%d", uint64(math.MaxUint8+1))}, Valid: true, Field: "Uint", Value: uint(math.MaxUint8 + 1)}, {Args: []string{"--uint", fmt.Sprintf("%d", uint64(math.MaxUint16))}, Valid: true, Field: "Uint", Value: uint(math.MaxUint16)}, {Args: []string{"--uint", fmt.Sprintf("%d", uint64(math.MaxUint16+1))}, Valid: true, Field: "Uint", Value: uint(math.MaxUint16 + 1)}, {Args: []string{"--uint", fmt.Sprintf("%d", uint64(math.MaxUint32))}, Valid: true, Field: "Uint", Value: uint(math.MaxUint32)}, {Args: []string{"--uint", fmt.Sprintf("%d", int64(math.MinInt8))}, Valid: false}, {Args: []string{"--uint", fmt.Sprintf("%d", int64(math.MinInt8-1))}, Valid: false}, {Args: []string{"--uint", fmt.Sprintf("%d", int64(math.MinInt16))}, Valid: false}, {Args: []string{"--uint", fmt.Sprintf("%d", int64(math.MinInt16-1))}, Valid: false}, {Args: []string{"--uint", fmt.Sprintf("%d", int64(math.MinInt32))}, Valid: false}, {Args: []string{"--uint", fmt.Sprintf("%d", int64(math.MinInt32-1))}, Valid: false}, {Args: []string{"--uint", fmt.Sprintf("%d", int64(math.MinInt32-1))}, Valid: false}, {Args: []string{"--uint", "1", "--uint", "2"}, Valid: false}, {Args: []string{"--uint", "1.0"}, Valid: false}, {Args: []string{"--uint", ""}, Valid: false}, {Args: []string{"--uint"}, Valid: false}, // Float32 {Args: []string{"--float32", "-1.23"}, Valid: true, Field: "Float32", Value: float32(-1.23)}, {Args: []string{"--float32", "4.56"}, Valid: true, Field: "Float32", Value: float32(4.56)}, {Args: []string{"--float32", "-1.2e3"}, Valid: true, Field: "Float32", Value: float32(-1.2e3)}, {Args: []string{"--float32", "4.5e6"}, Valid: true, Field: "Float32", Value: float32(4.5e6)}, {Args: []string{"--float32", "-1.2E3"}, Valid: true, Field: "Float32", Value: float32(-1.2e3)}, {Args: []string{"--float32", "4.5E6"}, Valid: true, Field: "Float32", Value: float32(4.5e6)}, {Args: []string{"--float32", "-1.2e+3"}, Valid: true, Field: "Float32", Value: float32(-1.2e3)}, {Args: []string{"--float32", "4.5e+6"}, Valid: true, Field: "Float32", Value: float32(4.5e6)}, {Args: []string{"--float32", "-1.2E+3"}, Valid: true, Field: "Float32", Value: float32(-1.2e3)}, {Args: []string{"--float32", "4.5E+6"}, Valid: true, Field: "Float32", Value: float32(4.5e6)}, {Args: []string{"--float32", "-1.2e-3"}, Valid: true, Field: "Float32", Value: float32(-1.2e-3)}, {Args: []string{"--float32", "4.5e-6"}, Valid: true, Field: "Float32", Value: float32(4.5e-6)}, {Args: []string{"--float32", "-1.2E-3"}, Valid: true, Field: "Float32", Value: float32(-1.2e-3)}, {Args: []string{"--float32", "4.5E-6"}, Valid: true, Field: "Float32", Value: float32(4.5e-6)}, {Args: []string{"--float32", strconv.FormatFloat(math.SmallestNonzeroFloat32, 'f', -1, 64)}, Valid: true, Field: "Float32", Value: float32(math.SmallestNonzeroFloat32)}, {Args: []string{"--float32", strconv.FormatFloat(math.MaxFloat32, 'f', -1, 64)}, Valid: true, Field: "Float32", Value: float32(math.MaxFloat32)}, {Args: []string{"--float32", strconv.FormatFloat(math.MaxFloat32, 'f', -1, 64)}, Valid: true, Field: "Float32", Value: float32(math.MaxFloat32)}, // XXX Skipped -- Not sure how to handle this!! {Args: []string{"--float32", strconv.FormatFloat(math.SmallestNonzeroFloat64, 'f', -1, 64)}, Field: "Float32", SkipReason: "Not sure how to handle the precision on this"}, {Args: []string{"--float32", strconv.FormatFloat(math.MaxFloat64, 'f', -1, 64)}, Valid: false}, {Args: []string{"--float32", strconv.FormatFloat(math.MaxFloat64, 'f', -1, 64)}, Valid: false}, {Args: []string{"--float32", "1"}, Valid: true, Field: "Float32", Value: float32(1)}, {Args: []string{"--float32", "-1"}, Valid: true, Field: "Float32", Value: float32(-1)}, {Args: []string{"--float32", "1.0", "--float32", "2.0"}, Valid: false}, {Args: []string{"--float32", ""}, Valid: false}, {Args: []string{"--float32"}, Valid: false}, // Float64 {Args: []string{"--float64", "-1.23"}, Valid: true, Field: "Float64", Value: float64(-1.23)}, {Args: []string{"--float64", "4.56"}, Valid: true, Field: "Float64", Value: float64(4.56)}, {Args: []string{"--float64", "-1.2e3"}, Valid: true, Field: "Float64", Value: float64(-1.2e3)}, {Args: []string{"--float64", "4.5e6"}, Valid: true, Field: "Float64", Value: float64(4.5e6)}, {Args: []string{"--float64", "-1.2E3"}, Valid: true, Field: "Float64", Value: float64(-1.2e3)}, {Args: []string{"--float64", "4.5E6"}, Valid: true, Field: "Float64", Value: float64(4.5e6)}, {Args: []string{"--float64", "-1.2e+3"}, Valid: true, Field: "Float64", Value: float64(-1.2e3)}, {Args: []string{"--float64", "4.5e+6"}, Valid: true, Field: "Float64", Value: float64(4.5e6)}, {Args: []string{"--float64", "-1.2E+3"}, Valid: true, Field: "Float64", Value: float64(-1.2e3)}, {Args: []string{"--float64", "4.5E+6"}, Valid: true, Field: "Float64", Value: float64(4.5e6)}, {Args: []string{"--float64", "-1.2e-3"}, Valid: true, Field: "Float64", Value: float64(-1.2e-3)}, {Args: []string{"--float64", "4.5e-6"}, Valid: true, Field: "Float64", Value: float64(4.5e-6)}, {Args: []string{"--float64", "-1.2E-3"}, Valid: true, Field: "Float64", Value: float64(-1.2e-3)}, {Args: []string{"--float64", "4.5E-6"}, Valid: true, Field: "Float64", Value: float64(4.5e-6)}, {Args: []string{"--float64", strconv.FormatFloat(math.SmallestNonzeroFloat32, 'f', -1, 64)}, Valid: true, Field: "Float64", Value: float64(math.SmallestNonzeroFloat32)}, {Args: []string{"--float64", strconv.FormatFloat(math.MaxFloat32, 'f', -1, 64)}, Valid: true, Field: "Float64", Value: float64(math.MaxFloat32)}, {Args: []string{"--float64", strconv.FormatFloat(math.SmallestNonzeroFloat64, 'f', -1, 64)}, Valid: true, Field: "Float64", Value: float64(math.SmallestNonzeroFloat64)}, {Args: []string{"--float64", strconv.FormatFloat(math.MaxFloat64, 'f', -1, 64)}, Valid: true, Field: "Float64", Value: float64(math.MaxFloat64)}, {Args: []string{"--float64", "1"}, Valid: true, Field: "Float64", Value: float64(1)}, {Args: []string{"--float64", "-1"}, Valid: true, Field: "Float64", Value: float64(-1)}, {Args: []string{"--float64", "1.0", "--float64", "2.0"}, Valid: false}, {Args: []string{"--float64", ""}, Valid: false}, {Args: []string{"--float64"}, Valid: false}, } func TestBasicFields(t *testing.T) { for _, test := range basicFieldTests { spec := &basicFieldSpec{} runFieldTest(t, spec, test) } } /* * Test invalid specs */ var invalidSpecTests = []struct { Description string Spec interface{} }{ // Invalid command specs { Description: "Commands must have a name 1", Spec: &struct { Command struct{} `command:","` }{}, }, { Description: "Commands must have a name 2", Spec: &struct { Command struct{} `command:" "` }{}, }, { Description: "Commands must have a single name", Spec: &struct { Command struct{} `command:"one,two"` }{}, }, { Description: "Command names cannot have a leading '-' prefix", Spec: &struct { Command struct{} `command:"-command"` }{}, }, { Description: "Command aliases cannot have a leading '-' prefix", Spec: &struct { Command struct{} `command:"command" alias:"-alias"` }{}, }, { Description: "Commands cannot have placeholders", Spec: &struct { Command struct{} `command:"command" placeholder:"PLACEHOLDER"` }{}, }, { Description: "Commands cannot have default values", Spec: &struct { Command struct{} `command:"command" default:"default"` }{}, }, { Description: "Commands cannot have env values", Spec: &struct { Command struct{} `command:"command" env:"ENV_VALUE"` }{}, }, { Description: "Command fields must be exported", Spec: &struct { command struct{} `command:"command"` }{}, }, { Description: "Command and alias names must be unique 1", Spec: &struct { Command struct{} `command:"foo" alias:"foo"` }{}, }, { Description: "Command and alias names must be unique 2", Spec: &struct { Command1 struct{} `command:"foo"` Command2 struct{} `command:"foo"` }{}, }, { Description: "Command and alias names must be unique 3", Spec: &struct { Command1 struct{} `command:"foo"` Command2 struct{} `command:"b" alias:"foo"` }{}, }, { Description: "Command and alias names must be unique 4", Spec: &struct { Command1 struct{} `command:"a" alias:"foo"` Command2 struct{} `command:"b" alias:"foo"` }{}, }, { Description: "Command specs must be a pointer to struct 1", Spec: struct{}{}, }, { Description: "Command specs must be a pointer to struct 2", Spec: 42, }, { Description: "Command specs must be a pointer to struct 3", Spec: (*int)(nil), }, // Invalid option specs { Description: "Options cannot have aliases", Spec: &struct { Option int `option:"option" alias:"alias" description:"option with an alias"` }{}, }, { Description: "Options must have a name 1", Spec: &struct { Option int `option:"," description:"option with no name"` }{}, }, { Description: "Options must have a name 2", Spec: &struct { Option int `option:" " description:"option with no name"` }{}, }, { Description: "Long option names cannot have a leading '-' prefix", Spec: &struct { Option int `option:"-option" description:"leading dash prefix"` }{}, }, { Description: "Short option names cannot have a leading '-' prefix", Spec: &struct { Option int `option:"-o" description:"leading dash prefix"` }{}, }, { Description: "Option fields must be exported", Spec: &struct { option int `option:"option" description:"non-exported field"` }{}, }, { Description: "Bools cannot be options", Spec: &struct { Option bool `option:"b" description:"boolean option"` }{}, }, { Description: "Option names must be unique 1", Spec: &struct { Option1 int `option:"foo"` Option2 int `option:"foo"` }{}, }, { Description: "Option names must be unique 2", Spec: &struct { Option1 int `option:"a, foo"` Option2 int `option:"b, foo"` }{}, }, { Description: "Option names must be unique 3", Spec: &struct { Flag bool `flag:"foo"` Option int `option:"foo"` }{}, }, { Description: "Not a supported option type", Spec: &struct { Option map[string]int `option:"foo"` }{}, }, // Invalid flag specs { Description: "Flags cannot have aliases", Spec: &struct { Flag bool `flag:"flag" alias:"alias" description:"flag with an alias"` }{}, }, { Description: "Flags cannot have placeholders", Spec: &struct { Flag bool `flag:"flag" placeholder:"PLACEHOLDER" description:"placeholder on flag"` }{}, }, { Description: "Flags cannot have default values", Spec: &struct { Flag bool `flag:"flag" default:"default" description:"default on flag"` }{}, }, { Description: "Flags cannot have env values", Spec: &struct { Flag bool `flag:"flag" env:"ENV_VALUE" description:"env on flag"` }{}, }, { Description: "Flags must have a name 1", Spec: &struct { Flag bool `flag:"," description:"flag with no name"` }{}, }, { Description: "Flags must have a name 2", Spec: &struct { Flag bool `flag:" " description:"flag with no name"` }{}, }, { Description: "Long flag names cannot have a leading '-' prefix", Spec: &struct { Flag bool `flag:"-flag" description:"leading dash prefix"` }{}, }, { Description: "Short flag names cannot have a leading '-' prefix", Spec: &struct { Flag bool `flag:"-f" description:"leading dash prefix"` }{}, }, { Description: "Flag fields must be exported", Spec: &struct { flag int `flag:"flag" description:"non-exported field"` }{}, }, { Description: "Flag names must be unique 1", Spec: &struct { Flag1 bool `flag:"foo"` Flag2 bool `flag:"foo"` }{}, }, { Description: "Flag names must be unique 2", Spec: &struct { Flag1 bool `flag:"a, foo"` Flag2 bool `flag:"b, foo"` }{}, }, { Description: "Flag names must be unique 3", Spec: &struct { Flag bool `flag:"foo"` Option int `option:"foo"` }{}, }, { Description: "Flag may only be bools, ints, and OptionDecoders 1", Spec: &struct { Flag string `flag:"foo"` }{}, }, { Description: "Flag may only be bools, ints, and OptionDecoders 2", Spec: &struct { Flag int32 `flag:"foo"` }{}, }, { Description: "Flag may only be bools, ints, and OptionDecoders 3", Spec: &struct { Flag struct{} `flag:"foo"` }{}, }, // Invalid mixes of command, flag, and option { Description: "Commands cannot be options", Spec: &struct { Command struct{} `command:"command" option:"option" description:"command as option"` }{}, }, { Description: "Commands cannot be flags", Spec: &struct { Command struct{} `command:"command" flag:"flag" description:"command as flag"` }{}, }, { Description: "Options cannot be commands", Spec: &struct { Option int `option:"option" command:"command" description:"option as command"` }{}, }, { Description: "Options cannot be flags", Spec: &struct { Option int `option:"option" flag:"flag" description:"option as flag"` }{}, }, { Description: "Flags cannot be commands", Spec: &struct { Flag bool `flag:"flag" command:"command" description:"flag as command"` }{}, }, { Description: "Flags cannot be options", Spec: &struct { Flag bool `flag:"flag" option:"option" description:"flag as option"` }{}, }, } func TestInvalidSpecs(t *testing.T) { for _, test := range invalidSpecTests { err := newInvalidCommand(test.Spec) if err == nil { t.Errorf("Expected error creating spec, but none received. Test: %s", test.Description) continue } } } func newInvalidCommand(spec interface{}) (err error) { defer func() { r := recover() if r != nil { switch e := r.(type) { case commandError: err = e case optionError: err = e default: panic(e) } } }() New("test", spec) return nil } var invalidCommandTests = []struct { Description string Command *Command }{ { Description: "Command name cannot be empty", Command: &Command{Name: ""}, }, { Description: "Command names cannot begin with -", Command: &Command{Name: "-command"}, }, { Description: "Command aliases cannot begin with -", Command: &Command{Name: "command", Aliases: []string{"-alias"}}, }, { Description: "Command names cannot have spaces 1", Command: &Command{Name: " command"}, }, { Description: "Command names cannot have spaces 2", Command: &Command{Name: "command "}, }, { Description: "Command names cannot have spaces 3", Command: &Command{Name: "command spaces"}, }, { Description: "Command aliases cannot begin with -", Command: &Command{Name: "command", Aliases: []string{"-alias"}}, }, { Description: "Command aliases cannot have spaces 1", Command: &Command{Name: "command", Aliases: []string{" alias"}}, }, { Description: "Command aliases cannot have spaces 2", Command: &Command{Name: "command", Aliases: []string{"alias "}}, }, { Description: "Command aliases cannot have spaces 3", Command: &Command{Name: "command", Aliases: []string{"alias spaces"}}, }, } func TestDirectCommandValidation(t *testing.T) { for _, test := range invalidCommandTests { err := checkInvalidCommand(test.Command) if err == nil { t.Errorf("Expected error validating command, but none received. Test: %s", test.Description) continue } } } func checkInvalidCommand(cmd *Command) (err error) { defer func() { r := recover() if r != nil { switch e := r.(type) { case commandError: err = e case optionError: err = e default: panic(e) } } }() cmd.validate() return nil } func TestGroupCommands(t *testing.T) { spec := &struct { Command1 struct{} `command:"command1"` Command2 struct{} `command:"command2"` }{} cmd := New("test", spec) group := cmd.GroupCommands("command1") if len(group.Commands) != 1 || group.Commands[0].Name != "command1" { t.Errorf("Expected a single command group with command %q", "command1") } group = cmd.GroupCommands("command2") if len(group.Commands) != 1 || group.Commands[0].Name != "command2" { t.Errorf("Expected a single command group with command %q", "command2") } group = cmd.GroupCommands("command1", "command2") if len(group.Commands) != 2 || group.Commands[0].Name != "command1" || group.Commands[1].Name != "command2" { t.Errorf("Expected a single command group with commands %q and %q", "command1", "command2") } group = cmd.GroupCommands("command2", "command1") if len(group.Commands) != 2 || group.Commands[0].Name != "command2" || group.Commands[1].Name != "command1" { t.Errorf("Expected a single command group with commands %q and %q", "command2", "command1") } err := checkInvalidCommandGroup(cmd, "command3") if err == nil { t.Errorf("Expected an error to occur grouping an unknown command, but none encountered.") } err = checkInvalidCommandGroup(cmd, "command1", "command3") if err == nil { t.Errorf("Expected an error to occur grouping an unknown command, but none encountered.") } } func checkInvalidCommandGroup(cmd *Command, name ...string) (err error) { defer func() { r := recover() if r != nil { switch e := r.(type) { case commandError: err = e case optionError: err = e default: panic(e) } } }() cmd.GroupCommands(name...) return nil } func TestGroupOptions(t *testing.T) { spec := &struct { Option1 int `option:"option1"` Option2 int `option:"option2"` }{} cmd := New("test", spec) group := cmd.GroupOptions("option1") if len(group.Options) != 1 || group.Options[0].Names[0] != "option1" { t.Errorf("Expected a single option group with option %q", "option1") } group = cmd.GroupOptions("option2") if len(group.Options) != 1 || group.Options[0].Names[0] != "option2" { t.Errorf("Expected a single option group with option %q", "option2") } group = cmd.GroupOptions("option1", "option2") if len(group.Options) != 2 || group.Options[0].Names[0] != "option1" || group.Options[1].Names[0] != "option2" { t.Errorf("Expected a single option group with options %q and %q", "option1", "option2") } group = cmd.GroupOptions("option2", "option1") if len(group.Options) != 2 || group.Options[0].Names[0] != "option2" || group.Options[1].Names[0] != "option1" { t.Errorf("Expected a single option group with options %q and %q", "option2", "option1") } err := checkInvalidOptionGroup(cmd, "option3") if err == nil { t.Errorf("Expected an error to occur grouping an unknown option, but none encountered.") } err = checkInvalidOptionGroup(cmd, "option1", "option3") if err == nil { t.Errorf("Expected an error to occur grouping an unknown option, but none encountered.") } } func checkInvalidOptionGroup(cmd *Command, name ...string) (err error) { defer func() { r := recover() if r != nil { switch e := r.(type) { case commandError: err = e case optionError: err = e default: panic(e) } } }() cmd.GroupOptions(name...) return nil } func TestCheckUnknownTagType(t *testing.T) { defer func() { spec := struct { Bogus int `bogus:"bogus"` }{} rval := reflect.ValueOf(spec) field, present := rval.Type().FieldByName("Bogus") if !present { t.Errorf("Expected Bogus field to be present") return } defer func() { recover() }() checkTags(field, "bogus") t.Errorf("Expected checkFields() to panic on unknown tag %q, but it didn't happen", "bogus") }() } /* * Misc coverage tests to ensure code doesn't panic/blow-up */ func TestCommandError(t *testing.T) { err := commandError{fmt.Errorf("test")} if err.Error() != "test" { t.Errorf("Expected commandError to return underlying error string. Expected: %q, Received: %q", "test", err.Error()) } } <|start_filename|>example_convenience_test.go<|end_filename|> // Copyright 2016 <NAME>. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package writ_test import ( "bufio" "errors" "fmt" "github.com/bobziuchkovski/writ" "io" "os" "strings" ) type ReplacerCmd struct { Input io.Reader `option:"i" description:"Read input values from FILE (default: stdin)" default:"-" placeholder:"FILE"` Output io.WriteCloser `option:"o" description:"Write output to FILE (default: stdout)" default:"-" placeholder:"FILE"` Replacements map[string]string `option:"r, replace" description:"Replace occurrences of ORIG with NEW" placeholder:"ORIG=NEW"` HelpFlag bool `flag:"h, help" description:"Display this help text and exit"` } // This example demonstrates some of the convenience features offered by writ. // It uses writ's support for io types and default values to ensure the Input // and Output fields are initialized. These default to stdin and stdout due // to the default:"-" field tags. The user may specify -i or -o to read from // or write to a file. Similarly, the Replacements map is initialized with // key=value pairs for every -r/--replace option the user specifies. func Example_convenience() { replacer := &ReplacerCmd{} cmd := writ.New("replacer", replacer) cmd.Help.Usage = "Usage: replacer [OPTION]..." cmd.Help.Header = "Perform text replacement according to the -r/--replace option" cmd.Help.Footer = "By default, replacer reads from stdin and write to stdout. Use the -i and -o options to override." // Decode input arguments _, positional, err := cmd.Decode(os.Args[1:]) if err != nil || replacer.HelpFlag { cmd.ExitHelp(err) } if len(positional) > 0 { cmd.ExitHelp(errors.New("replacer does not accept positional arguments")) } // At this point, the ReplacerCmd's Input, Output, and Replacements fields are all // known-valid and initialized, so we can run the replacement. err = replacer.Replace() if err != nil { fmt.Fprintf(os.Stderr, "Error: %s\n", err) os.Exit(1) } } // The Replace() method performs the input/output replacements, but is // not relevant to the example itself. func (r ReplacerCmd) Replace() error { var pairs []string for k, v := range r.Replacements { pairs = append(pairs, k, v) } replacer := strings.NewReplacer(pairs...) scanner := bufio.NewScanner(r.Input) for scanner.Scan() { line := scanner.Text() _, err := io.WriteString(r.Output, replacer.Replace(line)+"\n") if err != nil { return err } } err := scanner.Err() if err != nil { return err } return r.Output.Close() // Help Output: // Usage: replacer [OPTION]... // Perform text replacement according to the -r/--replace option // // Available Options: // -i FILE Read input values from FILE (default: stdin) // -o FILE Write output to FILE (default: stdout) // -r, --replace=ORIG=NEW Replace occurrences of ORIG with NEW // -h, --help Display this help text and exit // // By default, replacer reads from stdin and write to stdout. Use the -i and -o options to override. } <|start_filename|>help_test.go<|end_filename|> // Copyright (c) 2016 <NAME> // // 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. package writ import ( "bytes" "io/ioutil" "testing" "text/template" ) var helpFormattingTests = []struct { Description string Spec interface{} Rendered string }{ { Description: "A single option", Spec: &struct { Flag bool `flag:"h, help" description:"Display this text and exit"` }{}, Rendered: `Usage: test [OPTION]... [ARG]... Available Options: -h, --help Display this text and exit `, }, { Description: "A couple options", Spec: &struct { Flag bool `flag:"h" description:"Display this text and exit"` Option int `option:"i, int" description:"An int option" placeholder:"INT"` }{}, Rendered: `Usage: test [OPTION]... [ARG]... Available Options: -h Display this text and exit -i, --int=INT An int option `, }, { Description: "Multiple long and short names for an option", Spec: &struct { Option int `option:"i, I, int, Int" description:"An int option" placeholder:"INT"` }{}, Rendered: `Usage: test [OPTION]... [ARG]... Available Options: -i, -I, --int, --Int=INT An int option `, }, { Description: "An option with short-form placeholder", Spec: &struct { Option int `option:"i" description:"An int option" placeholder:"INT"` }{}, Rendered: `Usage: test [OPTION]... [ARG]... Available Options: -i INT An int option `, }, { Description: "A single command", Spec: &struct { Command struct{} `command:"command" description:"A command"` }{}, Rendered: `Usage: test [OPTION]... [ARG]... Available Commands: command A command `, }, { Description: "A single option and single command", Spec: &struct { Option int `option:"i" description:"An int option" placeholder:"INT"` Command struct{} `command:"command" description:"A command"` }{}, Rendered: `Usage: test [OPTION]... [ARG]... Available Options: -i INT An int option Available Commands: command A command `, }, { Description: "Command description wrapping", Spec: &struct { Command struct{} `command:"command" description:"A command with a reeeeeeeeeeeeeeeeeeeeeeeeeeeeeaaaaaaaaaallllllyyyyy loooooooooooooooonnnnnnngggggg description"` }{}, Rendered: `Usage: test [OPTION]... [ARG]... Available Commands: command A command with a reeeeeeeeeeeeeeeeeeeeeeeeeeeeeaaaaa aaaaallllllyyyyy loooooooooooooooonnnnnnngggggg desc ription `, }, { Description: "Command description wrapping with explicit newline in description", Spec: &struct { Command struct{} `command:"command" description:"A command with a\nnew line in the description"` }{}, Rendered: `Usage: test [OPTION]... [ARG]... Available Commands: command A command with a new line in the description `, }, { Description: "Option description wrapping", Spec: &struct { Option int `option:"opt" description:"An option with a reeeeeeeeeeeeeeeeeeeeeeeeeeeeeaaaaaaaaaallllllyyyyy loooooooooooooooonnnnnnngggggg description"` }{}, Rendered: `Usage: test [OPTION]... [ARG]... Available Options: --opt=ARG An option with a reeeeeeeeeeeeeeeeeeeeeeeeeeeeeaaaaa aaaaallllllyyyyy loooooooooooooooonnnnnnngggggg desc ription `, }, { Description: "Option description wrapping with explicit newline in description", Spec: &struct { Option int `option:"opt" description:"An option with a\nnew line in the description"` }{}, Rendered: `Usage: test [OPTION]... [ARG]... Available Options: --opt=ARG An option with a new line in the description `, }, { Description: "Hidden option", Spec: &struct { Hidden int `option:"hidden"` Flag bool `flag:"h, help" description:"Display this text and exit"` }{}, Rendered: `Usage: test [OPTION]... [ARG]... Available Options: -h, --help Display this text and exit `, }, { Description: "Hidden command", Spec: &struct { Command struct{} `command:"command" description:"A command"` Hidden struct{} `command:"hidden"` }{}, Rendered: `Usage: test [OPTION]... [ARG]... Available Commands: command A command `, }, } func TestHelpFormatting(t *testing.T) { for _, test := range helpFormattingTests { cmd := New("test", test.Spec) buf := bytes.NewBuffer(nil) err := cmd.WriteHelp(buf) if err != nil { t.Errorf("Encountered unexpecting error running test. Description: %s, Error: %s", test.Description, err) continue } if buf.String() != test.Rendered { t.Errorf("\nHelp output invalid. Test Description: %s\n===Expected===\n%s\n\n===Received:===\n%s", test.Description, test.Rendered, buf.String()) continue } } } func TestCustomHelpTemplate(t *testing.T) { templateText := "Custom content!" tpl := template.Must(template.New("Help").Parse(templateText)) cmd := New("test", &struct{}{}) cmd.Help.Template = tpl buf := bytes.NewBuffer(nil) err := cmd.WriteHelp(buf) if err != nil { t.Errorf("Encountered unexpecting error running custom template test. Error: %s", err) return } if buf.String() != templateText { t.Errorf("Custom help output invalid. Expected: %q, Received: %q", templateText, buf.String()) return } } func TestInvalidHelpTemplate(t *testing.T) { templateText := "{{.Bogus}}" tpl := template.Must(template.New("Help").Parse(templateText)) cmd := New("test", &struct{}{}) cmd.Help.Template = tpl defer func() { r := recover() if r != nil { switch r.(type) { case commandError, optionError: // Intentionally blank default: panic(r) } } }() cmd.WriteHelp(ioutil.Discard) t.Errorf("Expected cmd.WriteHelp() to panic on invalid template, but this didn't happen") } <|start_filename|>example_explicit_test.go<|end_filename|> // Copyright 2016 <NAME>. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. package writ_test import ( "github.com/bobziuchkovski/writ" "os" "runtime" ) type Config struct { help bool verbosity int bootloader string } // This example demonstrates explicit Command and Option creation, // along with explicit option grouping. It checks the host platform // and dynamically adds a --bootloader option if the example is run on // Linux. The same result could be achieved by using writ.New() to // construct a Command, and then adding the platform-specific option // to the resulting Command directly. func Example_explicit() { config := &Config{} cmd := &writ.Command{Name: "explicit"} cmd.Help.Usage = "Usage: explicit [OPTION]... [ARG]..." cmd.Options = []*writ.Option{ { Names: []string{"h", "help"}, Description: "Display this help text and exit", Decoder: writ.NewFlagDecoder(&config.help), Flag: true, }, { Names: []string{"v"}, Description: "Increase verbosity; may be specified more than once", Decoder: writ.NewFlagAccumulator(&config.verbosity), Flag: true, Plural: true, }, } // Note the explicit option grouping. Using writ.New(), a single option group is // created for all options/flags that have descriptions. Without writ.New(), we // need to create the OptionGroup(s) ourselves. general := cmd.GroupOptions("help", "v") general.Header = "General Options:" cmd.Help.OptionGroups = append(cmd.Help.OptionGroups, general) // Dynamically add --bootloader on Linux if runtime.GOOS == "linux" { cmd.Options = append(cmd.Options, &writ.Option{ Names: []string{"bootloader"}, Description: "Use the specified bootloader (grub, grub2, or lilo)", Decoder: writ.NewOptionDecoder(&config.bootloader), Placeholder: "NAME", }) platform := cmd.GroupOptions("bootloader") platform.Header = "Platform Options:" cmd.Help.OptionGroups = append(cmd.Help.OptionGroups, platform) } // Decode the options _, _, err := cmd.Decode(os.Args[1:]) if err != nil || config.help { cmd.ExitHelp(err) } // Help Output, Linux: // General Options: // -h, --help Display this help text and exit // -v Increase verbosity; may be specified more than once // // Platform Options: // --bootloader=NAME Use the specified bootloader (grub, grub2, or lilo) // // Help Output, other platforms: // General Options: // -h, --help Display this help text and exit // -v Increase verbosity; may be specified more than once }
bobziuchkovski/wr
<|start_filename|>client/src/nl/tue/id/oocsi/OOCSIString.java<|end_filename|> package nl.tue.id.oocsi; import nl.tue.id.oocsi.client.OOCSIClient; import nl.tue.id.oocsi.client.data.OOCSIVariable; /** * OOCSIString is a system-level primitive that allows for automatic synchronizing of local variables (read and write) * with different OOCSI clients on the same channel. This realizes synchronization on a single data variable without * aggregation. * * @author matsfunk * */ public class OOCSIString extends OOCSIVariable<String> { public OOCSIString(OOCSIClient client, String channelName, String key) { super(client, channelName, key); } public OOCSIString(OOCSIClient client, String channelName, String key, String referenceValue) { super(client, channelName, key, referenceValue); } public OOCSIString(OOCSIClient client, String channelName, String key, String referenceValue, int timeout) { super(client, channelName, key, referenceValue, timeout); } @Override protected String extractValue(OOCSIEvent event, String key) { return event.getString(key); } /** * set the limiting of incoming events in terms of "rate" and "seconds" timeframe; supports chained invocation * * @param rate * @param seconds * @return */ public OOCSIString limit(int rate, int seconds) { super.limit(rate, seconds); return this; } } <|start_filename|>client/src/nl/tue/id/oocsi/OOCSIInt.java<|end_filename|> package nl.tue.id.oocsi; import nl.tue.id.oocsi.client.OOCSIClient; import nl.tue.id.oocsi.client.data.OOCSIVariable; /** * OOCSIInt is a system-level primitive that allows for automatic synchronizing of local variables (read and write) with * different OOCSI clients on the same channel. This realizes synchronization on a single data variable without * aggregation. * * @author matsfunk * */ public class OOCSIInt extends OOCSIVariable<Integer> { public OOCSIInt(OOCSIClient client, String channelName, String key) { super(client, channelName, key); } public OOCSIInt(OOCSIClient client, String channelName, String key, int referenceValue) { super(client, channelName, key, referenceValue); } public OOCSIInt(OOCSIClient client, String channelName, String key, int referenceValue, int timeout) { super(client, channelName, key, referenceValue, timeout); } /** * @param referenceValue * @param timeout */ public OOCSIInt(int referenceValue, int timeout) { super(referenceValue, timeout); } /* * (non-Javadoc) * * @see nl.tue.id.oocsi.client.data.OOCSIVariable#get() */ @Override public Integer get() { if (super.get() == null) { return 0; } return super.get(); } @Override protected Integer extractValue(OOCSIEvent event, String key) { int intValue = event.getInt(key, Integer.MIN_VALUE); return intValue != Integer.MIN_VALUE ? intValue : null; } /* * (non-Javadoc) * * @see nl.tue.id.oocsi.client.data.OOCSIVariable#filter(java.lang.Object) */ @Override protected Integer filter(Integer var) { // check boundaries if (min != null && var < min) { var = min; } else if (max != null && var > max) { var = max; } // check mean and sigma if (sigma != null && mean != null) { // return null if value outside sigma deviation from mean if ((float) Math.abs(mean - var) > sigma) { var = (int) (mean - var > 0 ? mean - sigma / (float) values.size() : mean + sigma / (float) values.size()); } } // return filtered value return super.filter(var); } /* * (non-Javadoc) * * @see nl.tue.id.oocsi.client.data.OOCSIVariable#adapt(java.lang.Object) */ @Override protected Integer adapt(Integer var) { // history processing? if (windowLength > 0 && values != null && values.size() > 0) { // compute and store mean int sum = 0; for (Integer v : values) { sum += v; } mean = (int) (sum / (float) values.size()); return mean; } else { return var; } } /** * set the reference value (also possible during operation); supports chained invocation * * @param reference * @return */ @Override public OOCSIInt reference(Integer reference) { return (OOCSIInt) super.reference(reference); } /** * set the timeout in milliseconds (also possible during operation); supports chained invocation * * @param timeoutMS * @return */ @Override public OOCSIInt timeout(int timeoutMS) { return (OOCSIInt) super.timeout(timeoutMS); } /** * set the limiting of incoming events in terms of "rate" and "seconds" timeframe; supports chained invocation * * @param rate * @param seconds * @return */ public OOCSIInt limit(int rate, int seconds) { super.limit(rate, seconds); return this; } /** * set the minimum value for (lower-)bounded variable (also possible during operation); supports chained invocation * * @param min * @return */ @Override public OOCSIInt min(Integer min) { return (OOCSIInt) super.min(min); } /** * set the maximum value for (upper-)bounded variable (also possible during operation); supports chained invocation * * @param max * @return */ @Override public OOCSIInt max(Integer max) { return (OOCSIInt) super.max(max); } /** * set the length of the smoothing window, i.e., the buffer of historical values of this variable (also possible * during operation, however, this will reset the buffer); supports chained invocation * * @param windowLength * @return */ @Override public OOCSIInt smooth(int windowLength) { return (OOCSIInt) super.smooth(windowLength); } /** * set the length of the smoothing window, i.e., the buffer of historical values of this variable (also possible * during operation, however, this will reset the buffer); supports chained invocation. the parameter sigma sets the * upper bound for the standard deviation protected variable * * @param windowLength * @param sigma * @return */ @Override public OOCSIInt smooth(int windowLength, Integer sigma) { return (OOCSIInt) super.smooth(windowLength, sigma); } /** * creates a periodic feedback loop that feed either the last input value or the reference value into the variable * (locally). If there is no reference value set, the former applies. The period is given in milliseconds. * * @param periodMS * @return */ @Override public OOCSIInt generator(long periodMS) { return (OOCSIInt) super.generator(periodMS); } /** * creates a periodic feedback loop that feed either the last input value or the reference value into the variable * (locally). If there is no reference value set, the former applies. The period is given in milliseconds. In * addition, the new value of the variable is sent out to the channel "outputChannel" with the given key "outputKey" * * @param periodMS * @param outputChannel * @param outputKey * @return */ @Override public OOCSIInt generator(long periodMS, String outputChannel, String outputKey) { return (OOCSIInt) super.generator(periodMS, outputChannel, outputKey); } /* * (non-Javadoc) * * @see nl.tue.id.oocsi.client.data.OOCSIVariable#connect(nl.tue.id.oocsi.client.data.OOCSIVariable) */ @Override public void connect(OOCSIVariable<Integer> forward) { super.connect(forward); } /* * (non-Javadoc) * * @see nl.tue.id.oocsi.client.data.OOCSIVariable#disconnect(nl.tue.id.oocsi.client.data.OOCSIVariable) */ @Override public void disconnect(OOCSIVariable<Integer> forward) { super.disconnect(forward); } } <|start_filename|>client/test/ClientPasswordTest.java<|end_filename|> import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.junit.Test; import nl.tue.id.oocsi.client.OOCSIClient; import nl.tue.id.oocsi.client.protocol.DataHandler; public class ClientPasswordTest { @Test public void testConnectAndKillWithPassword() throws InterruptedException { OOCSIClient o1 = new OOCSIClient("test_priv_client_1:12345"); o1.connect("localhost", 4444); Thread.sleep(200); assertTrue(o1.isConnected()); OOCSIClient o2 = new OOCSIClient("test_priv_client_1"); o2.connect("localhost", 4444); Thread.sleep(200); assertTrue(!o2.isConnected()); OOCSIClient o3 = new OOCSIClient("test_priv_client_1:345"); o3.connect("localhost", 4444); Thread.sleep(200); assertTrue(!o3.isConnected()); OOCSIClient o4 = new OOCSIClient("test_priv_client_1:12345"); o4.connect("localhost", 4444); Thread.sleep(200); assertTrue(!o4.isConnected()); o1.disconnect(); o2.disconnect(); o3.disconnect(); o4.disconnect(); OOCSIClient o5 = new OOCSIClient("test_priv_client_1:12345"); o5.connect("localhost", 4444); Thread.sleep(200); assertTrue(o5.isConnected()); o5.disconnect(); } @Test public void testPasswordProtectedClient() throws InterruptedException { final List<String> list = new ArrayList<String>(); OOCSIClient o1 = new OOCSIClient("test_priv_client_1:12345"); o1.connect("localhost", 4444); assertTrue(o1.isConnected()); o1.subscribe(new DataHandler() { public void receive(String sender, Map<String, Object> data, long timestamp) { list.add(sender); } }); OOCSIClient o2 = new OOCSIClient("test_priv_client_2"); o2.connect("localhost", 4444); assertTrue(o2.isConnected()); o2.subscribe(new DataHandler() { public void receive(String sender, Map<String, Object> data, long timestamp) { list.add(sender); } }); assertEquals(0, list.size()); o2.send("test_priv_client_1", "hello1"); Thread.yield(); Thread.sleep(1000); assertEquals(1, list.size()); assertEquals("test_priv_client_2", list.get(0)); o1.disconnect(); o2.disconnect(); } } <|start_filename|>client/src/nl/tue/id/oocsi/client/protocol/Handler.java<|end_filename|> package nl.tue.id.oocsi.client.protocol; import java.io.IOException; import java.util.Map; import nl.tue.id.oocsi.client.data.JSONReader; /** * event handler for events with structured data * * @author matsfunk */ abstract public class Handler { /** * raw data wrapper; will parse the incoming data and forward the event to the actual handler * * @param sender * @param data * @param timestamp * @param channel * @param recipient */ public void send(String sender, String data, String timestamp, String channel, String recipient) { try { final Map<String, Object> map = parseData(data); final long ts = parseTimestamp(timestamp); // forward event receive(sender, map, ts, channel, recipient); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } /** * abstract method to be implemented in anonymous classes that are instantiated by subscribing and registering for * events * * @param sender * @param data * @param timestamp * @param channel * @param recipient */ abstract public void receive(String sender, Map<String, Object> data, long timestamp, String channel, String recipient); /** * parse the given "data" String into a Map * * @param data * @return * @throws IOException * @throws ClassNotFoundException */ @SuppressWarnings("unchecked") public static Map<String, Object> parseData(String data) throws IOException, ClassNotFoundException { return (Map<String, Object>) new JSONReader().read(data); } /** * parse the given "timestamp" String into a long value * * @param timestamp * @return */ public static long parseTimestamp(String timestamp) { long ts = System.currentTimeMillis(); try { ts = Long.parseLong(timestamp); } catch (Exception e) { // do nothing } return ts; } } <|start_filename|>client/src/nl/tue/id/oocsi/client/protocol/EventHandler.java<|end_filename|> package nl.tue.id.oocsi.client.protocol; import java.util.Map; import nl.tue.id.oocsi.OOCSIEvent; /** * event handler for events with structured data * * @author matsfunk */ abstract public class EventHandler extends Handler { /* * (non-Javadoc) * * @see nl.tue.id.oocsi.client.protocol.Handler#receive(java.lang.String, java.util.Map, long, java.lang.String, * java.lang.String) */ @Override public void receive(String sender, Map<String, Object> data, long timestamp, String channel, final String recipient) { receive(new OOCSIEvent(channel, data, sender, timestamp) { @Override public String getRecipient() { return recipient; } }); } /** * abstract method to be implemented in anonymous classes that are instantiated by subscribing and registering for * events; encapsulates all incoming data as OOCSIEvent object * * @param event */ abstract public void receive(OOCSIEvent event); } <|start_filename|>client/test/ClientSpatialTest.java<|end_filename|> import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.junit.Test; import nl.tue.id.oocsi.client.OOCSIClient; import nl.tue.id.oocsi.client.behavior.OOCSISpatial; import nl.tue.id.oocsi.client.protocol.Handler; import nl.tue.id.oocsi.client.services.OOCSICall; public class ClientSpatialTest { private static final String DESTINATION = "oocsi_spatial_destination_request"; private static final String DESTINATION_RESPONSE = "oocsi_spatial_destination_distance"; private static final String ROUTING_PATH = "oocsi_spatial_routing_path"; @Test public void testSpatialIntegerNeighbors() throws InterruptedException { OOCSIClient client1 = new OOCSIClient(); client1.connect("localhost", 4444); OOCSISpatial os1 = OOCSISpatial.createSpatial(client1, "spatialChannel", "integer_distance", 4, 2); Map<String, OOCSIClient> clients = getClients( new String[] { "os_spatial_2", "os_spatial_3", "os_spatial_4", "os_spatial_5", "os_spatial_6" }); { OOCSIClient client2 = clients.get("os_spatial_2"); client2.connect("localhost", 4444); OOCSISpatial.createSpatial(client2, "spatialChannel", "integer_distance", 3, 2); } { OOCSIClient client2 = clients.get("os_spatial_3"); client2.connect("localhost", 4444); OOCSISpatial.createSpatial(client2, "spatialChannel", "integer_distance", 1, 2); } { OOCSIClient client2 = clients.get("os_spatial_4"); client2.connect("localhost", 4444); OOCSISpatial.createSpatial(client2, "spatialChannel", "integer_distance", 5, 2); } { OOCSIClient client2 = clients.get("os_spatial_5"); client2.connect("localhost", 4444); OOCSISpatial.createSpatial(client2, "spatialChannel", "integer_distance", 6, 2); } { OOCSIClient client2 = clients.get("os_spatial_6"); client2.connect("localhost", 4444); OOCSISpatial.createSpatial(client2, "spatialChannel", "integer_distance", 7, 2); } // initialization should be reference value List<String> neighbors = os1.getNeighbors(); assertTrue(neighbors.contains("os_spatial_2")); assertTrue(!neighbors.contains("os_spatial_3")); assertTrue(neighbors.contains("os_spatial_4")); assertTrue(neighbors.contains("os_spatial_5")); assertTrue(!neighbors.contains("os_spatial_6")); // clean up client1.disconnect(); for (OOCSIClient c : clients.values()) { c.disconnect(); } } @Test public void testSpatialIntegerNeighborsMessages() throws InterruptedException { final List<String> eventSink = new LinkedList<String>(); OOCSIClient client1 = new OOCSIClient(); client1.connect("localhost", 4444); OOCSISpatial os1 = OOCSISpatial.createSpatial(client1, "spatialChannel", "integer_distance", 4, 2); Map<String, OOCSIClient> clients = getClients( new String[] { "os_spatial_2", "os_spatial_3", "os_spatial_4", "os_spatial_5", "os_spatial_6" }); { OOCSIClient client2 = clients.get("os_spatial_2"); client2.connect("localhost", 4444); OOCSISpatial.createSpatial(client2, "spatialChannel", "integer_distance", 3, 2); client2.subscribe(new Handler() { public void receive(String sender, Map<String, Object> data, long timestamp, String channel, String recipient) { eventSink.add("ok 2"); } }); } { OOCSIClient client2 = clients.get("os_spatial_3"); client2.connect("localhost", 4444); OOCSISpatial.createSpatial(client2, "spatialChannel", "integer_distance", 1, 2); client2.subscribe(new Handler() { public void receive(String sender, Map<String, Object> data, long timestamp, String channel, String recipient) { eventSink.add("not ok 3"); } }); } { OOCSIClient client2 = clients.get("os_spatial_4"); client2.connect("localhost", 4444); OOCSISpatial.createSpatial(client2, "spatialChannel", "integer_distance", 5, 2); client2.subscribe(new Handler() { public void receive(String sender, Map<String, Object> data, long timestamp, String channel, String recipient) { eventSink.add("ok 4"); } }); } { OOCSIClient client2 = clients.get("os_spatial_5"); client2.connect("localhost", 4444); OOCSISpatial.createSpatial(client2, "spatialChannel", "integer_distance", 6, 2); client2.subscribe(new Handler() { public void receive(String sender, Map<String, Object> data, long timestamp, String channel, String recipient) { eventSink.add("ok 5"); } }); } { OOCSIClient client2 = clients.get("os_spatial_6"); client2.connect("localhost", 4444); OOCSISpatial.createSpatial(client2, "spatialChannel", "integer_distance", 7, 2); client2.subscribe(new Handler() { public void receive(String sender, Map<String, Object> data, long timestamp, String channel, String recipient) { eventSink.add("not ok 6"); } }); } // send a message to all neighbors os1.neighbors().data("hello", "world").send(); // wait longer than timeout Thread.sleep(200); assertTrue(eventSink.contains("ok 2")); assertTrue(!eventSink.contains("not ok 3")); assertTrue(eventSink.contains("ok 4")); assertTrue(eventSink.contains("ok 5")); assertTrue(!eventSink.contains("not ok 6")); assertEquals(3, eventSink.size()); // clean up client1.disconnect(); for (OOCSIClient c : clients.values()) { c.disconnect(); } } @Test public void testSpatialIntegerClosestNeighbor() throws InterruptedException { final List<String> eventSink = new LinkedList<String>(); OOCSIClient client1 = new OOCSIClient(); client1.connect("localhost", 4444); OOCSISpatial os1 = OOCSISpatial.createSpatial(client1, "spatialChannel", "integer_distance", 4, 2); Map<String, OOCSIClient> clients = getClients( new String[] { "os_rt_2", "os_rt_3", "os_rt_4", "os_rt_5", "os_rt_6" }); { OOCSIClient client2 = clients.get("os_rt_2"); client2.connect("localhost", 4444); OOCSISpatial.createSpatial(client2, "spatialChannel", "integer_distance", 3, 2); client2.subscribe(new Handler() { public void receive(String sender, Map<String, Object> data, long timestamp, String channel, String recipient) { eventSink.add("ok 2"); } }); } { OOCSIClient client2 = clients.get("os_rt_3"); client2.connect("localhost", 4444); OOCSISpatial.createSpatial(client2, "spatialChannel", "integer_distance", 1, 2); client2.subscribe(new Handler() { public void receive(String sender, Map<String, Object> data, long timestamp, String channel, String recipient) { eventSink.add("not ok 3"); } }); } { OOCSIClient client2 = clients.get("os_rt_4"); client2.connect("localhost", 4444); OOCSISpatial.createSpatial(client2, "spatialChannel", "integer_distance", 5, 2); client2.subscribe(new Handler() { public void receive(String sender, Map<String, Object> data, long timestamp, String channel, String recipient) { eventSink.add("ok 4"); } }); } { OOCSIClient client2 = clients.get("os_rt_5"); client2.connect("localhost", 4444); OOCSISpatial.createSpatial(client2, "spatialChannel", "integer_distance", 6, 2); client2.subscribe(new Handler() { public void receive(String sender, Map<String, Object> data, long timestamp, String channel, String recipient) { eventSink.add("ok 5"); } }); } { OOCSIClient client2 = clients.get("os_rt_6"); client2.connect("localhost", 4444); OOCSISpatial.createSpatial(client2, "spatialChannel", "integer_distance", 7, 2); client2.subscribe(new Handler() { public void receive(String sender, Map<String, Object> data, long timestamp, String channel, String recipient) { eventSink.add("not ok 6"); } }); } // send a message to all neighbors assertEquals("os_rt_2", os1.getClosestNeighbor()); // clean up client1.disconnect(); for (OOCSIClient c : clients.values()) { c.disconnect(); } } @Test public void testSpatial1DRouting() throws InterruptedException { OOCSIClient client1 = new OOCSIClient(); client1.connect("localhost", 4444); OOCSISpatial os1 = OOCSISpatial.createSpatial(client1, "spatialChannel2", "integer_distance", 4, 2); Map<String, OOCSIClient> clients = getClients( new String[] { "os1_rt_2", "os1_rt_3", "os1_rt_4", "os1_rt_5", "os1_rt_6", "os1_rt_7", "os1_rt_8" }); { OOCSIClient client2 = clients.get("os1_rt_2"); client2.connect("localhost", 4444); OOCSISpatial.createSpatial(client2, "spatialChannel2", "integer_distance", 2, 2); } { OOCSIClient client2 = clients.get("os1_rt_3"); client2.connect("localhost", 4444); OOCSISpatial.createSpatial(client2, "spatialChannel2", "integer_distance", 0, 2); } { OOCSIClient client2 = clients.get("os1_rt_4"); client2.connect("localhost", 4444); OOCSISpatial.createSpatial(client2, "spatialChannel2", "integer_distance", 5, 2); } { OOCSIClient client2 = clients.get("os1_rt_5"); client2.connect("localhost", 4444); OOCSISpatial.createSpatial(client2, "spatialChannel2", "integer_distance", 7, 2); } { OOCSIClient client2 = clients.get("os1_rt_6"); client2.connect("localhost", 4444); OOCSISpatial.createSpatial(client2, "spatialChannel2", "integer_distance", 7, 2); } { OOCSIClient client2 = clients.get("os1_rt_7"); client2.connect("localhost", 4444); OOCSISpatial.createSpatial(client2, "spatialChannel2", "integer_distance", 8, 2); } { OOCSIClient client2 = clients.get("os1_rt_8"); client2.connect("localhost", 4444); OOCSISpatial.createSpatial(client2, "spatialChannel2", "integer_distance", 9, 2); } // starting routing... { // do a call test with chance of success (right direction; not neighbor) OOCSICall oc = new OOCSICall(client1, "os1_rt_5", DESTINATION, 2000, 10).data(DESTINATION, "os1_rt_6"); oc.sendAndWait(); assertTrue(oc.hasResponse()); assertEquals(0, oc.getFirstResponse().getFloat(DESTINATION_RESPONSE, -1), 0); } { // do a call test with chance of success (right direction; direct neighbor) OOCSICall oc = new OOCSICall(client1, "os1_rt_4", DESTINATION, 2000, 10).data(DESTINATION, "os1_rt_6"); oc.sendAndWait(); assertTrue(oc.hasResponse()); assertEquals(2, oc.getFirstResponse().getFloat(DESTINATION_RESPONSE, -1), 0); } { // do a call test with success chance (asking a direct neighbor; right direction) OOCSICall oc = new OOCSICall(client1, "os1_rt_4", DESTINATION, 2000, 10).data(DESTINATION, "os1_rt_5"); oc.sendAndWait(); assertTrue(oc.hasResponse()); assertEquals(2, oc.getFirstResponse().getFloat(DESTINATION_RESPONSE, -1), 0); } { // do a call test without chance of success (asking a direct neighbor; wrong direction) OOCSICall oc = new OOCSICall(client1, "os1_rt_2", DESTINATION, 2000, 10).data(DESTINATION, "os1_rt_6"); oc.sendAndWait(); assertTrue(oc.hasResponse()); assertEquals(5, oc.getFirstResponse().getFloat(DESTINATION_RESPONSE, -1), 0); } { // do a call test without chance of success (asking a direct neighbor; wrong direction) OOCSICall oc = new OOCSICall(client1, "os1_rt_2", DESTINATION, 2000, 10).data(DESTINATION, "os1_rt_6") .data(ROUTING_PATH, client1.getName() + ","); oc.sendAndWait(); assertTrue(oc.hasResponse()); assertEquals(Float.MAX_VALUE, oc.getFirstResponse().getFloat(DESTINATION_RESPONSE, -1), 0); } // send a message to all neighbors (one hop) assertEquals("os1_rt_2", os1.routing("os1_rt_2")); // send a message to all neighbors (two hops) assertEquals("os1_rt_2", os1.routing("os1_rt_3")); // send a message to all neighbors (two hops) assertEquals("os1_rt_2", os1.routing("os1_rt_3")); // send a message to all neighbors (two hops) assertEquals("os1_rt_4", os1.routing("os1_rt_8")); // clean up client1.disconnect(); for (OOCSIClient c : clients.values()) { c.disconnect(); } } @Test public void testSpatial1DRoutingWithBreak() throws InterruptedException { OOCSIClient client1 = new OOCSIClient(); client1.connect("localhost", 4444); OOCSISpatial os1 = OOCSISpatial.createSpatial(client1, "spatialChannel", "integer_distance", 4, 2); Map<String, OOCSIClient> clients = getClients( new String[] { "os2_rt_2", "os2_rt_3", "os2_rt_4", "os2_rt_5", "os2_rt_6", "os2_rt_7", "os2_rt_8" }); // { // OOCSIClient client2 = clients.get("os2_rt_2"); // client2.connect("localhost", 4444); // OOCSISpatial.createSpatial(client2, "spatialChannel", "integer_distance", 2, 2); // } // // { // OOCSIClient client2 = clients.get("os2_rt_3"); // client2.connect("localhost", 4444); // OOCSISpatial.createSpatial(client2, "spatialChannel", "integer_distance", 0, 2); // } { OOCSIClient client2 = clients.get("os2_rt_4"); client2.connect("localhost", 4444); OOCSISpatial.createSpatial(client2, "spatialChannel", "integer_distance", 5, 2); } { OOCSIClient client2 = clients.get("os2_rt_5"); client2.connect("localhost", 4444); OOCSISpatial.createSpatial(client2, "spatialChannel", "integer_distance", 6, 2); } { OOCSIClient client2 = clients.get("os2_rt_6"); client2.connect("localhost", 4444); OOCSISpatial.createSpatial(client2, "spatialChannel", "integer_distance", 7, 2); } { OOCSIClient client2 = clients.get("os2_rt_7"); client2.connect("localhost", 4444); OOCSISpatial.createSpatial(client2, "spatialChannel", "integer_distance", 8, 2); } { OOCSIClient client2 = clients.get("os2_rt_8"); client2.connect("localhost", 4444); OOCSISpatial.createSpatial(client2, "spatialChannel", "integer_distance", 9, 2); } // send a message to all neighbors (two hops) assertEquals("os2_rt_4", os1.routing("os2_rt_8")); clients.get("os2_rt_4").disconnect(); // send a message to all neighbors (two hops) assertEquals("os2_rt_5", os1.routing("os2_rt_8")); // clean up client1.disconnect(); for (OOCSIClient c : clients.values()) { c.disconnect(); } } @Test public void testSpatial1DRouting2() throws InterruptedException { OOCSIClient client1 = new OOCSIClient(); client1.connect("localhost", 4444); OOCSISpatial os1 = OOCSISpatial.createSpatial(client1, "spatialChannel2", "integer_distance2", 2, 2); Map<String, OOCSIClient> clients = getClients(new String[] { "os_rt_2", "os_rt_3", "os_rt_4", "os_rt_5" }); { OOCSIClient client2 = clients.get("os_rt_2"); client2.connect("localhost", 4444); OOCSISpatial.createSpatial(client2, "spatialChannel2", "integer_distance2", 3, 2); } { OOCSIClient client2 = clients.get("os_rt_3"); client2.connect("localhost", 4444); OOCSISpatial.createSpatial(client2, "spatialChannel2", "integer_distance2", 5, 2); } { OOCSIClient client2 = clients.get("os_rt_4"); client2.connect("localhost", 4444); OOCSISpatial.createSpatial(client2, "spatialChannel2", "integer_distance2", 7, 2); } { OOCSIClient client2 = clients.get("os_rt_5"); client2.connect("localhost", 4444); OOCSISpatial.createSpatial(client2, "spatialChannel2", "integer_distance2", 8, 2); } // start routing... { // one hop OOCSICall oc = new OOCSICall(client1, "os_rt_2", DESTINATION, 2000, 10).data(DESTINATION, "os_rt_3") .data(ROUTING_PATH, client1.getName() + ","); oc.sendAndWait(); // no response, because of timeout assertTrue(oc.hasResponse()); assertEquals(2, oc.getFirstResponse().getFloat(DESTINATION_RESPONSE, -1), 0); assertEquals("os_rt_2", oc.getFirstResponse().getSender()); } { // one hop OOCSICall oc = new OOCSICall(client1, "os_rt_3", DESTINATION, 2000, 10).data(DESTINATION, "os_rt_4"); oc.sendAndWait(); assertTrue(oc.hasResponse()); assertEquals(2, oc.getFirstResponse().getFloat(DESTINATION_RESPONSE, -1), 0); assertEquals("os_rt_3", oc.getFirstResponse().getSender()); } { // two hops OOCSICall oc = new OOCSICall(client1, "os_rt_2", DESTINATION, 2000, 10).data(DESTINATION, "os_rt_4"); oc.sendAndWait(); assertTrue(oc.hasResponse()); assertEquals(4, oc.getFirstResponse().getFloat(DESTINATION_RESPONSE, -1), 0); assertEquals("os_rt_2", oc.getFirstResponse().getSender()); } // send a message to all neighbors (one hop) assertEquals("os_rt_2", os1.routing("os_rt_2")); // send a message to all neighbors (two hops) assertEquals("os_rt_2", os1.routing("os_rt_3")); // repeat assertEquals("os_rt_2", os1.routing("os_rt_3")); // send a message to all neighbors (two hops) assertEquals("os_rt_2", os1.routing("os_rt_5")); // clean up client1.disconnect(); for (OOCSIClient c : clients.values()) { c.disconnect(); } } @Test public void testSpatial2DRouting() throws InterruptedException { OOCSIClient client1 = new OOCSIClient(); client1.connect("localhost", 4444); OOCSISpatial os1 = OOCSISpatial.createSpatial(client1, "spatialChannel3", "integer_distance2", 0, 0, 1.4f); Map<String, OOCSIClient> clients = getClients(new String[] { "os3_rt_2", "os3_rt_3", "os3_rt_4" }); { OOCSIClient client2 = clients.get("os3_rt_2"); client2.connect("localhost", 4444); OOCSISpatial.createSpatial(client2, "spatialChannel3", "integer_distance2", 0, 0.9f, 1.4f); } { OOCSIClient client2 = clients.get("os3_rt_3"); client2.connect("localhost", 4444); OOCSISpatial.createSpatial(client2, "spatialChannel3", "integer_distance2", 1, 0, 1.4f); } { OOCSIClient client2 = clients.get("os3_rt_4"); client2.connect("localhost", 4444); OOCSISpatial.createSpatial(client2, "spatialChannel3", "integer_distance2", 1.5f, 1, 1.4f); } // start routing... // send a message to all neighbors (one hop) assertEquals("os3_rt_2", os1.routing("os3_rt_2")); // send a message to all neighbors (two hops) assertEquals("os3_rt_3", os1.routing("os3_rt_3")); // routing from _2: 0.9 + 1.86 // routing from _3: 1.0 + 1.11 assertEquals("os3_rt_3", os1.routing("os3_rt_4")); // clean up client1.disconnect(); for (OOCSIClient c : clients.values()) { c.disconnect(); } } @Test public void testSpatial2DRoutingWithBreak() throws InterruptedException { OOCSIClient client1 = new OOCSIClient(); client1.connect("localhost", 4444); OOCSISpatial os1 = OOCSISpatial.createSpatial(client1, "spatialChannel2", "double_distance2", 0f, 0f, 1.4f); Map<String, OOCSIClient> clients = getClients( new String[] { "os_rt_2", "os_rt_3", "os_rt_4", "os_rt_5", "os_rt_6" }); OOCSIClient client2 = clients.get("os_rt_2"); client2.connect("localhost", 4444); OOCSISpatial.createSpatial(client2, "spatialChannel2", "double_distance2", 0f, 1f, 1.4f); OOCSIClient client3 = clients.get("os_rt_3"); client3.connect("localhost", 4444); OOCSISpatial.createSpatial(client3, "spatialChannel2", "double_distance2", 0f, 2f, 1.4f); OOCSIClient client4 = clients.get("os_rt_4"); client4.connect("localhost", 4444); OOCSISpatial.createSpatial(client4, "spatialChannel2", "double_distance2", 1f, 0f, 1.4f); OOCSIClient client5 = clients.get("os_rt_5"); client5.connect("localhost", 4444); OOCSISpatial.createSpatial(client5, "spatialChannel2", "double_distance2", 1f, 1f, 1.4f); OOCSIClient client6 = clients.get("os_rt_6"); client6.connect("localhost", 4444); OOCSISpatial.createSpatial(client6, "spatialChannel2", "double_distance2", 1f, 2f, 1.4f); // start routing... assertEquals("os_rt_2", os1.routing("os_rt_3")); // disconnect _2 clients.get("os_rt_2").disconnect(); assertEquals("os_rt_4", os1.routing("os_rt_3")); // clean up client1.disconnect(); for (OOCSIClient c : clients.values()) { c.disconnect(); } } public Map<String, OOCSIClient> getClients(String[] clientNames) { Map<String, OOCSIClient> clients = new HashMap<String, OOCSIClient>(); for (String client : clientNames) { clients.put(client, new OOCSIClient(client)); } return clients; } } <|start_filename|>client/src/nl/tue/id/oocsi/OOCSICommunicator.java<|end_filename|> package nl.tue.id.oocsi; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import nl.tue.id.oocsi.client.OOCSIClient; import nl.tue.id.oocsi.client.protocol.EventHandler; import nl.tue.id.oocsi.client.protocol.Handler; import nl.tue.id.oocsi.client.protocol.OOCSIMessage; import nl.tue.id.oocsi.client.protocol.RateLimitedClientEventHandler; import nl.tue.id.oocsi.client.protocol.RateLimitedEventHandler; import nl.tue.id.oocsi.client.services.OOCSICall; import nl.tue.id.oocsi.client.services.Responder; /** * communication interface for OOCSI client * * @author matsfunk */ public class OOCSICommunicator extends OOCSIClient { private Object parent; /** * constructor * * @param parent * @param name */ public OOCSICommunicator(Object parent, String name) { super(name); this.parent = parent; } /* * (non-Javadoc) * * @see nl.tue.id.oocsi.client.OOCSIClient#connect() */ @Override public boolean connect() { // connect delegate boolean result = super.connect(); // default subscribe if (!subscribe(name, name)) { if (subscribe(name, "handleOOCSIEvent")) { log(" - found 'handleOOCSIEvent', will send direct messages there"); } } return result; } /* * (non-Javadoc) * * @see nl.tue.id.oocsi.client.OOCSIClient#connect(java.lang.String, int) */ @Override public boolean connect(String hostname, int port) { // connect delegate boolean result = super.connect(hostname, port); // default subscribe if (!subscribe(name, name)) { if (!subscribe(name, "handleOOCSIEvent")) { log(" - no handlers found for receiving direct messages"); } } return result; } /** * send data through a channel given by the channelName * * @param channelName * @return */ public OOCSIMessage channel(String channelName) { return new OOCSIMessage(this, channelName); } /** * create a call for service method "callName" * * @param callName * @return */ public OOCSICall call(String callName) { return call(callName, 1000, 1); } /** * create a call for service method "callName" on channel "channelName" * * @param channelName * @param callName * @return */ public OOCSICall call(String channelName, String callName) { return call(channelName, callName, 1000, 1); } /** * create a call for service method "callName" with a specific timeout * * @param callName * @param timeoutMS * @return */ public OOCSICall call(String callName, int timeoutMS) { return call(callName, timeoutMS, 1); } /** * create a call for service method "callName" with a specific timeout on channel "channelName" * * @param channelName * @param callName * @param timeoutMS * @return */ public OOCSICall call(String channelName, String callName, int timeoutMS) { return call(channelName, callName, timeoutMS, 1); } /** * create a call for service method "callName" with a specific timeout * * @param callName * @param timeoutMS * @param maxResponses * @return */ public OOCSICall call(String callName, int timeoutMS, int maxResponses) { return new OOCSICall(this, callName, timeoutMS, maxResponses); } /** * create a call for service method "callName" with a specific timeout on channel "channelName" * * @param channelName * @param callName * @param timeoutMS * @param maxResponses * @return */ public OOCSICall call(String channelName, String callName, int timeoutMS, int maxResponses) { return new OOCSICall(this, channelName, callName, timeoutMS, maxResponses); } /** * subscribe to channel "channelName" for handler method "channelName" in the parent class; the handler method will * be called with an OOCSIEvent object upon occurrence of an event; will try 'handleOOCSIEvent' as a fall-back in * case no matching handler method is found for "channelName" * * @param channelName * @return */ public boolean subscribe(String channelName) { return subscribe(channelName, channelName) ? true : subscribe(channelName, "handleOOCSIEvent"); } /** * subscribe to channel "channelName" for handler method in the parent class with the given name "handlerName"; the * handler method will be called with an OOCSIEvent object upon occurrence of an event * * @param channelName * @param handlerName * @return */ public boolean subscribe(String channelName, String handlerName) { return this.subscribe(channelName, handlerName, 0, 0); } /** * subscribe to channel "channelName" for handler method in the parent class with the given name "handlerName"; the * handler method will be called with an OOCSIEvent object upon occurrence of an event * * @param channelName * @param handlerName * @param rate * @param seconds * @return */ public boolean subscribe(String channelName, String handlerName, int rate, int seconds) { return subscribe(channelName, handlerName, rate, seconds, false); } /** * subscribe to channel "channelName" for handler method in the parent class with the given name "handlerName"; the * handler method will be called with an OOCSIEvent object upon occurrence of an event * * @param channelName * @param handlerName * @param rate * @param seconds * @param ratePerSender * @return */ public boolean subscribe(final String channelName, String handlerName, int rate, int seconds, boolean ratePerSender) { // try event handler with OOCSIEvent parameter try { final Method handler = parent.getClass().getDeclaredMethod(handlerName, new Class[] { OOCSIEvent.class }); if (!Modifier.isPublic(handler.getModifiers())) { log(" - [ERROR] event handler for channel " + channelName + " needs to be a public method: 'public void " + channelName + "(OOCSIEvent evt) { ... }'"); return false; } if (rate > 0 && seconds > 0) { if (ratePerSender) { subscribe(channelName, new RateLimitedClientEventHandler(rate, seconds) { @Override public void receive(OOCSIEvent event) { try { handler.invoke(parent, new Object[] { event }); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } }); } else { subscribe(channelName, new RateLimitedEventHandler(rate, seconds) { @Override public void receive(OOCSIEvent event) { try { handler.invoke(parent, new Object[] { event }); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } }); } } else { subscribe(channelName, new RateLimitedEventHandler(rate, seconds) { @Override public void receive(OOCSIEvent event) { try { handler.invoke(parent, new Object[] { event }); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } }); } log(" - subscribed to " + channelName + " with event handler"); return true; } catch (Exception e) { // not found, just return false if (!name.equals(channelName)) { log(" - no event handler for channel " + channelName); } return false; } } /** * create a simple handler that calls the method with the given handlerName in the parent object (without * parameters) * * @param handlerName * @return */ public Handler createSimpleCallerHandler(String handlerName) { try { final Method handler = parent.getClass().getDeclaredMethod(handlerName, new Class[] {}); return new EventHandler() { @Override public void receive(OOCSIEvent event) { try { handler.invoke(parent, new Object[] {}); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } }; } catch (Exception e) { // not found, just return null return null; } } /** * subscribe to channel "responderName" for handler method "responderName" in the parent class; the handler method * will be called with an OOCSIEvent object and a response map object upon occurrence of an event; will try * 'respondToOOCSIEvent' as a fall-back in case no matching handler method is found for "responderName" * * @param responderName * @return */ public boolean register(String responderName) { return register(responderName, responderName) ? true : register(responderName, "respondToOOCSIEvent"); } /** * register a handler method in the parent class with the given name "handlerName" for the channel "channelName"; * the handler method will be called with an OOCSIEvent object upon occurrence of an event * * @param responderName * @param handlerName * @return */ public boolean register(String responderName, String handlerName) { // try responder event handler with OOCSIEvent and response map parameters try { final Method handler = parent.getClass().getDeclaredMethod(handlerName, new Class[] { OOCSIEvent.class, OOCSIData.class }); Responder responder = new Responder(this) { @Override public void respond(OOCSIEvent event, OOCSIData response) { try { handler.invoke(parent, new Object[] { event, response }); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } }; responder.setCallName(responderName); register(responderName, responder); log(" - registered " + responderName + " as call responder"); return true; } catch (Exception e) { // not found, just return false if (!name.equals(responderName)) { log(" - no call responders found for channel " + responderName); } return false; } } /** * subscribe to channel "responderName" for handler method "responderName" in the parent class; the handler method * will be called with an OOCSIEvent object and a response map object upon occurrence of an event; will try * 'respondToOOCSIEvent' as a fall-back in case no matching handler method is found for "responderName" * * @param channelName * @param responderName * @return */ public boolean registerChannel(String channelName, String responderName) { return registerChannel(channelName, responderName, responderName) ? true : registerChannel(channelName, responderName, "respondToOOCSIEvent"); } /** * register a handler method in the parent class with the given name "handlerName" for the channel "channelName"; * the handler method will be called with an OOCSIEvent object upon occurrence of an event * * @param channelName * @param responderName * @param handlerName * @return */ public boolean registerChannel(String channelName, String responderName, String handlerName) { // try responder event handler with OOCSIEvent and response map parameters try { final Method handler = parent.getClass().getDeclaredMethod(handlerName, new Class[] { OOCSIEvent.class, OOCSIData.class }); Responder responder = new Responder(this) { @Override public void respond(OOCSIEvent event, OOCSIData response) { try { handler.invoke(parent, new Object[] { event, response }); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } }; responder.setCallName(responderName); register(channelName, responderName, responder); log(" - registered " + responderName + " as call responder"); return true; } catch (Exception e) { // not found, just return false if (!name.equals(responderName)) { log(" - no call responders found for channel " + responderName); } return false; } } } <|start_filename|>client/src/nl/tue/id/oocsi/client/protocol/RateLimitedEventHandler.java<|end_filename|> package nl.tue.id.oocsi.client.protocol; import java.util.Map; /** * rate limited event handler for events with structured data that will only let through "rate" events per "second" * secs; this counts for all incoming events * * @author matsfunk */ abstract public class RateLimitedEventHandler extends EventHandler { // configuration protected int rate = 0; protected int seconds = 0; // keep track of time protected long timestamp = 0; // counter private int counter = 0; /** * creates a rate limited event handler that will at most let through "rate" event per "second" secs * * @param rate * @param seconds */ public RateLimitedEventHandler(int rate, int seconds) { this.rate = rate; this.seconds = seconds; this.timestamp = System.currentTimeMillis(); } /* * (non-Javadoc) * * @see nl.tue.id.oocsi.client.protocol.EventHandler#receive(java.lang.String, java.util.Map, long, * java.lang.String, java.lang.String) */ @Override public void receive(String sender, Map<String, Object> data, long timestamp, String channel, final String recipient) { final long currentTimeMillis = System.currentTimeMillis(); // if rate and seconds are invalid if (rate <= 0 || seconds <= 0) { // just forward the event internalReceive(sender, data, timestamp, channel, recipient); } else { // if timeout has passed if (this.timestamp + seconds * 1000l < currentTimeMillis) { this.timestamp = currentTimeMillis; this.counter = 1; internalReceive(sender, data, timestamp, channel, recipient); } // if timeout has not passed = rate limit check necessary else { if (++counter <= rate) { internalReceive(sender, data, timestamp, channel, recipient); } else { // rate limit exceeded, no forwarding exceeded(sender, data, timestamp, channel, recipient); } } } } /** * internal hook to the super class method * * @param sender * @param data * @param timestamp * @param channel * @param recipient */ final protected void internalReceive(String sender, Map<String, Object> data, long timestamp, String channel, final String recipient) { super.receive(sender, data, timestamp, channel, recipient); } public void exceeded(String sender, Map<String, Object> data, long timestamp, String channel, String recipient) { // do nothing } /** * reconfigure the rate limitation to different "rate" and "seconds" timeframe * * @param rate * @param seconds */ public void limit(int rate, int seconds) { this.rate = rate; this.seconds = seconds; } } <|start_filename|>client/src/nl/tue/id/oocsi/client/behavior/OOCSISpatial.java<|end_filename|> package nl.tue.id.oocsi.client.behavior; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentHashMap; import nl.tue.id.oocsi.OOCSIData; import nl.tue.id.oocsi.OOCSIEvent; import nl.tue.id.oocsi.client.OOCSIClient; import nl.tue.id.oocsi.client.behavior.OOCSISpatial.Position; import nl.tue.id.oocsi.client.protocol.EventHandler; import nl.tue.id.oocsi.client.protocol.Handler; import nl.tue.id.oocsi.client.protocol.MultiMessage; import nl.tue.id.oocsi.client.protocol.OOCSIMessage; import nl.tue.id.oocsi.client.services.OOCSICall; import nl.tue.id.oocsi.client.services.Responder; /** * OOCSISpatial is a system-level primitive that allows for routing across a multi-dimensional lattice of positions of * different OOCSI clients. * * @author matsfunk */ @SuppressWarnings("rawtypes") public class OOCSISpatial extends OOCSISystemCommunicator<Position> { private static final int REBALANCING_TIMEOUT = 20000; // call constants private static final String CALL = "oocsi_spatial_call"; private static final String VOTE = "oocsi_spatial_vote"; private static final String DESTINATION = "oocsi_spatial_destination_request"; private static final String DESTINATION_RESPONSE = "oocsi_spatial_destination_distance"; private static final String ROUTING_PATH = "oocsi_spatial_routing_path"; // configuration int timeout; // dynamics private Position metric; public Map<String, Position> positions = new ConcurrentHashMap<String, Position>(); private boolean votingDone = true; /** * same as all, one value and a distance metric, routing is easy (shortest by direct distance) * * @param client * @param channelName * @param key * @param neighborDistance */ public OOCSISpatial(OOCSIClient client, String channelName, String key, Position<?> neighborDistance) { this(client, channelName, key, (int) (Math.random() * REBALANCING_TIMEOUT), null); // define distance metric to separate neighbors from all others // define routing throughout the neighbors metric = neighborDistance; start(); } /** * create a new gathering process with a callback that will be called when the process is done * * @param client * @param channelName * @param key * @param timeoutMS * @param handler */ private OOCSISpatial(final OOCSIClient client, final String channelName, String key, int timeoutMS, Handler handler) { super(client, channelName + "_" + key + "_spatial", handler); this.timeout = timeoutMS; // first subscribe to sync channel subscribe(new EventHandler() { @Override public void receive(OOCSIEvent event) { // call coming in? if (event.has(CALL)) { // add my vote if it exists if (metric != null) { positions.put(OOCSISpatial.this.client.getName(), metric); } // send out my vote new OOCSIMessage(client, OOCSISpatial.this.channelName).data(VOTE, metric.serialise()) .data(HANDLE, getHandle()).send(); } // vote coming in? else if (event.has(VOTE)) { // record vote an incoming vote try { Position<?> vote = metric.deserialise(event.getString(VOTE)); if (vote != null) { positions.put(event.getSender(), vote); } } catch (ClassCastException e) { // ignore class cast exceptions } } } }); client.register(DESTINATION, new Responder(client) { @SuppressWarnings("unchecked") @Override public void respond(OOCSIEvent event, OOCSIData response) { if (event.has(DESTINATION)) { String destination = event.getString(DESTINATION); String path = event.getString(ROUTING_PATH, ""); if (path.contains(client.getName() + ",")) { response.data(DESTINATION_RESPONSE, Float.MAX_VALUE); return; } if (getNeighbors().contains(destination)) { response.data(DESTINATION_RESPONSE, metric.distance(positions.get(destination))); } else { float minDistance = Float.MAX_VALUE; int timeoutMS2 = 2000 - path.split(",").length * 100; MultiMessage mm = neighborCall(DESTINATION).data(DESTINATION, destination).data(ROUTING_PATH, path + client.getName() + ","); mm.sendAndWait(timeoutMS2); for (OOCSIMessage om : mm.getMessages()) { if (om instanceof OOCSICall) { OOCSIEvent subEvent = ((OOCSICall) om).getFirstResponse(); if (subEvent != null) { float pathLength = subEvent.getFloat(DESTINATION_RESPONSE, -1); if (pathLength < Float.MAX_VALUE) { float temp = metric.distance(positions.get(subEvent.getSender())) + pathLength; if (temp > -1 && temp < minDistance) { minDistance = temp; } } } } } response.data(DESTINATION_RESPONSE, minDistance); } } else { response.data(DESTINATION_RESPONSE, Float.MAX_VALUE); } } }); } /** * create an OOCSISpatial for 1D float positions * * @param client * @param channelName * @param key * @param myPosition * @param neighborDistance * @return */ static public OOCSISpatial createSpatial(OOCSIClient client, String channelName, String key, final float myPosition, final float neighborDistance) { return new OOCSISpatial(client, channelName, key, new Position1D(myPosition, neighborDistance)); } /** * create an OOCSISpatial for 2D float positions * * @param client * @param channelName * @param key * @param myPositionX * @param myPositionY * @param neighborDistance * @return */ static public OOCSISpatial createSpatial(OOCSIClient client, String channelName, String key, final float myPositionX, final float myPositionY, final float neighborDistance) { return new OOCSISpatial(client, channelName, key, new Position2D(myPositionX, myPositionY, neighborDistance)); } /** * stop participating in this gathering process * */ public void stop() { client.unsubscribe(this.channelName); } /** * returns the current set of direct neighbors * * @return */ @SuppressWarnings("unchecked") public List<String> getNeighbors() { List<String> resultSet = new LinkedList<String>(); for (String key : positions.keySet()) { if (!client.getName().equals(key) && metric.isNeighbor(positions.get(key))) { resultSet.add(key); } } return resultSet; } /** * returns a message container that includes messages to all neighbors which can be filled and sent all at once * * @return */ public MultiMessage neighbors() { MultiMessage mm = new MultiMessage(client); for (String nb : getNeighbors()) { mm.add(new OOCSIMessage(client, nb)); } return mm; } /** * return a message container that includes OOCSICalls to all neighbors which can be filled and sent all at once * * @param callName * @return */ public MultiMessage neighborCall(String callName) { MultiMessage mm = new MultiMessage(client); for (String nb : getNeighbors()) { mm.add(new OOCSICall(client, nb, callName, 2000, 100)); } return mm; } /** * returns the handle of the closest neighbor * * @return */ @SuppressWarnings("unchecked") public String getClosestNeighbor() { return metric.closestNeighbor(positions); } /** * returns the handle of the neighbor through which the closest path to the destination can be routed at this moment * * @param destination * @return */ @SuppressWarnings("unchecked") public String routing(String destination) { // is my direct neighbor? if (getNeighbors().contains(destination)) { return destination; } // not my direct neighbor... // send to all neighbors to ask their neighbors // add my name to path, so I don't have to answer my own question when my neighbor calls back MultiMessage mm = neighborCall(DESTINATION).data(DESTINATION, destination).data(ROUTING_PATH, client.getName() + ","); mm.sendAndWait(); float minDistance = Float.MAX_VALUE; String neighbor = null; for (OOCSIMessage om : mm.getMessages()) { if (om instanceof OOCSICall) { OOCSIEvent event = ((OOCSICall) om).getFirstResponse(); if (event != null) { // get length of path from neighbor onwards float pathLength = event.getFloat(DESTINATION_RESPONSE, -1); if (pathLength > -1 && pathLength < Float.MAX_VALUE) { // add distance to neighbor to path length pathLength = metric.distance(positions.get(event.getSender())) + pathLength; if (pathLength > -1 && pathLength < minDistance) { // if ok, this is now the smallest distance minDistance = pathLength; neighbor = event.getSender(); } } } } } // now we send off the data towards the shortest route neighbor return neighbor; } /** INTERNAL */ /** * start the consensus process * */ private void start() { // only if timeout has passed (throttling) if (!votingDone) { return; } // clear previous votes positions.clear(); // request positions message(CALL); // add my vote internally positions.put(client.getName(), metric); // directly send my vote, so others know about it as well new OOCSIMessage(client, this.channelName).data(VOTE, metric.serialise()).data(HANDLE, getHandle()).send(); // close voting after timeout has passed new Timer(true).schedule(new TimerTask() { @Override public void run() { votingDone = true; // report back if handler is given triggerHandler(); } // trigger after 10 * timeout milliseconds }, timeout * 10); } abstract static class Position<T> implements DistanceMetric<T> { abstract public String serialise(); abstract public Position<T> deserialise(String position); } public static interface DistanceMetric<T> { public float distance(T value); public boolean isNeighbor(T value); public String closestNeighbor(Map<String, T> positions); } static class Position1D extends Position<Position1D> { private float myPosition; private float neighborDistance; public Position1D(float position, float neighborDistance) { this.myPosition = position; this.neighborDistance = neighborDistance; } @Override public float distance(Position1D value) { return Math.abs(myPosition - value.myPosition); } @Override public boolean isNeighbor(Position1D value) { return distance(value) <= neighborDistance; } @Override public String closestNeighbor(Map<String, Position1D> positions) { String result = null; float minDistance = neighborDistance; for (String key : positions.keySet()) { float abs = distance(positions.get(key)); if (abs > 0 && abs < minDistance) { minDistance = abs; result = key; } } return result; } @Override public String serialise() { return "" + myPosition; } @Override public Position1D deserialise(String position) { return new Position1D(Float.parseFloat(position), neighborDistance); } } static class Position2D extends Position<Position2D> { private float myPositionX; private float myPositionY; private float neighborDistance; public Position2D(float positionX, float positionY, float neighborDistance) { this.myPositionX = positionX; this.myPositionY = positionY; this.neighborDistance = neighborDistance; } @Override public float distance(Position2D value) { return (float) Math .sqrt(Math.pow(myPositionX - value.myPositionX, 2) + Math.pow(myPositionY - value.myPositionY, 2)); } @Override public boolean isNeighbor(Position2D value) { return distance(value) <= neighborDistance; } @Override public String closestNeighbor(Map<String, Position2D> positions) { String result = null; float minDistance = neighborDistance; for (String key : positions.keySet()) { float abs = distance(positions.get(key)); if (abs > 0 && abs < minDistance) { minDistance = abs; result = key; } } return result; } @Override public String serialise() { return myPositionX + ";" + myPositionY; } @Override public Position2D deserialise(String position) { String[] ps = position.split(";"); return new Position2D(Float.parseFloat(ps[0]), Float.parseFloat(ps[1]), neighborDistance); } } } <|start_filename|>server/src/nl/tue/id/oocsi/server/model/Client.java<|end_filename|> package nl.tue.id.oocsi.server.model; import nl.tue.id.oocsi.server.protocol.Message; /** * data structure for client * * @author matsfunk * */ abstract public class Client extends Channel { protected enum ClientType { OOCSI, PD, JSON, OSC } private long lastAction = System.currentTimeMillis(); /** * constructor * * @param token */ public Client(String token, ChangeListener presence) { super(token, presence); } /* * (non-Javadoc) * * @see nl.tue.id.oocsi.server.model.Channel#send(nl.tue.id.oocsi.server.protocol .Message) */ abstract public void send(Message message); /** * disconnect this client from server */ abstract public void disconnect(); /** * check if this client is still connected * * @return */ abstract public boolean isConnected(); /** * ping the client to fill in the last action property, ultimately determining an inactive client * */ abstract public void ping(); /** * acknowledge that a ping was responded to by the remote client */ abstract public void pong(); /** * retrieves time stamp of last action from the connected client * * @return */ public long lastAction() { return lastAction; } /** * set last action to now * */ public void touch() { lastAction = System.currentTimeMillis(); } } <|start_filename|>server/src/nl/tue/id/oocsi/server/services/SocketService.java<|end_filename|> package nl.tue.id.oocsi.server.services; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketAddress; import java.net.SocketException; import java.net.UnknownHostException; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import nl.tue.id.oocsi.server.OOCSIServer; import nl.tue.id.oocsi.server.model.Client; import nl.tue.id.oocsi.server.model.Server; /** * socket service component * * @author matsfunk * */ public class SocketService extends AbstractService { private static final int MULTICAST_PORT = 4448; private static final String MULTICAST_GROUP = "192.168.127.12"; private final int port; private final String[] registeredUsers; private ServerSocket serverSocket; private boolean listening = true; /** * create a TCP socket service for OOCSI * * @param server * @param port */ public SocketService(Server server, int port, String[] registeredUsers) { super(server); this.port = port; this.registeredUsers = registeredUsers; } /* * (non-Javadoc) * * @see nl.tue.id.oocsi.server.services.AbstractService#register(nl.tue.id.oocsi.server.model.Client) */ @Override public boolean register(Client client) { // non-private clients, normal procedure if (!client.isPrivate()) { return super.register(client); } // for private clients, first check whether it needs to comply to existing users final String name = client.getName(); if (registeredUsers != null) { for (String user : registeredUsers) { if (user == null || !user.replaceFirst(":.*", "").equals(name)) { continue; } // if there is a match, replace client if (client.validate(user)) { return super.register(client); } else { return false; } } } // for non-private clients return !client.isPrivate() && super.register(client); } /* * (non-Javadoc) * * @see nl.tue.id.oocsi.server.services.AbstractService#start() */ public void start() { try { // configure server socket serverSocket = new ServerSocket(); serverSocket.setPerformancePreferences(0, 1, 0); serverSocket.setReuseAddress(true); // bind to localhost at port <port> SocketAddress sockaddr = new InetSocketAddress(port); serverSocket.bind(sockaddr); } catch (IOException e) { OOCSIServer.log("[TCP socket server]: Could not listen on port: " + port); } InetAddress addr; try { addr = InetAddress.getLocalHost(); final String hostname = addr.getHostName(); OOCSIServer.log("[TCP socket server]: Started TCP service @ local address '" + hostname + "' on port " + port + " for TCP"); // configure periodic services Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(new Runnable() { private DatagramSocket socket; @Override public void run() { // multicast beacon try { if (socket == null) { socket = new DatagramSocket(); } InetAddress group = InetAddress.getByName(MULTICAST_GROUP); String dString = "OOCSI@" + hostname + ":" + port; byte[] buf = dString.getBytes(); DatagramPacket packet = new DatagramPacket(buf, buf.length, group, MULTICAST_PORT); socket.send(packet); } catch (Exception e) { // e.printStackTrace(); } }; }, 1000, (long) (5 * 1000 + Math.random() * 1000), TimeUnit.MILLISECONDS); // socket service operations while (listening) { if (!serverSocket.isBound()) { Thread.yield(); continue; } // first see if there is a new connection coming in Socket acceptedSocket = serverSocket.accept(); // then check if we can accept a new client if (server.canAcceptClient(null)) { new SocketClient(this, acceptedSocket).start(); } else { acceptedSocket.close(); } } serverSocket.close(); } catch (SocketException e) { // only report if still listening if (listening) { e.printStackTrace(); } } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { // only report if still listening if (listening) { e.printStackTrace(); } } } /* * (non-Javadoc) * * @see nl.tue.id.oocsi.server.services.AbstractService#stop() */ public void stop() { // switch off listening loop listening = false; // close server socket try { serverSocket.close(); } catch (IOException e) { } } } <|start_filename|>client/src/nl/tue/id/oocsi/client/services/Service.java<|end_filename|> package nl.tue.id.oocsi.client.services; import java.util.LinkedList; import java.util.List; import nl.tue.id.oocsi.client.OOCSIClient; public class Service { public String name; public String handle; public String uuid; public String category; public List<ServiceMethod> methods = new LinkedList<ServiceMethod>(); public ServiceMethod newServiceMethod() { ServiceMethod serviceMethod = new ServiceMethod(name); methods.add(serviceMethod); return serviceMethod; } public static class ServiceMethod { public String serviceName; public String name; public String handle; public String uuid; public List<ServiceField<?>> input = new LinkedList<Service.ServiceField<?>>(); public List<ServiceField<?>> output = new LinkedList<Service.ServiceField<?>>(); /** * hidden constructor, so users will build the method via the service * * @param serviceName */ private ServiceMethod(String serviceName) { this.serviceName = serviceName; } /** * register a responder for this method * * @param oocsi * @param responder */ public void registerResponder(OOCSIClient oocsi, Responder responder) { responder.setOocsi(oocsi); responder.setCallName(getName()); oocsi.register(getName(), responder); } /** * build a call to a responder on OOCSI for this method * * @param oocsi * @param timeoutMS * @param maxResponses * @return */ public OOCSICall buildCall(OOCSIClient oocsi, int timeoutMS, int maxResponses) { OOCSICall call = new OOCSICall(oocsi, getName(), timeoutMS, maxResponses); for (ServiceField<?> field : input) { call.data(field.name, field.defaultValue); } return call; } /** * get method name respective the service * * @return */ public String getName() { return serviceName + '.' + name; } } public static class ServiceField<T> { public String name; public T defaultValue; public T value; public ServiceField(String name) { this.name = name; } public ServiceField(String name, T defaultValue) { this.name = name; this.defaultValue = defaultValue; } public void set(T value) { this.value = value; } public String getType() { return this.value.getClass().getName(); } } } <|start_filename|>client/src/nl/tue/id/oocsi/client/behavior/OOCSIAwareness.java<|end_filename|> package nl.tue.id.oocsi.client.behavior; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import nl.tue.id.oocsi.OOCSIEvent; import nl.tue.id.oocsi.client.OOCSIClient; import nl.tue.id.oocsi.client.protocol.EventHandler; /** * OOCSIAwareness is a system-level primitive that allows for local representations of different OOCSI clients on the * same channel and the data they share on that channel. The local representation will be about several keys or all * data. This realizes synchronization on data without aggregation. * * @author matsfunk */ public class OOCSIAwareness extends OOCSISystemCommunicator<String> { // constant private String OOCSIAwarenessTimeoutKey = "OOCSIAwarenessTimeout_" + Math.random(); // configuration private int timeout = 0; private List<String> keys = new LinkedList<String>(); // dynamics private Map<String, Map<String, Object>> representation = new ConcurrentHashMap<String, Map<String, Object>>(); /** * create a new awareness process on the given channel for ALL data * * @param client * @param channelName */ public OOCSIAwareness(OOCSIClient client, String channelName) { this(client, channelName, 0, new String[] {}); } /** * create a new awareness process on the given channel for the specified data (as keys) * * @param client * @param channelName * @param keys */ public OOCSIAwareness(OOCSIClient client, String channelName, String... keys) { this(client, channelName, 0, keys); } /** * create a new awareness process on the given channel for the specified data (as keys), a timeout is specified to * "forget" nodes on the channel, unless they post data during the timeout duration * * @param client * @param channelName * @param timeout * @param keys */ public OOCSIAwareness(OOCSIClient client, String channelName, int timeout, String... keys) { super(client, channelName + "_awareness"); this.timeout = timeout; for (String key : keys) { this.keys.add(key); } subscribe(new EventHandler() { @Override public void receive(OOCSIEvent event) { // get or create data map for sender Map<String, Object> map; String sender = event.getSender(); if (!representation.containsKey(sender)) { representation.put(sender, map = new HashMap<String, Object>()); } else { map = get(sender); } if (map != null) { // last updated map.put(OOCSIAwarenessTimeoutKey, System.currentTimeMillis()); // store all if no keys are given if (OOCSIAwareness.this.keys.isEmpty()) { for (String key : event.keys()) { map.put(key, event.getObject(key)); } } // store keys selectively else { for (String key : OOCSIAwareness.this.keys) { if (event.has(key)) { Object value = event.getObject(key); if (value != null) { map.put(key, value); } } } } } } }); } /** * retrieve the number of nodes * * @return */ public int size() { return representation.size(); } /** * check whether nodes are locally represented * * @return */ public boolean isEmpty() { return representation.isEmpty(); } /** * check whether a node given by nodeName is represented * * @param nodeName * @return */ public boolean containsNode(Object nodeName) { return representation.containsKey(nodeName); } private Map<String, Object> get(String node) { if (representation.containsKey(node)) { Map<String, Object> map = representation.get(node); if (timeout == 0 || ((Long) map.get(OOCSIAwarenessTimeoutKey)) > System.currentTimeMillis() - timeout) { return map; } else { representation.remove(node); } } return null; } /** * get data with key from node with given name * * @param nodeName * @param key * @param defaultValue * @return */ public Integer get(String nodeName, String key, int defaultValue) { Map<String, Object> map = get(nodeName); return map != null ? (Integer) map.get(key) : defaultValue; } /** * get data with key from node with given name * * @param nodeName * @param key * @param defaultValue * @return */ public Long get(String nodeName, String key, long defaultValue) { Map<String, Object> map = get(nodeName); return map != null ? (Long) map.get(key) : defaultValue; } /** * get data with key from node with given name * * @param nodeName * @param key * @param defaultValue * @return */ public Double get(String nodeName, String key, double defaultValue) { Map<String, Object> map = get(nodeName); return map != null ? (Double) map.get(key) : defaultValue; } /** * get data with key from node with given name * * @param nodeName * @param key * @param defaultValue * @return */ public float get(String nodeName, String key, float defaultValue) { Map<String, Object> map = get(nodeName); return map != null ? (Float) map.get(key) : defaultValue; } /** * get data with key from node with given name * * @param nodeName * @param key * @param defaultValue * @return */ public String get(String nodeName, String key, String defaultValue) { Map<String, Object> map = get(nodeName); return map != null ? (String) map.get(key) : defaultValue; } /** * get data with key from node with given name * * @param nodeName * @param key * @return */ public Object get(String nodeName, String key) { Map<String, Object> map = get(nodeName); return map != null ? map.get(key) : null; } /** * remove a node from the local representation * * @param key * @return */ public Map<String, Object> remove(String key) { return representation.remove(key); } /** * retrieve set of node names * * @return */ public Set<String> nodes() { return representation.keySet(); } /** * retrieve all keys that will be represented from node data (configured in constructor) * * @return */ public List<String> keys() { return Collections.unmodifiableList(keys); } } <|start_filename|>client/src/nl/tue/id/oocsi/client/behavior/OOCSISync.java<|end_filename|> package nl.tue.id.oocsi.client.behavior; import java.util.Timer; import java.util.TimerTask; import nl.tue.id.oocsi.OOCSIEvent; import nl.tue.id.oocsi.client.OOCSIClient; import nl.tue.id.oocsi.client.protocol.EventHandler; import nl.tue.id.oocsi.client.protocol.Handler; /** * OOCSISync is a system-level primitive that allows for easy synchronization between different OOCSI clients on the * same channel. Synchronization is on triggers, not on data, for which we have OOCSIVote. * * @author matsfunk */ public class OOCSISync extends OOCSISystemCommunicator<Integer> { // call constants private static final String SYNC = "sync"; private static final String CYCLE = "cycle"; // sync resolution private static int PERIOD = 20; // progress sync point (to avoid spikes in network communication) private static int progressSync = (int) (Math.random() * (float) PERIOD); // infrastructure, configuration private int periodMS; // dynamics private Timer timer; private boolean isSynced = false; private int progress = 0; private int cycle = 0; /** * creates a synchronization process among OOCSI clients on the same channel with a default of 2 secs between * pulses. starts automatically. * * @param client * @param channelName */ public OOCSISync(OOCSIClient client, String channelName) { this(client, channelName, 2000); } /** * creates a synchronization process among OOCSI clients on the same channel with a given time between pulses. * starts automatically. * * @param client * @param channelName * @param periodMS */ public OOCSISync(OOCSIClient client, String channelName, int periodMS) { this(client, channelName, periodMS, null); } /** * creates a synchronization process among OOCSI clients on the same channel with a given time between pulses and a * callback to trigger at every pulse. starts automatically. * * @param client * @param channelName * @param periodMS * @param handler */ public OOCSISync(OOCSIClient client, String channelName, int periodMS, Handler handler) { super(client, channelName + "_sync", handler); this.periodMS = periodMS; // first subscribe to sync channel subscribe(new EventHandler() { @Override public void receive(OOCSIEvent event) { if (event.has(SYNC)) { int progressSync = PERIOD - event.getInt(SYNC, 0); int virtualProgress = (progress + progressSync) % PERIOD; // compare the synchronizing from others to my own progress in the periodic sync cycle if (virtualProgress < getPeriodFraction(0.05) || virtualProgress > getPeriodFraction(0.95)) { isSynced = true; } else if (virtualProgress <= getPeriodFraction(0.9)) { long d = Math.round(getPeriodFraction(1. / PERIOD) * Math.random()) - Math.round((float) virtualProgress / PERIOD); progress -= d; isSynced = false; } else { isSynced = false; } // cycle update if (event.has(CYCLE)) { cycle = Math.max(cycle, event.getInt(CYCLE, 0)); } } } }); start(); } /** * start the synchronization process * */ public void start() { // send out sync signal myself periodically (timer = new Timer(true)).schedule(new TimerTask() { @Override public void run() { // send sync signal to channel if (progress == progressSync) { message().data(SYNC, progress).data(CYCLE, cycle).send(); } // reset progress if (progress-- <= 0) { // trigger pulse triggerHandler(); // increase cycle cycle++; // reset progress progress = PERIOD; } } }, (int) (periodMS / PERIOD), (int) (periodMS / PERIOD)); } /** * stop the synchronization process * */ public void stop() { // cancel the thread timer.cancel(); timer = null; // unsubscribe from sync channel client.unsubscribe(channelName); // reset reset(); // sync primitive is now essentially at startup state, can be started again later on } /** * reset dynamic properties * */ public void reset() { progress = (int) PERIOD; isSynced = false; } /** * return the cycle progress (an integer value from 0 - 19) * * @return */ public int getProgress() { return progress; } /** * return the current cycle count * * @return */ public int getCycle() { return cycle; } /** * returns the resolution of this synchronization process * * @return */ public int getResolution() { return (int) PERIOD; } /** * set the resolution of this synchronization process (20 works well, but 100 gives nicer output for using in * visuals); rule of thumb: the smaller the resolution, the faster the synchornization * * @param resolution */ public void setResolution(int resolution) { PERIOD = resolution; } /** * check if this system process is running * * @return */ public boolean isRunning() { return timer != null; } /** * are we synchronized to the channel? * * @return */ public boolean isSynced() { return isSynced; } /** INTERNAL */ private int getPeriodFraction(double fraction) { return (int) Math.round(Math.max(1, PERIOD * fraction)); } } <|start_filename|>client/src/nl/tue/id/oocsi/client/behavior/OOCSISpread.java<|end_filename|> package nl.tue.id.oocsi.client.behavior; import java.util.HashMap; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import nl.tue.id.oocsi.OOCSIEvent; import nl.tue.id.oocsi.client.OOCSIClient; import nl.tue.id.oocsi.client.protocol.EventHandler; import nl.tue.id.oocsi.client.protocol.Handler; /** * OOCSISpread is a system-level primitive that allows for easy allocation of all OOCSI clients in a channel. The * allocation will be about a single key or data item, for which eventually an allocation is provided. This realizes a * distribution of roles that can be used to perform different tasks in a system. * * @author matsfunk */ public class OOCSISpread extends OOCSISystemCommunicator<Integer> { // call constants private static final String ROLE = "role"; private static final int REBALANCE = 80; // infrastructure private int timeout; // confirmed roles private Map<String, Integer> roles = new HashMap<String, Integer>(); // my role (1 - ...), 0: no role private int role = 0; // frame counters private long frameCount = 0; private long framesSinceAssignment = 0; // flag to enable or disable period re-balancing of allocations private boolean isRebalancing = false; /** * create a new OOCSI spread * * @param client * @param channelName * @param key * @param timeoutMS */ public OOCSISpread(OOCSIClient client, String channelName, String key, int timeoutMS) { this(client, channelName, key, timeoutMS, null); } /** * create a new OOCSI spread with a handler that will be triggered once a stable allocation has been established * * @param client * @param channelName * @param key * @param timeoutMS * @param handler */ public OOCSISpread(OOCSIClient client, String channelName, String key, int timeoutMS, Handler handler) { super(client, channelName + "_" + key + "_spread", handler); this.timeout = timeoutMS; subscribe(new EventHandler() { @Override public void receive(OOCSIEvent event) { // record confirmed roles for others if (event.has(ROLE)) { int confirmedRole = event.getInt(ROLE, -1); String confirmedHandle = event.getString(HANDLE, "");// event.getSender(); if (confirmedRole > -1 && confirmedHandle != null && confirmedHandle.length() > 0) { roles.put(confirmedHandle, confirmedRole); // if someone has the same role and I'm still in election, start a new round by resetting my // role if (confirmedRole == role && !confirmedHandle.equals(getHandle())) { role = 0; framesSinceAssignment = 0; } } } } }); start(); } /** * internally start the allocation process * */ private void start() { new Timer(true).schedule(new TimerTask() { @Override public void run() { // counters for frames frameCount++; framesSinceAssignment++; // if not role was allocated if (role == 0) { // start with 1 and use cache to pick better next number int triedRole = 1; while (roles.values().contains(triedRole)) { triedRole++; } // assume this role for now role = triedRole; framesSinceAssignment = 0; } // if a role was allocated if (role > 0) { if (isRebalancing) { // sometimes clear the roles, to shake it up if (framesSinceAssignment > REBALANCE * role) { reset(); } } // send my role periodically if (frameCount % 5 == 0) { // send out my role periodically message(ROLE, role); } } // after balancing, call trigger if (isDone()) { triggerHandler(); } } }, OOCSISpread.this.timeout / 20 + Math.round(Math.random() * OOCSISpread.this.timeout), OOCSISpread.this.timeout / 20 + Math.round(Math.random() * OOCSISpread.this.timeout)); } /** * reset the current allocation * */ public void reset() { roles.clear(); role = 0; frameCount = 0; framesSinceAssignment = 0; } /** * return the current allocation of this instance * * @return */ public int get() { return role; } /** * return whether the allocation process is temporarily done (= no changes have occurred for a reasonable time) * * @return */ public boolean isDone() { return role != -1 && framesSinceAssignment > 10; } /** * return whether period re-balancing of allocation is switched on or off * * @return */ public boolean isRebalancing() { return isRebalancing; } /** * switch periodic re-balancing of allocation * * @param rebalancing */ public void setRebalancing(boolean rebalancing) { this.isRebalancing = rebalancing; } } <|start_filename|>client/test/ClientConnectionTest.java<|end_filename|> import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.BeforeClass; import org.junit.Test; import nl.tue.id.oocsi.OOCSIEvent; import nl.tue.id.oocsi.client.OOCSIClient; import nl.tue.id.oocsi.client.protocol.DataHandler; import nl.tue.id.oocsi.client.protocol.Handler; import nl.tue.id.oocsi.client.protocol.RateLimitedClientEventHandler; import nl.tue.id.oocsi.client.protocol.RateLimitedEventHandler; public class ClientConnectionTest { @BeforeClass public static void checkClientList() { OOCSIClient o = new OOCSIClient("pre_checks"); o.connect("localhost", 4444); assertTrue(o.isConnected()); assertTrue(o.clients().contains("pre_checks")); o.disconnect(); } @Test public void testConnectionToServer() { OOCSIClient o = new OOCSIClient("test_client"); o.connect("localhost", 4444); assertTrue(o.isConnected()); o.disconnect(); } @Test public void testConnectAndDisconnect() throws InterruptedException { OOCSIClient o = new OOCSIClient("test_client_0"); o.connect("localhost", 4444); assertTrue(o.isConnected()); Thread.sleep(500); o.disconnect(); Thread.sleep(500); assertTrue(!o.isConnected()); o.disconnect(); } @Test public void testConnectAndKill() throws InterruptedException { OOCSIClient o = new OOCSIClient("test_client_0_kill"); o.setReconnect(false); o.connect("localhost", 4444); assertTrue(o.isConnected()); // this is necessary, so the old client does not respond to server pings anymore o.kill(); Thread.sleep(2500); { OOCSIClient o1 = new OOCSIClient("test_client_0_kill"); o1.connect("localhost", 4444); Thread.sleep(100); assertTrue(o1.isConnected()); o1.disconnect(); } o.disconnect(); } @Test public void testConnectReconnect() throws InterruptedException { OOCSIClient o = new OOCSIClient("test_client_0_reconnect") { // @Override // public void log(String message) { // System.out.println(message); // } }; o.setReconnect(true); o.connect("localhost", 4444); Thread.sleep(2000); assertTrue(o.isConnected()); Thread.sleep(500); o.reconnect(); assertTrue(!o.isConnected()); Thread.sleep(500); assertTrue(o.isConnected()); o.setReconnect(false); o.reconnect(); assertTrue(!o.isConnected()); Thread.sleep(500); assertTrue(!o.isConnected()); o.disconnect(); } @Test public void testConnectReconnectSubscriptions() throws InterruptedException { final List<String> list = new ArrayList<String>(); OOCSIClient o = new OOCSIClient("test_client_0_reconnect_subscriptions1") { // @Override // public void log(String message) { // System.out.println(message); // } }; ; o.setReconnect(true); o.connect("localhost", 4444); o.subscribe("subscriptionTest", new Handler() { @Override public void receive(String sender, Map<String, Object> data, long timestamp, String channel, String recipient) { list.add("event received"); } }); Thread.sleep(1000); assertTrue(o.isConnected()); OOCSIClient o2 = new OOCSIClient("test_client_0_reconnect_subscriptions2"); o2.connect("localhost", 4444); assertTrue(o2.isConnected()); o2.send("subscriptionTest", "some unimportant data"); Thread.sleep(500); assertTrue(!list.isEmpty()); list.clear(); Thread.sleep(500); o.reconnect(); assertTrue(!o.isConnected()); Thread.sleep(500); assertTrue(o.isConnected()); OOCSIClient o3 = new OOCSIClient("test_client_0_reconnect_subscriptions3"); o3.connect("localhost", 4444); assertTrue(o3.isConnected()); o3.send("subscriptionTest", "some unimportant data"); Thread.sleep(500); assertTrue(!list.isEmpty()); o.disconnect(); o2.disconnect(); o3.disconnect(); } @Test public void testSendReceive() throws InterruptedException { final List<String> list = new ArrayList<String>(); OOCSIClient o1 = new OOCSIClient("test_client_1r"); o1.connect("localhost", 4444); assertTrue(o1.isConnected()); o1.subscribe(new DataHandler() { public void receive(String sender, Map<String, Object> data, long timestamp) { list.add(sender); } }); OOCSIClient o2 = new OOCSIClient("test_client_2r"); o2.connect("localhost", 4444); assertTrue(o2.isConnected()); o2.subscribe(new DataHandler() { public void receive(String sender, Map<String, Object> data, long timestamp) { list.add(sender); } }); o1.send("test_client_2r", "hello2"); Thread.yield(); Thread.sleep(3000); assertEquals(1, list.size()); assertEquals("test_client_1r", list.get(0)); o2.send("test_client_1r", "hello1"); Thread.yield(); Thread.sleep(3000); assertEquals(2, list.size()); assertEquals("test_client_2r", list.get(1)); o1.disconnect(); o2.disconnect(); } @Test public void testSendReceive2() throws InterruptedException { final List<Long> list = new ArrayList<Long>(); OOCSIClient o1 = new OOCSIClient("test_client_3s"); o1.connect("localhost", 4444); assertTrue(o1.isConnected()); o1.subscribe(new DataHandler() { public void receive(String sender, Map<String, Object> data, long timestamp) { list.add((Long) data.get("data")); } }); Map<String, Object> map1 = new HashMap<String, Object>(); map1.put("data", System.currentTimeMillis()); OOCSIClient o2 = new OOCSIClient("test_client_4s"); o2.connect("localhost", 4444); assertTrue(o2.isConnected()); o2.subscribe(new DataHandler() { public void receive(String sender, Map<String, Object> data, long timestamp) { list.add((Long) data.get("data")); } }); Map<String, Object> map2 = new HashMap<String, Object>(); map2.put("data", System.currentTimeMillis()); o1.send("test_client_3s", map1); Thread.yield(); Thread.sleep(3000); assertEquals(1, list.size()); assertEquals(list.get(0), map1.get("data")); o2.send("test_client_4s", map2); Thread.yield(); Thread.sleep(3000); assertEquals(2, list.size()); assertEquals(list.get(1), map2.get("data")); o1.disconnect(); o2.disconnect(); } @Test public void testRateLimit() throws InterruptedException { final List<String> list = new ArrayList<String>(); OOCSIClient o1 = new OOCSIClient("test_client_rate_limit_1"); o1.connect("localhost", 4444); assertTrue(o1.isConnected()); o1.subscribe(new RateLimitedEventHandler(5, 3) { public void receive(OOCSIEvent event) { list.add(event.getSender()); } }); OOCSIClient o2 = new OOCSIClient("test_client_rate_limit_2"); o2.connect("localhost", 4444); assertTrue(o2.isConnected()); o2.subscribe(new RateLimitedEventHandler(2, 3) { public void receive(OOCSIEvent event) { list.add(event.getSender()); } }); assertEquals(0, list.size()); // appear o1.send("test_client_rate_limit_2", "hello1y"); o1.send("test_client_rate_limit_2", "hello2y"); // won't appear o1.send("test_client_rate_limit_2", "hello3n"); Thread.sleep(1000); assertEquals(2, list.size()); // appear all o2.send("test_client_rate_limit_1", "hello4y"); o2.send("test_client_rate_limit_1", "hello5y"); o2.send("test_client_rate_limit_1", "hello6y"); Thread.sleep(1000); assertEquals(5, list.size()); // won't appear o1.send("test_client_rate_limit_2", "hello7n"); o1.send("test_client_rate_limit_2", "hello8n"); o1.send("test_client_rate_limit_2", "hello9n"); // appear o2.send("test_client_rate_limit_1", "hello10y"); o2.send("test_client_rate_limit_1", "hello11y"); // won't appear o2.send("test_client_rate_limit_1", "hello12n"); Thread.sleep(500); assertEquals(7, list.size()); // wait for timeout reset Thread.sleep(500); // appear o1.send("test_client_rate_limit_2", "hello13y"); o1.send("test_client_rate_limit_2", "hello14y"); // won't appear o1.send("test_client_rate_limit_2", "hello15n"); // appear o2.send("test_client_rate_limit_1", "hello16y"); o2.send("test_client_rate_limit_1", "hello17y"); o2.send("test_client_rate_limit_1", "hello18y"); Thread.sleep(500); for (String string : list) { System.out.println(string); } assertEquals(12, list.size()); o1.disconnect(); o2.disconnect(); } @Test public void testRateLimitPerClient() throws InterruptedException { final List<String> list = new ArrayList<String>(); OOCSIClient o1 = new OOCSIClient("test_client_rate_limit_pc_1"); o1.connect("localhost", 4444); assertTrue(o1.isConnected()); o1.subscribe(new RateLimitedClientEventHandler(2, 3) { public void receive(OOCSIEvent event) { list.add(event.getSender()); } }); OOCSIClient o2 = new OOCSIClient("test_client_rate_limit_pc_2"); o2.connect("localhost", 4444); assertTrue(o2.isConnected()); OOCSIClient o3 = new OOCSIClient("test_client_rate_limit_pc_3"); o3.connect("localhost", 4444); assertTrue(o3.isConnected()); assertEquals(0, list.size()); // appear o2.send("test_client_rate_limit_pc_1", "hello1y"); o2.send("test_client_rate_limit_pc_1", "hello2y"); // won't appear o2.send("test_client_rate_limit_pc_1", "hello3n"); Thread.sleep(1500); assertEquals(2, list.size()); // appear all o3.send("test_client_rate_limit_pc_1", "hello4y"); o3.send("test_client_rate_limit_pc_1", "hello5y"); // won't appear o3.send("test_client_rate_limit_pc_1", "hello6n"); Thread.sleep(500); assertEquals(4, list.size()); // won't appear o2.send("test_client_rate_limit_pc_1", "hello7n"); o2.send("test_client_rate_limit_pc_1", "hello8n"); o2.send("test_client_rate_limit_pc_1", "hello9n"); o3.send("test_client_rate_limit_pc_1", "hello10n"); o3.send("test_client_rate_limit_pc_1", "hello11n"); o3.send("test_client_rate_limit_pc_1", "hello12n"); Thread.sleep(500); assertEquals(4, list.size()); // wait for timeout reset Thread.sleep(1500); // appear o2.send("test_client_rate_limit_pc_1", "hello13y"); o2.send("test_client_rate_limit_pc_1", "hello14y"); // won't appear o2.send("test_client_rate_limit_pc_1", "hello15n"); // appear o3.send("test_client_rate_limit_pc_1", "hello16y"); o3.send("test_client_rate_limit_pc_1", "hello17y"); // won't appear o3.send("test_client_rate_limit_pc_1", "hello18n"); Thread.sleep(500); for (String string : list) { System.out.println(string); } assertEquals(8, list.size()); o1.disconnect(); o2.disconnect(); o3.disconnect(); } @Test public void testChannelNameParsing() throws InterruptedException { final List<String> list = new ArrayList<String>(); OOCSIClient o1 = new OOCSIClient("test_client_cnameparser_1"); o1.connect("localhost", 4444); assertTrue(o1.isConnected()); o1.subscribe("testpattern_-AZ09<>!#$@%$*^", new DataHandler() { public void receive(String sender, Map<String, Object> data, long timestamp) { list.add(sender); } }); OOCSIClient o2 = new OOCSIClient("test_client_cnameparser_2"); o2.connect("localhost", 4444); assertTrue(o2.isConnected()); // baseline assertEquals(0, list.size()); // test correct password o2.send("testpattern_-AZ09<>!#$@%$*^", "hello1"); Thread.sleep(100); assertEquals(1, list.size()); o2.send("testpattern", "hello2"); Thread.sleep(100); assertEquals(1, list.size()); o2.send("AZ09<>!#$@%$*^", "hello1"); Thread.sleep(100); assertEquals(1, list.size()); o2.send("testpattern_-AZ09<>!#$@%$*^", "hello1"); Thread.sleep(100); assertEquals(2, list.size()); o1.disconnect(); o2.disconnect(); } @Test public void testClientPresence() throws InterruptedException { final List<String> list = new ArrayList<String>(); OOCSIClient o1 = new OOCSIClient("test_client_presence_1"); o1.connect("localhost", 4444); assertTrue(o1.isConnected()); // baseline assertEquals(0, list.size()); o1.subscribe("presence(test_client_presence_2)", new DataHandler() { public void receive(String sender, Map<String, Object> data, long timestamp) { list.add(sender + data.toString()); } }); Thread.sleep(100); // test _client_presence_2 is not yet registered, so absent assertEquals(0, list.size()); OOCSIClient o2 = new OOCSIClient("test_client_presence_2"); o2.connect("localhost", 4444); assertTrue(o2.isConnected()); Thread.sleep(100); assertTrue(list.get(0).contains("join")); o2.disconnect(); Thread.sleep(100); assertTrue(list.size() > 1); assertTrue(list.get(list.size() - 1).contains("leave")); o1.disconnect(); } @Test public void testChannelPresence() throws InterruptedException { final List<String> list = new ArrayList<String>(); OOCSIClient o1 = new OOCSIClient("test_channel_presence_1"); o1.connect("localhost", 4444); assertTrue(o1.isConnected()); o1.subscribe("presence(test_presence)", new DataHandler() { public void receive(String sender, Map<String, Object> data, long timestamp) { list.add(sender + data.toString()); } }); Thread.sleep(100); // baseline assertEquals(0, list.size()); OOCSIClient o2 = new OOCSIClient("test_channel_presence_2"); o2.connect("localhost", 4444); assertTrue(o2.isConnected()); Thread.sleep(200); assertEquals(0, list.size()); o2.subscribe("test_presence", null); Thread.sleep(100); assertEquals(1, list.size()); o2.subscribe("test_presence_wrong", null); Thread.sleep(100); assertEquals(1, list.size()); o2.unsubscribe("test_presence"); Thread.sleep(100); assertEquals(2, list.size()); o1.disconnect(); o2.disconnect(); } @Test public void testPrivateChannel() throws InterruptedException { final List<String> list = new ArrayList<String>(); OOCSIClient o1 = new OOCSIClient("test_client_private_1"); o1.connect("localhost", 4444); assertTrue(o1.isConnected()); o1.subscribe("test:password", new DataHandler() { public void receive(String sender, Map<String, Object> data, long timestamp) { list.add(sender); } }); OOCSIClient o2 = new OOCSIClient("test_client_private_2"); o2.connect("localhost", 4444); assertTrue(o2.isConnected()); o2.subscribe("test", new DataHandler() { public void receive(String sender, Map<String, Object> data, long timestamp) { list.add(sender); } }); OOCSIClient o3 = new OOCSIClient("test_client_private_3"); o3.connect("localhost", 4444); assertTrue(o3.isConnected()); // baseline assertEquals(0, list.size()); // test without password o3.send("test", "hello1"); Thread.sleep(100); assertEquals(0, list.size()); // test wrong pass 1 o3.send("test:pass", "<PASSWORD>"); Thread.sleep(100); assertEquals(0, list.size()); // test wrong pass 2 o3.send("test:passwwwwwooooorrrrddd", "<PASSWORD>"); Thread.sleep(100); assertEquals(0, list.size()); // test wrong pass 3 o3.send("test:password1", "<PASSWORD>"); Thread.sleep(100); assertEquals(0, list.size()); // test correct password o3.send("test:password", "<PASSWORD>"); Thread.sleep(100); assertEquals(1, list.size()); o1.disconnect(); o2.disconnect(); } // @Test // public void testConnectToMulticastServer() throws InterruptedException { // OOCSIClient o = new OOCSIClient("test_client_0_multicast"); // // o.connect(); // // assertTrue(o.isConnected()); // // Thread.sleep(500); // // o.disconnect(); // // Thread.sleep(500); // // assertTrue(!o.isConnected()); // } } <|start_filename|>client/src/nl/tue/id/oocsi/client/behavior/state/OOCSIStateMachine.java<|end_filename|> package nl.tue.id.oocsi.client.behavior.state; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import nl.tue.id.oocsi.client.protocol.Handler; /** * A simple finite state machine for use with OOCSI * * API and logic was inspired by the Processing StateMachine library: https://github.com/atduskgreg/Processing-FSM and * the AlphaBeta FSM library for Arduino: http://www.arduino.cc/playground/Code/FiniteStateMachine * * @author matsfunk */ public class OOCSIStateMachine { private String currentState; private Map<String, State> states = new HashMap<String, State>(); private List<Transition> transitions = new LinkedList<Transition>(); /** * add a new state to the state machine by specifying its name, and optional handlers for this new state's enter and * exit events, and the execute handler that will be used while state is on * * @param name * @param enter * @param execute * @param exit * @return the new state */ public State addState(String name, Handler enter, Handler execute, Handler exit) { State state = new State(enter, execute, exit); states.put(name, state); return state; } /** * triggers the execute handler of the current state of this state machine * */ public void execute() { // trigger execute action in current transition if (currentState != null && states.containsKey(currentState)) { states.get(currentState).execute(); } } /** * check if this state machine is currently in the given state * * @param state * @return */ public boolean isInState(String state) { return state != null && state.equals(currentState); } /** * get the current state of this state machine; might be null * * @return */ public String get() { return currentState; } /** * get the state with the given name * * @param name * @return */ public State get(String name) { return states.get(name); } /** * set the state with the given name as the new current state; will trigger enter and exit handlers respectively * * @param newState */ public void set(String newState) { if (checkTransition(newState, newState)) { if (currentState != null && states.containsKey(currentState)) { // trigger exit action states.get(currentState).exit(); } // set the new state currentState = newState; if (currentState != null && states.containsKey(currentState)) { // trigger enter action states.get(currentState).enter(); } } } /** * add a new transition between the source and the destination state * * @param source * @param destination */ public void addTransition(State source, State destination) { transitions.add(new Transition(source, destination)); } /** * check whether the desired transition from source to destination is valid for this state machine; if no * transitions are given, then every transition is valid. * * @param source * @param destination * @return */ private boolean checkTransition(String source, String destination) { State currentState = states.get(source); State newState = states.get(destination); if (!transitions.isEmpty()) { for (Transition transition : transitions) { if (transition.accept(currentState, newState)) { return true; } } return false; } else { // if no transitions are defined, all transitions are possible return true; } } /** * internal state representation * */ public class State { private Handler enterAction; private Handler executeAction; private Handler exitAction; /** * constructor that sets the given handlers for enter, execute, and exit * * @param enter * @param execute * @param exit */ public State(Handler enter, Handler execute, Handler exit) { this.enterAction = enter; this.executeAction = execute; this.exitAction = exit; } /** * trigger the enter handler, if it is given and not null * */ public void enter() { if (enterAction != null) { enterAction.receive("StateMachine", Collections.<String, Object> emptyMap(), System.currentTimeMillis(), "", "enter state"); } } /** * set the enter handler (any time after creation of this state) * * @param handler */ public void setEnter(Handler handler) { enterAction = handler; } /** * trigger the execute handler, if it is given and not null * */ public void execute() { if (executeAction != null) { executeAction.receive("StateMachine", Collections.<String, Object> emptyMap(), System.currentTimeMillis(), "", "execute state"); } } /** * set the execute handler (any time after creation of this state) * * @param handler */ public void setExecute(Handler handler) { executeAction = handler; } /** * trigger the exit handler, if it is given and not null * */ public void exit() { if (exitAction != null) { exitAction.receive("StateMachine", Collections.<String, Object> emptyMap(), System.currentTimeMillis(), "", "exit state"); } } /** * set the exit handler (any time after creation of this state) * * @param handler */ public void setExit(Handler handler) { exitAction = handler; } } /** * internal transition representation * */ public class Transition { private State source; private State destination; /** * constructor that sets the given source and destination state of this new transition * * @param from * @param to */ public Transition(State from, State to) { this.source = from; this.destination = to; } /** * check if the given source and destination state match this transition * * @param from * @param to * @return */ public boolean accept(State from, State to) { return from == source && to == destination; } } } <|start_filename|>server/src/nl/tue/id/oocsi/server/services/AbstractService.java<|end_filename|> package nl.tue.id.oocsi.server.services; import nl.tue.id.oocsi.server.model.Channel.ChangeListener; import nl.tue.id.oocsi.server.model.Client; import nl.tue.id.oocsi.server.model.Server; /** * abstract service component class * * @author matsfunk * */ abstract public class AbstractService { protected final Server server; protected final ChangeListener presence; public AbstractService(Server server) { this.server = server; this.presence = server.getChangeListener(); } abstract public void start(); abstract public void stop(); /** * add a client to the client list in the server * * @param client * @return */ public boolean register(Client client) { return server.addClient(client); } /** * remove a client from the client list in the server * * @param client */ public void unregister(Client client) { presence.leave(client.getName(), client.getName()); server.removeClient(client); } /** * process input from a client and return string response * * @param client * @param inputLine * @return */ public String processInput(SocketClient client, String inputLine) { return server.processInput(client, inputLine); } } <|start_filename|>client/src/nl/tue/id/oocsi/client/protocol/OOCSIMessage.java<|end_filename|> package nl.tue.id.oocsi.client.protocol; import java.util.HashMap; import java.util.Map; import nl.tue.id.oocsi.OOCSIData; import nl.tue.id.oocsi.OOCSIEvent; import nl.tue.id.oocsi.client.OOCSIClient; /** * message helper class for constructing and sending events to OOCSI * * @author matsfunk */ public class OOCSIMessage extends OOCSIEvent implements OOCSIData { protected OOCSIClient oocsi; private boolean isSent = false; /** * create a new message * * @param oocsi * @param channelName */ public OOCSIMessage(OOCSIClient oocsi, String channelName) { super(channelName, new HashMap<String, Object>(), ""); this.oocsi = oocsi; } /** * store data in message * * @param key * @param value * @return */ public OOCSIMessage data(String key, String value) { // store data this.data.put(key, value); return this; } /** * store data in message * * @param key * @param value * @return */ public OOCSIMessage data(String key, boolean value) { // store data this.data.put(key, value); return this; } /** * store data in message * * @param key * @param value * @return */ public OOCSIMessage data(String key, int value) { // store data this.data.put(key, value); return this; } /** * store data in message * * @param key * @param value * @return */ public OOCSIMessage data(String key, float value) { // store data this.data.put(key, value); return this; } /** * store data in message * * @param key * @param value * @return */ public OOCSIMessage data(String key, double value) { // store data this.data.put(key, value); return this; } /** * store data in message * * @param key * @param value * @return */ public OOCSIMessage data(String key, long value) { // store data this.data.put(key, value); return this; } /** * store data in message * * @param key * @param value * @return */ public OOCSIMessage data(String key, Object value) { // store data this.data.put(key, value); return this; } /** * store bulk data in message * * @param bulkData * @return */ public OOCSIMessage data(Map<String, ? extends Object> bulkData) { // store data this.data.putAll(bulkData); return this; } /** * store bulk data in message * * @param bulkData * @return */ public OOCSIMessage data(OOCSIData bulkData) { // store data this.data.putAll(bulkData.internal()); return this; } /** * send message * */ public synchronized void send() { // but send only once if (!isSent) { isSent = true; oocsi.send(channelName, data); } } @Override public Map<String, Object> internal() { return this.data; } } <|start_filename|>server/test/MessageParsingSpeedTest.java<|end_filename|> import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.HashMap; import java.util.Map; import org.junit.Test; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import nl.tue.id.oocsi.client.data.JSONWriter; import nl.tue.id.oocsi.server.protocol.Base64Coder; public class MessageParsingSpeedTest { @SuppressWarnings("unchecked") @Test public void test() throws IOException, ClassNotFoundException { Map<String, Object> messageMap = new HashMap<String, Object>(); messageMap.put("number", 1.0); messageMap.put("bool", false); messageMap.put("hello", "world"); messageMap.put("hello1", "world"); messageMap.put("array", new boolean[] { true, false, true, false }); messageMap.put("array2", new int[] { 1, 2, 3, 4, 5 }); messageMap.put("array3", new String[] { "1", "2", "3" }); long time1 = 0, time2 = 0; { long start = System.currentTimeMillis(); for (int i = 0; i < 1000000; i++) { // to string String msg = new JSONWriter().write(messageMap); // to map JsonObject jo = JsonParser.parseString(msg).getAsJsonObject(); String joStr = jo.toString(); if (!joStr.equals(msg)) { System.out.println("Problem:" + joStr + "\n\n" + msg); } } time1 = System.currentTimeMillis() - start; System.out.println("JSON time: " + time1); } { long start = System.currentTimeMillis(); for (int i = 0; i < 1000000; i++) { // to byte stream final ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); final ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(messageMap); final byte[] rawData = baos.toByteArray(); String data = new String(Base64Coder.encode(rawData)); // to map ByteArrayInputStream bais = new ByteArrayInputStream(Base64Coder.decode(data)); ObjectInputStream ois = new ObjectInputStream(bais); Object outputObject = ois.readObject(); Map<String, Object> parsedMap = (Map<String, Object>) outputObject; parsedMap.get("bool"); } time2 = System.currentTimeMillis() - start; System.out.println("Java time: " + time2); } System.out.println("Speed-up: " + time2 / (double) time1); } } <|start_filename|>client/test/ClientVariableTest.java<|end_filename|> import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import org.junit.Test; import nl.tue.id.oocsi.OOCSIFloat; import nl.tue.id.oocsi.OOCSIInt; import nl.tue.id.oocsi.client.OOCSIClient; import nl.tue.id.oocsi.client.data.OOCSIVariable; public class ClientVariableTest { @Test public void testOOCSIBoolean() throws InterruptedException { OOCSIClient client1 = new OOCSIClient(); client1.connect("localhost", 4444); OOCSIVariable<Boolean> of11 = new OOCSIVariable<>(client1, "localVariableTestChannel", "boolean1"); OOCSIVariable<Boolean> of12 = new OOCSIVariable<>(client1, "localVariableTestChannel", "boolean2"); OOCSIClient client2 = new OOCSIClient(); client2.connect("localhost", 4444); OOCSIVariable<Boolean> of21 = new OOCSIVariable<>(client2, "localVariableTestChannel", "boolean1"); OOCSIVariable<Boolean> of22 = new OOCSIVariable<>(client2, "localVariableTestChannel", "boolean2"); // initially --- assertNull(of21.get()); assertNull(of22.get()); // towards --- of11.set(true); of12.set(false); Thread.sleep(1000); assertEquals(true, of21.get()); assertEquals(false, of22.get()); // back --- of21.set(false); of22.set(true); Thread.sleep(1000); assertEquals(false, of11.get()); assertEquals(true, of12.get()); client1.disconnect(); client2.disconnect(); } @Test public void testOOCSIInt() throws InterruptedException { OOCSIClient client1 = new OOCSIClient(); client1.connect("localhost", 4444); OOCSIVariable<Integer> of11 = new OOCSIInt(client1, "localVariableTestChannel", "integer1"); OOCSIVariable<Integer> of12 = new OOCSIInt(client1, "localVariableTestChannel", "integer2"); OOCSIClient client2 = new OOCSIClient(); client2.connect("localhost", 4444); OOCSIVariable<Integer> of21 = new OOCSIInt(client2, "localVariableTestChannel", "integer1"); OOCSIVariable<Integer> of22 = new OOCSIInt(client2, "localVariableTestChannel", "integer2"); // initially --- // assertNull(of21.get()); // assertNull(of22.get()); // towards --- of11.set(1); of12.set(-1); Thread.sleep(1000); assertEquals(1, (int) of21.get()); assertEquals(-1, (int) of22.get()); // back --- of21.set(-10); of22.set(10); Thread.sleep(1000); assertEquals(-10, (int) of11.get()); assertEquals(10, (int) of12.get()); client1.disconnect(); client2.disconnect(); } @Test public void testOOCSIFloat() throws InterruptedException { OOCSIClient client1 = new OOCSIClient(); client1.connect("localhost", 4444); OOCSIVariable<Float> of11 = new OOCSIFloat(client1, "localVariableTestChannel3", "float1"); OOCSIVariable<Float> of12 = new OOCSIFloat(client1, "localVariableTestChannel3", "float2"); OOCSIClient client2 = new OOCSIClient(); client2.connect("localhost", 4444); OOCSIVariable<Float> of21 = new OOCSIFloat(client2, "localVariableTestChannel3", "float1"); OOCSIVariable<Float> of22 = new OOCSIFloat(client2, "localVariableTestChannel3", "float2"); // initially --- // assertNull(of21.get()); // assertNull(of22.get()); // towards --- of11.set(1.2f); of12.set(-1.2f); Thread.sleep(1000); assertEquals(1.2f, of21.get(), 0); assertEquals(-1.2f, of22.get(), 0); // back --- of21.set(10.2f); of22.set(-10.2f); Thread.sleep(1000); assertEquals(10.2f, of11.get(), 0); assertEquals(-10.2f, of12.get(), 0); client1.disconnect(); client2.disconnect(); } @Test public void testVariableMinMax() throws InterruptedException { OOCSIClient client1 = new OOCSIClient(); client1.connect("localhost", 4444); OOCSIFloat of11 = new OOCSIFloat(client1, "localVariableTestChannel", "float3").min(2f).max(6f); OOCSIFloat of12 = new OOCSIFloat(client1, "localVariableTestChannel", "float4"); OOCSIClient client2 = new OOCSIClient(); client2.connect("localhost", 4444); OOCSIFloat of21 = new OOCSIFloat(client2, "localVariableTestChannel", "float3").min(3f).max(5f); OOCSIFloat of22 = new OOCSIFloat(client2, "localVariableTestChannel", "float4"); // initially --- assertEquals(0f, of21.get(), 0); assertEquals(0f, of22.get(), 0); // towards --- of11.set(1.f); of12.set(-1.2f); Thread.sleep(500); assertEquals(2f, of11.get(), 0); assertEquals(-1.2f, of12.get(), 0); assertEquals(3f, of21.get(), 0); assertEquals(-1.2f, of22.get(), 0); // back --- of21.set(10.2f); Thread.sleep(500); assertEquals(5f, of11.get(), 0); assertEquals(5f, of21.get(), 0); // back --- of21.set(-10.2f); Thread.sleep(500); assertEquals(3f, of11.get(), 0); assertEquals(3f, of21.get(), 0); client1.disconnect(); client2.disconnect(); } @Test public void testVariableRateLimit() throws InterruptedException { OOCSIClient client1 = new OOCSIClient(); client1.connect("localhost", 4444); OOCSIFloat of11 = new OOCSIFloat(client1, "localVariableTestChannel", "float1").limit(5, 1); OOCSIClient client2 = new OOCSIClient(); client2.connect("localhost", 4444); OOCSIFloat of21 = new OOCSIFloat(client2, "localVariableTestChannel", "float1").limit(5, 1); // initially --- assertEquals(0f, of21.get(), 0); // five settings will go through per burst (rate 5/s) of11.set(1.f); Thread.sleep(50); of11.set(2.f); Thread.sleep(50); of11.set(3.f); Thread.sleep(50); of11.set(4.f); Thread.sleep(50); of11.set(5.f); Thread.sleep(50); // this one will fail of11.set(6.f); Thread.sleep(500); assertTrue(6f > of21.get()); client1.disconnect(); client2.disconnect(); } @Test public void testVariableSmooth() throws InterruptedException { OOCSIClient client1 = new OOCSIClient(); client1.connect("localhost", 4444); OOCSIFloat of11 = new OOCSIFloat(client1, "localVariableTestChannel", "float1").smooth(2); OOCSIFloat of12 = new OOCSIFloat(client1, "localVariableTestChannel", "float2"); OOCSIClient client2 = new OOCSIClient(); client2.connect("localhost", 4444); OOCSIFloat of21 = new OOCSIFloat(client2, "localVariableTestChannel", "float1").smooth(2); OOCSIFloat of22 = new OOCSIFloat(client2, "localVariableTestChannel", "float2"); // initially --- assertEquals(0f, of21.get(), 0); assertEquals(0f, of22.get(), 0); // towards --- of11.set(1.f); of11.set(2.f); of12.set(-1.2f); Thread.sleep(500); assertEquals(1.5f, of21.get(), 0); assertEquals(-1.2f, of22.get(), 0); // back --- of21.set(10.2f); of21.set(10.2f); Thread.sleep(500); assertEquals(10.2f, of11.get(), 0); // back --- of21.set(-10.2f); Thread.sleep(100); of21.set(10.2f); Thread.sleep(100); assertEquals(0f, of11.get(), 0); client1.disconnect(); client2.disconnect(); } @Test public void testVariableSmoothSigma() throws InterruptedException { OOCSIClient client1 = new OOCSIClient(); client1.connect("localhost", 4444); OOCSIFloat of11 = new OOCSIFloat(client1, "localVariableTestChannel2", "float1s").smooth(2, 1f); OOCSIFloat of12 = new OOCSIFloat(client1, "localVariableTestChannel2", "float2s").smooth(2, 2f); OOCSIClient client2 = new OOCSIClient(); client2.connect("localhost", 4444); OOCSIFloat of21 = new OOCSIFloat(client2, "localVariableTestChannel2", "float1s").smooth(2, 1f); OOCSIFloat of22 = new OOCSIFloat(client2, "localVariableTestChannel2", "float2s").smooth(2, 2f); // initially --- assertEquals(0f, of21.get(), 0); assertEquals(0f, of22.get(), 0); // towards --- of11.set(1.f); Thread.sleep(50); of11.set(2.f); Thread.sleep(50); of12.set(1.f); Thread.sleep(50); of12.set(2.f); Thread.sleep(500); assertEquals(1.5f, of21.get(), 0); assertEquals(1.5f, of22.get(), 0); // move up a lot --- of21.set(10.2f); Thread.sleep(50); of22.set(10.2f); Thread.sleep(500); // both will move up a bit, but of11 less because of a lower sigma assertEquals(2f, of11.get(), 0.1); assertTrue(of11.get() < of12.get()); // move up --- of21.set(10.2f); of21.set(10.2f); Thread.sleep(500); assertEquals(2.625f, of11.get(), 0.1); // back --- of21.set(-10.2f); of21.set(10.2f); Thread.sleep(500); assertEquals(2.53f, of11.get(), 0.1); client1.disconnect(); client2.disconnect(); } @Test public void testVariableTimeout() throws InterruptedException { OOCSIClient client1 = new OOCSIClient(); client1.connect("localhost", 4444); OOCSIFloat of11 = new OOCSIFloat(client1, "localVariableTestChannel", "float1").reference(4f).timeout(500); OOCSIFloat of12 = new OOCSIFloat(client1, "localVariableTestChannel", "float2").reference(4f).timeout(1000); // initialization should be reference value assertEquals(4f, of11.get(), 0); assertEquals(4f, of12.get(), 0); // setting the variable starts timeout of11.set(0f); of12.set(0f); // new values are directly available assertEquals(0f, of11.get(), 0); assertEquals(0f, of12.get(), 0); // wait more than first variable's timeout Thread.sleep(600); // first variable has switched back assertEquals(4f, of11.get(), 0); assertEquals(0f, of12.get(), 0); // wait for more time Thread.sleep(500); // also second variable has switched back assertEquals(4f, of11.get(), 0); assertEquals(4f, of12.get(), 0); client1.disconnect(); } @Test public void testVariableConnect() throws InterruptedException { OOCSIFloat of11 = new OOCSIFloat(0f, -1); OOCSIFloat of12 = new OOCSIFloat(0f, -1); OOCSIFloat of21 = new OOCSIFloat(0f, -1); of11.connect(of21); of12.connect(of21); // initialization should be reference value assertEquals(0f, of11.get(), 0); assertEquals(0f, of12.get(), 0); assertEquals(0f, of21.get(), 0); // set the variables of11.set(8f); of12.set(8f); // new values are directly available assertEquals(8f, of11.get(), 0); assertEquals(8f, of12.get(), 0); assertEquals(8f, of21.get(), 0); // activate smoothing of21.smooth(2); // send events of11.set(10f); of12.set(20f); // wait for more time Thread.sleep(100); // check end point assertEquals(15f, of21.get(), 0); // send events of11.set(10f); // wait for more time Thread.sleep(100); // check end point assertEquals(15f, of21.get(), 0); // send events of11.set(10f); // wait for more time Thread.sleep(100); // check end point assertEquals(10f, of21.get(), 0); } @Test public void testConnectReconnectVariableSubscriptions() throws InterruptedException { OOCSIClient client1 = new OOCSIClient(); client1.setReconnect(true); client1.connect("localhost", 4444); assertTrue(client1.isConnected()); OOCSIFloat of11 = new OOCSIFloat(client1, "localVariableTestChannel", "float1"); of11.set(10f); // connect second client OOCSIClient client2 = new OOCSIClient(); client2.connect("localhost", 4444); assertTrue(client2.isConnected()); assertEquals(10f, of11.get(), 0); OOCSIFloat of21 = new OOCSIFloat(client2, "localVariableTestChannel", "float1"); Thread.sleep(200); of11.set(11f); Thread.sleep(500); assertEquals(11f, of11.get(), 0); assertEquals(11f, of21.get(), 0); client1.reconnect(); assertTrue(!client1.isConnected()); of21.set(10.6f); Thread.sleep(500); assertEquals(10.6f, of21.get(), 0); assertEquals(11f, of11.get(), 0); assertTrue(client1.isConnected()); of21.set(12.6f); Thread.sleep(500); assertEquals(12.6f, of11.get(), 0); client1.disconnect(); client2.disconnect(); } } <|start_filename|>client/src/nl/tue/id/oocsi/client/services/OOCSICall.java<|end_filename|> package nl.tue.id.oocsi.client.services; import java.util.Map; import java.util.UUID; import nl.tue.id.oocsi.OOCSIEvent; import nl.tue.id.oocsi.client.OOCSIClient; import nl.tue.id.oocsi.client.protocol.OOCSIMessage; /** * call helper class for constructing, sending and receiving (function) calls over OOCSI * * @author matsfunk */ public class OOCSICall extends OOCSIMessage { public static final String MESSAGE_HANDLE = "_MESSAGE_HANDLE"; public static final String MESSAGE_ID = "_MESSAGE_ID"; enum CALL_MODE { call_return, call_multi_return } private String uuid = ""; private long expiration = 0; private int maxResponses = 1; private OOCSIEvent response = null; /** * create a new message to the channel "channelName" * * @param oocsi * @param callName * @param timeoutMS * @param maxResponses */ public OOCSICall(OOCSIClient oocsi, String callName, int timeoutMS, int maxResponses) { this(oocsi, callName, callName, timeoutMS, maxResponses); } /** * create a new message to the channel "channelName" * * @param oocsi * @param channelName * @param callName * @param timeoutMS * @param maxResponses */ public OOCSICall(OOCSIClient oocsi, String channelName, String callName, int timeoutMS, int maxResponses) { super(oocsi, channelName); this.data(OOCSICall.MESSAGE_HANDLE, callName); this.expiration = System.currentTimeMillis() + timeoutMS; this.maxResponses = maxResponses; } /** * return unique id of this OOCSI call * * @return */ public String getId() { return uuid; } /** * add a response to this open call * * @param data */ public void respond(Map<String, Object> data) { response = new OOCSIEvent(super.sender, data, super.channelName); } /** * check whether all values have been filled in for sending the call * * @return */ public boolean canSend() { for (Map.Entry<String, Object> entry : data.entrySet()) { if (entry.getValue() == null) { return false; } } return true; } /** * check whether this call is still not expired or has gotten a response * * @return */ public boolean isValid() { return System.currentTimeMillis() < expiration && !hasResponse(); } /** * check whether this call has gotten a response * * @return */ public boolean hasResponse() { return response != null && 1 <= maxResponses; } /** * retrieve the first response to this call as an OOCSIEvent * * @return */ public OOCSIEvent getFirstResponse() { return response; } /* * (non-Javadoc) * * @see nl.tue.id.oocsi.client.protocol.OOCSIMessage#send() */ @Override public void send() { // intercept to add message id uuid = UUID.randomUUID().toString(); data(OOCSICall.MESSAGE_ID, uuid); // register centrally oocsi.register(this); // submit super.send(); } /** * send message and then wait until either the timeout has passed or at least one response has been recorded * * @return */ public OOCSICall sendAndWait() { send(); waitForResponse(); return this; } /** * send message and then wait until either the timeout given by <code>ms</code> has passed or at least one response * has been recorded * * @param ms * timeout * @return */ public OOCSICall sendAndWait(int ms) { this.expiration = System.currentTimeMillis() + ms; sendAndWait(); return this; } /** * wait until either the timeout has passed or at least one response has been recorded * * @return */ public OOCSICall waitForResponse() { while (isValid()) { try { Thread.sleep(100); } catch (InterruptedException e) { // do nothing } } return this; } /* * (non-Javadoc) * * @see nl.tue.id.oocsi.client.protocol.OOCSIMessage#data(java.lang.String, java.lang.String) */ @Override public OOCSICall data(String key, String value) { return (OOCSICall) super.data(key, value); } /* * (non-Javadoc) * * @see nl.tue.id.oocsi.client.protocol.OOCSIMessage#data(java.lang.String, boolean) */ @Override public OOCSICall data(String key, boolean value) { return (OOCSICall) super.data(key, value); } /* * (non-Javadoc) * * @see nl.tue.id.oocsi.client.protocol.OOCSIMessage#data(java.lang.String, int) */ @Override public OOCSICall data(String key, int value) { return (OOCSICall) super.data(key, value); } /* * (non-Javadoc) * * @see nl.tue.id.oocsi.client.protocol.OOCSIMessage#data(java.lang.String, float) */ @Override public OOCSICall data(String key, float value) { return (OOCSICall) super.data(key, value); } /* * (non-Javadoc) * * @see nl.tue.id.oocsi.client.protocol.OOCSIMessage#data(java.lang.String, double) */ @Override public OOCSICall data(String key, double value) { return (OOCSICall) super.data(key, value); } /* * (non-Javadoc) * * @see nl.tue.id.oocsi.client.protocol.OOCSIMessage#data(java.lang.String, long) */ @Override public OOCSICall data(String key, long value) { return (OOCSICall) super.data(key, value); } /* * (non-Javadoc) * * @see nl.tue.id.oocsi.client.protocol.OOCSIMessage#data(java.lang.String, java.lang.Object) */ @Override public OOCSICall data(String key, Object value) { return (OOCSICall) super.data(key, value); } /* * (non-Javadoc) * * @see nl.tue.id.oocsi.client.protocol.OOCSIMessage#data(java.util.Map) */ @Override public OOCSICall data(Map<String, ? extends Object> bulkData) { return (OOCSICall) super.data(bulkData); } } <|start_filename|>client/src/nl/tue/id/oocsi/client/protocol/OOCSIDataImpl.java<|end_filename|> package nl.tue.id.oocsi.client.protocol; import java.util.HashMap; import java.util.Map; import nl.tue.id.oocsi.OOCSIData; public class OOCSIDataImpl implements OOCSIData { private final Map<String, Object> data = new HashMap<String, Object>(); /** * store data in message * * @param key * @param value * @return */ @Override public OOCSIData data(String key, String value) { // store data this.data.put(key, value); return this; } /** * store data in message * * @param key * @param value * @return */ @Override public OOCSIData data(String key, int value) { // store data this.data.put(key, value); return this; } /** * store data in message * * @param key * @param value * @return */ @Override public OOCSIData data(String key, float value) { // store data this.data.put(key, value); return this; } /** * store data in message * * @param key * @param value * @return */ @Override public OOCSIData data(String key, double value) { // store data this.data.put(key, value); return this; } /** * store data in message * * @param key * @param value * @return */ @Override public OOCSIData data(String key, long value) { // store data this.data.put(key, value); return this; } /** * store data in message * * @param key * @param value * @return */ @Override public OOCSIData data(String key, Object value) { // store data this.data.put(key, value); return this; } /** * store bulk data in message * * @param bulkData * @return */ @Override public OOCSIData data(Map<String, ? extends Object> bulkData) { // store data this.data.putAll(bulkData); return this; } /** * get internal map * * @return */ public Map<String, Object> internal() { return data; } } <|start_filename|>client/src/nl/tue/id/oocsi/OOCSIEvent.java<|end_filename|> package nl.tue.id.oocsi; import java.util.ArrayList; import java.util.Date; import java.util.Map; /** * event class for receiving events from OOCSI * * @author matsfunk */ public class OOCSIEvent { protected String channelName; protected String sender; protected Map<String, Object> data; protected Date timestamp; /** * constructor (implicit timestamp upon creation) * * @param channelName where to? * @param data what data? * @param sender who sends it? */ public OOCSIEvent(String channelName, Map<String, Object> data, String sender) { this(channelName, data, sender, new Date()); } /** * constructor * * @param channelName where to? * @param data what data? * @param sender who sends it? * @param timestamp when? (as UNIX timestamp, long value) */ public OOCSIEvent(String channelName, Map<String, Object> data, String sender, long timestamp) { this(channelName, data, sender, new Date(timestamp)); } /** * constructor * * @param channelName where to? * @param data what data? * @param sender who sends it? * @param timestamp when? (as Date object) */ public OOCSIEvent(String channelName, Map<String, Object> data, String sender, Date timestamp) { this.channelName = channelName; this.data = data; this.sender = sender; this.timestamp = timestamp; } /** * get value for the given key as boolean * * @param key * @param defaultValue * @return */ public boolean getBoolean(String key, boolean defaultValue) { Object result = this.data.get(key); if (result != null) { if (result instanceof Boolean) { return ((Boolean) result).booleanValue(); } else { try { return Boolean.parseBoolean(result.toString()); } catch (NumberFormatException nfe) { return defaultValue; } } } else { return defaultValue; } } /** * get value for the given key as int * * @param key * @param defaultValue * @return */ public int getInt(String key, int defaultValue) { Object result = this.data.get(key); if (result != null) { if (result instanceof Integer) { return ((Integer) result).intValue(); } else { try { return Integer.parseInt(result.toString()); } catch (NumberFormatException nfe) { return defaultValue; } } } else { return defaultValue; } } /** * get value for the given key as long * * @param key * @param defaultValue * @return */ public long getLong(String key, long defaultValue) { Object result = this.data.get(key); if (result != null) { if (result instanceof Long) { return ((Long) result).longValue(); } else { try { return Long.parseLong(result.toString()); } catch (NumberFormatException nfe) { return defaultValue; } } } else { return defaultValue; } } /** * get value for the given key as float * * @param key * @param defaultValue * @return */ public float getFloat(String key, float defaultValue) { Object result = this.data.get(key); if (result != null) { if (result instanceof Float) { return ((Float) result).floatValue(); } else { try { return Float.parseFloat(result.toString()); } catch (NumberFormatException nfe) { return defaultValue; } } } else { return defaultValue; } } /** * get value for the given key as double * * @param key * @param defaultValue * @return */ public double getDouble(String key, double defaultValue) { Object result = this.data.get(key); if (result != null) { if (result instanceof Double) { return ((Double) result).doubleValue(); } else { try { return Double.parseDouble(result.toString()); } catch (NumberFormatException nfe) { return defaultValue; } } } else { return defaultValue; } } /** * get the value for the given key as String * * @param key * @return */ public String getString(String key) { Object result = this.data.get(key); return result != null ? result.toString() : null; } /** * get the value for the given key as String * * @param key * @param defaultValue * @return */ public String getString(String key, String defaultValue) { Object result = this.data.get(key); return result != null ? result.toString() : defaultValue; } //////////////////////////////////////////////////////////////////// /** * get the value for the given key as boolean array (boolean[]) * * @param key * @param defaultValue * @return */ public boolean[] getBooleanArray(String key, boolean[] defaultValue) { try { Object object = getObject(key); if (object instanceof ArrayList) { @SuppressWarnings("unchecked") ArrayList<Boolean> list = (ArrayList<Boolean>) object; boolean[] array = new boolean[list.size()]; for (int i = 0; i < list.size(); i++) { array[i] = list.get(i); } return array; } return (boolean[]) object; } catch (Exception e) { return defaultValue; } } /** * get the value for the given key as int array (int[]) * * @param key * @param defaultValue * @return */ public int[] getIntArray(String key, int[] defaultValue) { try { Object object = getObject(key); if (object instanceof ArrayList) { @SuppressWarnings("unchecked") ArrayList<Double> list = (ArrayList<Double>) object; int[] array = new int[list.size()]; for (int i = 0; i < list.size(); i++) { array[i] = ((Double) list.get(i)).intValue(); } return array; } return (int[]) object; } catch (Exception e) { return defaultValue; } } /** * get the value for the given key as float array (float[]) * * @param key * @param defaultValue * @return */ public float[] getFloatArray(String key, float[] defaultValue) { try { Object object = getObject(key); if (object instanceof ArrayList) { @SuppressWarnings("unchecked") ArrayList<Double> list = (ArrayList<Double>) object; float[] array = new float[list.size()]; for (int i = 0; i < list.size(); i++) { array[i] = ((Double) list.get(i)).floatValue(); } return array; } return (float[]) object; } catch (Exception e) { return defaultValue; } } /** * get the value for the given key as long array (long[]) * * @param key * @param defaultValue * @return */ public long[] getLongArray(String key, long[] defaultValue) { try { Object object = getObject(key); if (object instanceof ArrayList) { @SuppressWarnings("unchecked") ArrayList<Double> list = (ArrayList<Double>) object; long[] array = new long[list.size()]; for (int i = 0; i < list.size(); i++) { array[i] = ((Double) list.get(i)).longValue(); } return array; } return (long[]) object; } catch (Exception e) { return defaultValue; } } /** * get the value for the given key as double array (double[]) * * @param key * @param defaultValue * @return */ public double[] getDoubleArray(String key, double[] defaultValue) { try { Object object = getObject(key); if (object instanceof ArrayList) { @SuppressWarnings("unchecked") ArrayList<Double> list = (ArrayList<Double>) object; double[] array = new double[list.size()]; for (int i = 0; i < list.size(); i++) { array[i] = list.get(i); } return array; } return (double[]) object; } catch (Exception e) { return defaultValue; } } /** * get the value for the given key as String array (String[]) * * @param key * @param defaultValue * @return */ public String[] getStringArray(String key, String[] defaultValue) { try { Object object = getObject(key); if (object instanceof ArrayList) { @SuppressWarnings("unchecked") ArrayList<String> list = (ArrayList<String>) object; String[] array = new String[list.size()]; for (int i = 0; i < list.size(); i++) { array[i] = list.get(i); } return array; } return (String[]) object; } catch (Exception e) { return defaultValue; } } /** * get the array value for the given key as array of type T. note that you need to call this with the type T * specified. * * example: getArray<Float>() * * @param <T> * @param key * @param defaultValue * @return */ @SuppressWarnings("unchecked") public <T> T[] getArray(String key, T[] defaultValue) { try { return (T[]) getObject(key); } catch (Exception e) { return defaultValue; } } //////////////////////////////////////////////////////////////////// /** * get the value for the given key as Object * * @param key * @return */ public Object getObject(String key) { return this.data.get(key); } /** * check if the event contains data with the key * * @param key * @return */ public boolean has(String key) { return this.data.containsKey(key); } /** * retrieve all keys from the event * * @return */ public String[] keys() { return this.data.keySet().toArray(new String[] {}); } /** * get the name or handle of the sender who sent this event * * @return */ public String getSender() { return sender; } /** * get the name of the recipient or channel that this event was sent to * * @return */ public String getRecipient() { return channelName; } /** * get the name of the recipient or channel that this event was sent to * * @return */ public String getChannel() { return channelName; } /** * get timestamp of this event as Date object * * @return */ public Date getTimestamp() { return timestamp; } /** * get timestamp of this event as long value * * @return */ public long getTime() { return timestamp.getTime(); } /** * get a String representation of this event * */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Sender: " + getSender()); sb.append("Recipient: " + getRecipient() + ", "); sb.append("Timestamp: " + getTimestamp() + ", "); sb.append("\n"); for (String key : keys()) { sb.append(key + ": " + getString(key) + ", "); } sb.append("\n"); return sb.toString(); } } <|start_filename|>client/src/nl/tue/id/oocsi/client/protocol/RateLimitedClientEventHandler.java<|end_filename|> package nl.tue.id.oocsi.client.protocol; import java.util.HashMap; import java.util.Map; /** * rate limited event handler for events with structured data that will only let through "rate" events per "second" * secs; this counts for all incoming events per sender which protects against single senders overloading the system * * @author matsfunk */ abstract public class RateLimitedClientEventHandler extends RateLimitedEventHandler { // counter map private Map<String, Integer> counter = new HashMap<String, Integer>(100); /** * creates a rate limited event handler that will at most let through "rate" event per "second" secs * * @param rate * @param seconds */ public RateLimitedClientEventHandler(int rate, int seconds) { super(rate, seconds); } @Override public void receive(String sender, Map<String, Object> data, long timestamp, String channel, final String recipient) { final long currentTimeMillis = System.currentTimeMillis(); // if rate and seconds are invalid if (rate <= 0 || seconds <= 0) { // just forward the event internalReceive(sender, data, timestamp, channel, recipient); } else { // if timeout has passed if (this.timestamp + seconds * 1000l < currentTimeMillis) { this.timestamp = currentTimeMillis; counter.clear(); inc(sender); internalReceive(sender, data, timestamp, channel, recipient); } // if timeout has not passed = rate limit check necessary else { if (inc(sender) <= rate) { internalReceive(sender, data, timestamp, channel, recipient); } else { // rate limit exceeded, no forwarding exceeded(sender, data, timestamp, channel, recipient); } } } } private int inc(String sender) { int count = 1; if (counter.containsKey(sender)) { count += counter.get(sender); } counter.put(sender, count); return count; } } <|start_filename|>client/src/nl/tue/id/oocsi/client/behavior/OOCSIConsensus.java<|end_filename|> package nl.tue.id.oocsi.client.behavior; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import nl.tue.id.oocsi.OOCSIEvent; import nl.tue.id.oocsi.client.OOCSIClient; import nl.tue.id.oocsi.client.protocol.EventHandler; import nl.tue.id.oocsi.client.protocol.Handler; /** * OOCSIConsensus is a system-level primitive that allows for easy consensus between different OOCSI clients on the same * channel. The consensus will be about a single key or data item, for which different options are given to vote for. * This realizes synchronization on data, not time for which we have OOCSISync. * * @author matsfunk */ public class OOCSIConsensus<T> extends OOCSISystemCommunicator<T> { // call constants private static final String CALL = "call"; private static final String VOTE = "vote"; private static final String CONSENSUS = "consensus"; // configuration int timeout; // recording votes Map<String, T> votes = new HashMap<String, T>(); // dynamics T myVote; T consensus; boolean votingDone = true; /** * create a new consensus process * * @param client * @param channelName * @param key * @param timeoutMS */ public OOCSIConsensus(OOCSIClient client, String channelName, String key, int timeoutMS) { this(client, channelName, key, timeoutMS, null); } /** * create a new consensus process with a callback that will be triggered when the consensus is reached * * @param client * @param channelName * @param key * @param timeoutMS * @param handler */ public OOCSIConsensus(OOCSIClient client, String channelName, String key, int timeoutMS, Handler handler) { super(client, channelName + "_" + key + "_consensus", handler); this.timeout = timeoutMS; // first subscribe to sync channel subscribe(new EventHandler() { @Override public void receive(OOCSIEvent event) { if (event.has(CALL)) { // send our my vote message(VOTE, myVote); } else if (event.has(VOTE)) { // record vote try { @SuppressWarnings("unchecked") T vote = (T) event.getObject(VOTE); votes.put(event.getSender(), vote); } catch (ClassCastException e) { // ignore class cast exceptions } } else if (event.has(CONSENSUS)) { // store consensus try { @SuppressWarnings("unchecked") T vote = (T) event.getObject(CONSENSUS); consensus = vote; } catch (ClassCastException e) { // ignore class cast exceptions } } } }); } /** * set my vote for the consensus process * * @param myVote */ public void set(T myVote) { // only do if we are not voting right now if (!myVote.equals(this.myVote)) { // save own vote this.myVote = myVote; // start process start(); } } /** * returns the current consensus value or my last vote; attention: may return null in case no vote was given * * @return */ public T get() { return consensus != null ? consensus : myVote; } /** * returns the current consensus value or the default value if no consensus has been reached yet * * @param defaultValue * @return */ public T get(T defaultValue) { return consensus != null ? consensus : defaultValue; } /** INTERNAL */ /** * start the consensus process * */ private void start() { // only if timeout has passed (throttling) if (!votingDone) { return; } // clear previous votes votes.clear(); votes.put(client.getName(), myVote); // send out values to all others to inform them about the outcome message(CALL); // close voting after timeout has passed new Timer(true).schedule(new TimerTask() { @Override public void run() { votingDone = true; // report back if handler is given triggerHandler(); // compute consensus across votes consensus = getAggregate(votes); // send out values to all others to inform them about the outcome message(CONSENSUS, consensus); } }, timeout); } /** * compute the aggregate of all votes (after all votes have been recorded, the aggregate function is used to compute * a single result value; different implementations might be plugged into this depending on needs) * * @param votes * @return */ protected T getAggregate(Map<String, T> votes) { return getMajorityAggregate(votes); } /** * @param votes * @return */ private T getMajorityAggregate(Map<String, T> votes) { // find consensus in votes Map<T, Integer> counter = new HashMap<T, Integer>(); for (T vote : votes.values()) { if (counter.containsKey(vote)) { counter.put(vote, counter.get(vote) + 1); } else { counter.put(vote, 1); } } Integer[] array = counter.values().toArray(new Integer[] {}); Arrays.sort(array); int mostFreq = array[array.length - 1]; for (Map.Entry<T, Integer> e : counter.entrySet()) { if (e.getValue() == mostFreq) { return e.getKey(); } } return myVote; } public void stop() { client.unsubscribe(channelName); } /** STATIC FACTORY METHODS */ static public OOCSIConsensus<Integer> createIntegerConsensus(OOCSIClient client, String channelName, String key, int timeoutMS) { return createIntegerConsensus(client, channelName, key, timeoutMS, null); } static public OOCSIConsensus<Integer> createIntegerConsensus(OOCSIClient client, String channelName, String key, int timeoutMS, Handler handler) { OOCSIConsensus<Integer> oocsiConsensus = new OOCSIConsensus<Integer>(client, channelName, key, timeoutMS, handler); oocsiConsensus.set(0); return oocsiConsensus; } static public OOCSIConsensus<Integer> createIntegerAvgConsensus(OOCSIClient client, String channelName, String key, int timeoutMS) { return createIntegerAvgConsensus(client, channelName, key, timeoutMS, null); } static public OOCSIConsensus<Integer> createIntegerAvgConsensus(OOCSIClient client, String channelName, String key, int timeoutMS, Handler handler) { OOCSIConsensus<Integer> oocsiConsensus = new OOCSIConsensus<Integer>(client, channelName, key, timeoutMS, handler) { @Override protected Integer getAggregate(Map<String, Integer> votes) { float aggregate = 0; // find consensus in votes for (Integer vote : votes.values()) { if (vote instanceof Number) { aggregate += Float.parseFloat(vote.toString()); } } return (int) (aggregate / votes.size()); } }; oocsiConsensus.set(0); return oocsiConsensus; } static public OOCSIConsensus<Float> createFloatAvgConsensus(OOCSIClient client, String channelName, String key, int timeoutMS) { return createFloatAvgConsensus(client, channelName, key, timeoutMS, null); } static public OOCSIConsensus<Float> createFloatAvgConsensus(OOCSIClient client, String channelName, String key, int timeoutMS, Handler handler) { OOCSIConsensus<Float> oocsiConsensus = new OOCSIConsensus<Float>(client, channelName, key, timeoutMS, handler) { /** * @param votes * @return */ @Override protected Float getAggregate(Map<String, Float> votes) { float aggregate = 0; // find consensus in votes for (Float vote : votes.values()) { if (vote instanceof Number) { aggregate += Float.parseFloat(vote.toString()); } } return aggregate / votes.size(); } }; oocsiConsensus.set(0f); return oocsiConsensus; } static public OOCSIConsensus<String> createStringConsensus(OOCSIClient client, String channelName, String key, int timeoutMS) { OOCSIConsensus<String> oocsiConsensus = new OOCSIConsensus<String>(client, channelName, key, timeoutMS); oocsiConsensus.set(""); return oocsiConsensus; } static public OOCSIConsensus<String> createStringConsensus(OOCSIClient client, String channelName, String key, int timeoutMS, Handler handler) { OOCSIConsensus<String> oocsiConsensus = new OOCSIConsensus<String>(client, channelName, key, timeoutMS, handler); oocsiConsensus.set(""); return oocsiConsensus; } static public OOCSIConsensus<Boolean> createBooleanConsensus(OOCSIClient client, String channelName, String key, int timeoutMS) { return new OOCSIConsensus<Boolean>(client, channelName, key, timeoutMS); } static public OOCSIConsensus<Boolean> createBooleanConsensus(OOCSIClient client, String channelName, String key, int timeoutMS, Handler handler) { return new OOCSIConsensus<Boolean>(client, channelName, key, timeoutMS, handler); } } <|start_filename|>server/src/nl/tue/id/oocsi/server/services/PresenceTracker.java<|end_filename|> package nl.tue.id.oocsi.server.services; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import nl.tue.id.oocsi.server.model.Channel; import nl.tue.id.oocsi.server.model.Channel.ChangeListener; import nl.tue.id.oocsi.server.protocol.Message; public class PresenceTracker implements ChangeListener { private static final String JOIN = "join"; private static final String REFRESH = "refresh"; private static final String LEAVE = "leave"; private static final String TIMEOUT = "timeout"; protected ConcurrentMap<String, Channel> presenceTracking = new ConcurrentHashMap<String, Channel>(); /** * add a listening client <code>subscriber</code> for presence on channel <code>presenceChannelName</code> * * @param presenceChannelName * @param subscriber */ public void add(String presenceChannelName, Channel subscriber) { presenceTracking.putIfAbsent(presenceChannelName, new Channel("presence(" + presenceChannelName + ")", nullListener)); presenceTracking.get(presenceChannelName).addChannel(subscriber); } /** * remove a listening client <code>channel</code> from all presence on any channel it might be subscribed to * * @param channel */ public void remove(Channel channel) { for (Channel c : presenceTracking.values()) { c.removeChannel(channel, true); } } @Override public void created(Channel host) { // tbd. } @Override public void closed(Channel host) { // tbd. } @Override public void join(Channel host, Channel guest) { Channel listeners = presenceTracking.get(host.getName()); if (listeners != null) { if (host != guest) { listeners.send(new Message(host.getName(), "presence(" + host.getName() + ")") .addData("channel", host.getName()).addData(JOIN, guest.getName())); } else { listeners.send(new Message(host.getName(), "presence(" + host.getName() + ")") .addData("client", host.getName()).addData(JOIN, guest.getName())); } } } @Override public void refresh(Channel host, Channel guest) { Channel listeners = presenceTracking.get(host.getName()); if (listeners != null) { if (host != guest) { listeners.send(new Message(host.getName(), "presence(" + host.getName() + ")") .addData("channel", host.getName()).addData(REFRESH, guest.getName())); } else { listeners.send(new Message(host.getName(), "presence(" + host.getName() + ")") .addData("client", host.getName()).addData(REFRESH, guest.getName())); } } } @Override public void leave(String host, String guest) { Channel listeners = presenceTracking.get(host); if (listeners != null) { if (!host.equals(guest)) { listeners.send( new Message(host, "presence(" + host + ")").addData("channel", host).addData(LEAVE, guest)); } else { listeners.send( new Message(host, "presence(" + host + ")").addData("client", guest).addData(LEAVE, guest)); } } } @Override public void timeout(String host, String guest) { Channel listeners = presenceTracking.get(host); if (listeners != null) { if (!host.equals(guest)) { listeners.send( new Message(host, "presence(" + host + ")").addData("channel", host).addData(TIMEOUT, guest)); } else { listeners.send( new Message(host, "presence(" + host + ")").addData("client", guest).addData(TIMEOUT, guest)); } } } /** * listener implementation that will not listen (for special (meta)channels) * */ public final static ChangeListener nullListener = new ChangeListener() { @Override public void created(Channel host) { } @Override public void leave(String host, String guest) { } @Override public void join(Channel host, Channel guest) { } @Override public void refresh(Channel host, Channel guest) { } @Override public void closed(Channel host) { } @Override public void timeout(String host, String guest) { } }; } <|start_filename|>client/src/nl/tue/id/oocsi/client/behavior/OOCSIGather.java<|end_filename|> package nl.tue.id.oocsi.client.behavior; import java.util.HashMap; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import nl.tue.id.oocsi.OOCSIEvent; import nl.tue.id.oocsi.client.OOCSIClient; import nl.tue.id.oocsi.client.protocol.EventHandler; import nl.tue.id.oocsi.client.protocol.Handler; /** * OOCSIGather is a system-level primitive that allows for easy collection of all values that different OOCSI clients * contribute for the same channel. The distribution will be about a single key or data item. This realizes an overview * on data. * * @author matsfunk */ public class OOCSIGather<T> extends OOCSISystemCommunicator<T> { // call constants private static final String CALL = "call"; private static final String VOTE = "vote"; // configuration int timeout; // dynamics T myVote; Map<String, T> votes = new HashMap<String, T>(); boolean votingDone = true; /** * create a new gathering process * * @param client * @param channelName * @param key * @param timeoutMS */ public OOCSIGather(OOCSIClient client, String channelName, String key, int timeoutMS) { this(client, channelName, key, timeoutMS, null); } /** * create a new gathering process with a callback that will be called when the process is done * * @param client * @param channelName * @param key * @param timeoutMS * @param handler */ public OOCSIGather(OOCSIClient client, String channelName, String key, int timeoutMS, Handler handler) { super(client, channelName + "_" + key + "_gather", handler); this.timeout = timeoutMS; // first subscribe to sync channel subscribe(new EventHandler() { @Override public void receive(OOCSIEvent event) { if (event.has(CALL)) { // new gathering, reset all votes votes.clear(); // add my vote if it exists if (myVote != null) { votes.put(OOCSIGather.this.client.getName(), myVote); } // send out my vote message(VOTE, myVote); } else if (event.has(VOTE)) { // record vote an incoming vote try { @SuppressWarnings("unchecked") T vote = (T) event.getObject(VOTE); if (vote != null) { votes.put(event.getSender(), vote); } } catch (ClassCastException e) { // ignore class cast exceptions } } } }); } /** * stop participating in this gathering process * */ public void stop() { client.unsubscribe(this.channelName); } /** * set my vote for the gathering process * * @param myVote */ public void set(T myVote) { // only do if we are not voting right now if (!myVote.equals(this.myVote)) { // save own vote this.myVote = myVote; // start process start(); } } /** * returns the current set of options mapped to their frequency * * @return */ public Map<T, Integer> get() { Map<T, Integer> resultSet = new HashMap<T, Integer>(); for (T t : votes.values()) { if (resultSet.containsKey(t)) { resultSet.put(t, resultSet.get(t) + 1); } else { resultSet.put(t, 1); } } return resultSet; } /** INTERNAL */ /** * start the consensus process * */ private void start() { // only if timeout has passed (throttling) if (!votingDone) { return; } // clear previous votes votes.clear(); // send out values to all others to inform them about the outcome message(CALL); // add my vote internally votes.put(client.getName(), myVote); // directly send my vote, so others know about it as well message(VOTE, myVote); // close voting after timeout has passed new Timer(true).schedule(new TimerTask() { @Override public void run() { votingDone = true; // report back if handler is given triggerHandler(); } }, timeout); } } <|start_filename|>client/src/nl/tue/id/oocsi/OOCSIBoolean.java<|end_filename|> package nl.tue.id.oocsi; import nl.tue.id.oocsi.client.OOCSIClient; import nl.tue.id.oocsi.client.data.OOCSIVariable; /** * OOCSIBoolean is a system-level primitive that allows for automatic synchronizing of local variables (read and write) * with different OOCSI clients on the same channel. This realizes synchronization on a single data variable without * aggregation. * * @author matsfunk * */ public class OOCSIBoolean extends OOCSIVariable<Boolean> { public OOCSIBoolean(OOCSIClient client, String channelName, String key) { super(client, channelName, key); } public OOCSIBoolean(OOCSIClient client, String channelName, String key, boolean referenceValue) { super(client, channelName, key, referenceValue); } public OOCSIBoolean(OOCSIClient client, String channelName, String key, boolean referenceValue, int timeout) { super(client, channelName, key, referenceValue, timeout); } public OOCSIBoolean(boolean referenceValue, int timeout) { super(referenceValue, timeout); } @Override protected Boolean extractValue(OOCSIEvent event, String key) { Object result = event.getObject(key); if (result != null) { if (result instanceof Boolean) { return ((Boolean) result).booleanValue(); } else { try { return Boolean.parseBoolean(result.toString()); } catch (NumberFormatException nfe) { return null; } } } else { return null; } } /** * set the limiting of incoming events in terms of "rate" and "seconds" timeframe; supports chained invocation * * @param rate * @param seconds * @return */ public OOCSIBoolean limit(int rate, int seconds) { super.limit(rate, seconds); return this; } } <|start_filename|>client/test/ClientLoadTest.java<|end_filename|> import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.junit.Test; import nl.tue.id.oocsi.client.OOCSIClient; import nl.tue.id.oocsi.client.protocol.DataHandler; import nl.tue.id.oocsi.client.protocol.OOCSIMessage; public class ClientLoadTest { @Test public void testConnectionToServer() { OOCSIClient o = new OOCSIClient("test_client_connection_to_server"); o.connect("localhost", 4444); assertTrue(o.isConnected()); o.disconnect(); } @Test public void testSendReceive() throws InterruptedException { final List<String> list = new ArrayList<String>(); OOCSIClient o1 = new OOCSIClient("test_client_send_receive_1"); o1.connect("localhost", 4444); assertTrue(o1.isConnected()); o1.subscribe(new DataHandler() { public void receive(String sender, Map<String, Object> data, long timestamp) { list.add(sender); } }); OOCSIClient o2 = new OOCSIClient("test_client_send_receive_2"); o2.connect("localhost", 4444); assertTrue(o2.isConnected()); o2.subscribe(new DataHandler() { public void receive(String sender, Map<String, Object> data, long timestamp) { list.add(sender); } }); for (int i = 0; i < 1000; i++) { o1.send("test_client_send_receive_2", "hello " + i); } Thread.sleep(6000); assertTrue(990 < list.size()); list.clear(); for (int i = 0; i < 1000; i++) { o2.send("test_client_send_receive_1", "hello1"); } Thread.sleep(3000); assertTrue(990 < list.size()); o1.disconnect(); o2.disconnect(); } @Test public void testSendingBigMessages() throws InterruptedException { final List<Object> list = new ArrayList<Object>(); OOCSIClient o1 = new OOCSIClient("test_client_big_message_1"); o1.connect("localhost", 4444); assertTrue(o1.isConnected()); o1.subscribe(new DataHandler() { public void receive(String sender, Map<String, Object> data, long timestamp) { list.add((String) data.get("data")); } }); OOCSIClient o2 = new OOCSIClient("test_client_big_message_2"); o2.connect("localhost", 4444); assertTrue(o2.isConnected()); o2.subscribe(new DataHandler() { public void receive(String sender, Map<String, Object> data, long timestamp) { list.add(data.get("load")); } }); int[][] largePayload = new int[10000][10]; for (int i = 0; i < 10000; i++) { largePayload[i] = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; } new OOCSIMessage(o1, "test_client_big_message_2").data("load", largePayload).send(); Thread.yield(); Thread.sleep(1000); assertEquals(1, list.size()); assertTrue(((ArrayList) list.get(0)).size() == 10000); assertEquals(3l, ((ArrayList) ((ArrayList) list.get(0)).get(0)).get(2)); o1.disconnect(); o2.disconnect(); } // @Test // public void testSendReceive2() throws InterruptedException { // final List<Long> list = new ArrayList<Long>(); // // OOCSI o1 = new OOCSI("test_client_3"); // o1.connect("localhost", 4444); // assertTrue(o1.isConnected()); // o1.subscribe(new DataHandler() { // public void receive(String sender, Map<String, Object> data, // String timestamp) { // list.add((Long) data.get("data")); // } // }); // Map<String, Object> map1 = new HashMap<String, Object>(); // map1.put("data", System.currentTimeMillis()); // // OOCSI o2 = new OOCSI("test_client_4"); // o2.connect("localhost", 4444); // assertTrue(o2.isConnected()); // o2.subscribe(new DataHandler() { // public void receive(String sender, Map<String, Object> data, // String timestamp) { // list.add((Long) data.get("data")); // } // }); // Map<String, Object> map2 = new HashMap<String, Object>(); // map2.put("data", System.currentTimeMillis()); // // o1.send("test_client_3", map1); // Thread.yield(); // Thread.sleep(3000); // // assertEquals(1, list.size()); // assertEquals(list.get(0), map1.get("data")); // // o2.send("test_client_4", map2); // Thread.yield(); // Thread.sleep(3000); // // assertEquals(2, list.size()); // assertEquals(list.get(1), map2.get("data")); // // } } <|start_filename|>client/src/nl/tue/id/oocsi/OOCSIData.java<|end_filename|> package nl.tue.id.oocsi; import java.util.Map; public interface OOCSIData { /** * store data in message * * @param key * @param value * @return */ OOCSIData data(String key, String value); /** * store data in message * * @param key * @param value * @return */ OOCSIData data(String key, int value); /** * store data in message * * @param key * @param value * @return */ OOCSIData data(String key, float value); /** * store data in message * * @param key * @param value * @return */ OOCSIData data(String key, double value); /** * store data in message * * @param key * @param value * @return */ OOCSIData data(String key, long value); /** * store data in message * * @param key * @param value * @return */ OOCSIData data(String key, Object value); /** * store bulk data in message * * @param bulkData * @return */ OOCSIData data(Map<String, ? extends Object> bulkData); /** * return internal representation of the data as a Map<String, Object> * * @return */ Map<String, Object> internal(); } <|start_filename|>client/src/nl/tue/id/oocsi/client/protocol/MultiHandler.java<|end_filename|> package nl.tue.id.oocsi.client.protocol; import java.util.LinkedList; import java.util.List; import java.util.Map; /** * Handler that internally maintains a list of sub-handlers which will be called in FIFO order once this handler is * called; this is very helpful for multiple subscriptions to a channel * * @author matsfunk */ public class MultiHandler extends Handler { private List<Handler> subscribers = new LinkedList<Handler>(); public MultiHandler() { } public MultiHandler(Handler handler) { add(handler); } public void add(Handler handler) { subscribers.add(handler); } public void remove(Handler handler) { subscribers.remove(handler); } public boolean isEmpty() { return subscribers.isEmpty(); } @Override public void receive(String sender, Map<String, Object> data, long timestamp, String channel, String recipient) { for (Handler handler : subscribers) { handler.receive(sender, data, timestamp, channel, recipient); } } } <|start_filename|>client/src/nl/tue/id/oocsi/client/data/JSONReader.java<|end_filename|> package nl.tue.id.oocsi.client.data; import java.math.BigDecimal; import java.math.BigInteger; import java.text.CharacterIterator; import java.text.StringCharacterIterator; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * JSONReader is part of the StringTree library (https://github.com/efficacy/stringtree) * * Apache licence 2.0 http://www.apache.org/licenses/LICENSE-2.0.html * */ public class JSONReader { protected static final Object OBJECT_END = new Object(); protected static final Object ARRAY_END = new Object(); protected static final Object COLON = new Object(); protected static final Object COMMA = new Object(); public static final int FIRST = 0; public static final int CURRENT = 1; public static final int NEXT = 2; protected static Map<Character, Character> escapes = new HashMap<Character, Character>(); static { escapes.put(Character.valueOf('"'), Character.valueOf('"')); escapes.put(Character.valueOf('\\'), Character.valueOf('\\')); escapes.put(Character.valueOf('/'), Character.valueOf('/')); escapes.put(Character.valueOf('b'), Character.valueOf('\b')); escapes.put(Character.valueOf('f'), Character.valueOf('\f')); escapes.put(Character.valueOf('n'), Character.valueOf('\n')); escapes.put(Character.valueOf('r'), Character.valueOf('\r')); escapes.put(Character.valueOf('t'), Character.valueOf('\t')); } protected CharacterIterator it; protected char c; protected Object token; protected StringBuffer buf = new StringBuffer(); public void reset() { it = null; c = 0; token = null; buf.setLength(0); } protected char next() { c = it.next(); return c; } protected void skipWhiteSpace() { while (Character.isWhitespace(c)) { next(); } } public Object read(CharacterIterator ci, int start) { reset(); it = ci; switch (start) { case FIRST: c = it.first(); break; case CURRENT: c = it.current(); break; case NEXT: c = it.next(); break; } return read(); } public Object read(CharacterIterator it) { return read(it, NEXT); } public Object read(String string) { return read(new StringCharacterIterator(string), FIRST); } protected Object read() { skipWhiteSpace(); char ch = c; next(); switch (ch) { case '"': token = string(); break; case '[': token = array(); break; case ']': token = ARRAY_END; break; case ',': token = COMMA; break; case '{': token = object(); break; case '}': token = OBJECT_END; break; case ':': token = COLON; break; case 't': next(); next(); next(); // assumed r-u-e token = Boolean.TRUE; break; case 'f': next(); next(); next(); next(); // assumed a-l-s-e token = Boolean.FALSE; break; case 'n': next(); next(); next(); // assumed u-l-l token = null; break; default: c = it.previous(); if (Character.isDigit(c) || c == '-') { token = number(); } } // System.out.println("token: " + token); // enable this line to see the token stream return token; } protected Object object() { Map<Object, Object> ret = new LinkedHashMap<Object, Object>(); Object key = read(); while (token != OBJECT_END) { read(); // should be a colon if (token != OBJECT_END) { ret.put(key, read()); if (read() == COMMA) { key = read(); } } } return ret; } protected Object array() { List<Object> ret = new ArrayList<Object>(); Object value = read(); while (token != ARRAY_END) { ret.add(value); if (read() == COMMA) { value = read(); } } return ret; } protected Object number() { int length = 0; boolean isFloatingPoint = false; buf.setLength(0); if (c == '-') { add(); } length += addDigits(); if (c == '.') { add(); length += addDigits(); isFloatingPoint = true; } if (c == 'e' || c == 'E') { add(); if (c == '+' || c == '-') { add(); } addDigits(); isFloatingPoint = true; } String s = buf.toString(); return isFloatingPoint ? (length < 17) ? (Object) Double.valueOf(s) : new BigDecimal(s) : (length < 19) ? (Object) Long.valueOf(s) : new BigInteger(s); } protected int addDigits() { int ret; for (ret = 0; Character.isDigit(c); ++ret) { add(); } return ret; } protected Object string() { buf.setLength(0); while (c != '"') { if (c == '\\') { next(); if (c == 'u') { add(unicode()); } else { Object value = escapes.get(Character.valueOf(c)); if (value != null) { add(((Character) value).charValue()); } } } else { add(); } } next(); return buf.toString(); } protected void add(char cc) { buf.append(cc); next(); } protected void add() { add(c); } protected char unicode() { int value = 0; for (int i = 0; i < 4; ++i) { switch (next()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': value = (value << 4) + c - '0'; break; case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': value = (value << 4) + (c - 'a') + 10; break; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': value = (value << 4) + (c - 'A') + 10; break; } } return (char) value; } } <|start_filename|>client/src/nl/tue/id/oocsi/client/behavior/OOCSISystemCommunicator.java<|end_filename|> package nl.tue.id.oocsi.client.behavior; import java.util.Collections; import java.util.HashMap; import java.util.Map; import nl.tue.id.oocsi.OOCSIEvent; import nl.tue.id.oocsi.client.OOCSIClient; import nl.tue.id.oocsi.client.protocol.EventHandler; import nl.tue.id.oocsi.client.protocol.Handler; import nl.tue.id.oocsi.client.protocol.OOCSIMessage; public class OOCSISystemCommunicator<T> { protected static final String HANDLE = "handle"; protected OOCSIClient client; protected String channelName; private Handler handler; private Map<String, SystemFilter<?>> filters = new HashMap<String, SystemFilter<?>>(); public OOCSISystemCommunicator(OOCSIClient client, String channelName) { this(client, channelName, null); } public OOCSISystemCommunicator(OOCSIClient client, String channelName, Handler handler) { this.client = client; this.channelName = channelName; this.handler = handler; } /** * subscribe and inject filter checks * * @param handler */ protected void subscribe(final EventHandler handler) { client.subscribe(channelName, new EventHandler() { @Override public void receive(OOCSIEvent event) { boolean accept = true; for (String key : filters.keySet()) { accept &= filters.get(key).accept(event); if (!accept) { return; } } if (accept) { handler.receive(event); } } }); } protected void message(String command, T data) { if (client != null) { message().data(command, data).send(); } } protected void message(String command) { if (client != null) { message().data(command, "").send(); } } protected OOCSIMessage message() { if (client != null) { OOCSIMessage oocsiMessage = new OOCSIMessage(client, channelName).data(HANDLE, getHandle()); for (String filterKey : filters.keySet()) { oocsiMessage.data(filterKey, filters.get(filterKey)); } return oocsiMessage; } return null; } public void addFilter(String dataKey, SystemFilter<?> filter) { filters.put(dataKey, filter); } public void updateFilter(String dataKey, Object value) { filters.get(dataKey).value(value); } /** * returns the unique handle for this object * * @return */ protected String getHandle() { return client.getName() + "_" + OOCSISystemCommunicator.this.hashCode(); } protected void triggerHandler() { if (handler != null) { handler.receive(channelName, Collections.<String, Object> emptyMap(), System.currentTimeMillis(), channelName, client.getName()); } } abstract public class SystemFilter<K> { K value; public abstract boolean accept(OOCSIEvent event); @SuppressWarnings("unchecked") public void value(Object value) { this.value = (K) value; } public K value() { return value; } } } <|start_filename|>server/test/ClientSignoffTest.java<|end_filename|> import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import java.io.IOException; import java.util.concurrent.CountDownLatch; import org.junit.Test; import nl.tue.id.oocsi.client.OOCSIClient; import nl.tue.id.oocsi.server.OOCSIServer; public class ClientSignoffTest { CountDownLatch cdl; OOCSIServer server; @Test public void testMultiClientSignOff() throws InterruptedException, IOException { cdl = new CountDownLatch(100); server = new OOCSIServer(4444, 102, false); assertNotEquals(null, server); // start clients that simply sign on and then off after some time for (int i = 0; i < 100; i++) { new Thread(new Runnable() { @Override public void run() { try { String clientName = "clienttest__" + "__" + System.currentTimeMillis(); OOCSIClient client = new OOCSIClient(clientName); if (client.connect("localhost", 4444)) { try { Thread.sleep(2000); } catch (InterruptedException e) { } client.kill(); } } catch (Exception e) { } cdl.countDown(); } }).start(); Thread.sleep(20); } cdl.await(); assertNotEquals(null, server); assertEquals(server.getClientList(), ""); } } <|start_filename|>server/test/ServerCommandLineParsing.java<|end_filename|> import static org.junit.Assert.assertEquals; import nl.tue.id.oocsi.server.OOCSIServer; import org.junit.Test; public class ServerCommandLineParsing { @Test public void testCommandLineParsing() { OOCSIServer os = OOCSIServer.getInstance(); os.port = 0; os.parseCommandlineArgs("-port 4445".split(" ")); assertEquals(os.port, 4445); os.setMaxClients(0); os.parseCommandlineArgs("-clients 24".split(" ")); assertEquals(os.getMaxClients(), 24); os.isLogging = false; assertEquals(os.isLogging, false); os.parseCommandlineArgs("-logging".split(" ")); assertEquals(os.isLogging, true); os.port = 0; os.setMaxClients(0); os.parseCommandlineArgs("-port 4446 -clients 26".split(" ")); assertEquals(os.port, 4446); assertEquals(os.getMaxClients(), 26); os.port = 0; os.setMaxClients(0); os.parseCommandlineArgs("-clients 27 -port 4447".split(" ")); assertEquals(os.port, 4447); assertEquals(os.getMaxClients(), 27); os.port = 0; os.setMaxClients(0); os.isLogging = false; os.parseCommandlineArgs("-port 4446 -logging -clients 26".split(" ")); assertEquals(os.port, 4446); assertEquals(os.getMaxClients(), 26); assertEquals(os.isLogging, true); os.port = 0; os.setMaxClients(0); os.isLogging = false; os.parseCommandlineArgs("-clients 27 -port 4447 -logging".split(" ")); assertEquals(os.port, 4447); assertEquals(os.getMaxClients(), 27); assertEquals(os.isLogging, true); } } <|start_filename|>client/src/nl/tue/id/oocsi/OOCSILong.java<|end_filename|> package nl.tue.id.oocsi; import nl.tue.id.oocsi.client.OOCSIClient; import nl.tue.id.oocsi.client.data.OOCSIVariable; /** * OOCSILong is a system-level primitive that allows for automatic synchronizing of local variables (read and write) * with different OOCSI clients on the same channel. This realizes synchronization on a single data variable without * aggregation. * * @author matsfunk * */ public class OOCSILong extends OOCSIVariable<Long> { public OOCSILong(OOCSIClient client, String channelName, String key) { super(client, channelName, key); } public OOCSILong(OOCSIClient client, String channelName, String key, long referenceValue) { super(client, channelName, key, referenceValue); } public OOCSILong(OOCSIClient client, String channelName, String key, long referenceValue, int timeout) { super(client, channelName, key, referenceValue, timeout); } public OOCSILong(long referenceValue, int timeout) { super(referenceValue, timeout); } /* * (non-Javadoc) * * @see nl.tue.id.oocsi.client.data.OOCSIVariable#get() */ @Override public Long get() { if (super.get() == null) { return 0l; } return super.get(); } @Override protected Long extractValue(OOCSIEvent event, String key) { long longValue = event.getLong(key, Long.MIN_VALUE); return longValue != Long.MIN_VALUE ? longValue : null; } /* * (non-Javadoc) * * @see nl.tue.id.oocsi.client.data.OOCSIVariable#filter(java.lang.Object) */ @Override protected Long filter(Long var) { // check boundaries if (min != null && var < min) { var = min; } else if (max != null && var > max) { var = max; } // check mean and sigma if (sigma != null && mean != null) { // return null if value outside sigma deviation from mean if ((double) Math.abs(mean - var) > sigma) { var = (long) (mean - var > 0 ? mean - sigma / (float) values.size() : mean + sigma / (float) values.size()); } } // return filtered value return super.filter(var); } /* * (non-Javadoc) * * @see nl.tue.id.oocsi.client.data.OOCSIVariable#adapt(java.lang.Object) */ @Override protected Long adapt(Long var) { // history processing? if (windowLength > 0 && values != null && values.size() > 0) { // compute and store mean long sum = 0; for (Long v : values) { sum += v; } mean = (long) (sum / (float) values.size()); return mean; } else { return var; } } /** * set the reference value (also possible during operation); supports chained invocation * * @param reference * @return */ @Override public OOCSILong reference(Long reference) { return (OOCSILong) super.reference(reference); } /** * set the timeout in milliseconds (also possible during operation); supports chained invocation * * @param timeoutMS * @return */ @Override public OOCSILong timeout(int timeoutMS) { return (OOCSILong) super.timeout(timeoutMS); } /** * set the limiting of incoming events in terms of "rate" and "seconds" timeframe; supports chained invocation * * @param rate * @param seconds * @return */ public OOCSILong limit(int rate, int seconds) { super.limit(rate, seconds); return this; } /** * set the minimum value for (lower-)bounded variable (also possible during operation); supports chained invocation * * @param min * @return */ @Override public OOCSILong min(Long min) { return (OOCSILong) super.min(min); } /** * set the maximum value for (upper-)bounded variable (also possible during operation); supports chained invocation * * @param max * @return */ @Override public OOCSILong max(Long max) { return (OOCSILong) super.max(max); } /** * set the length of the smoothing window, i.e., the buffer of historical values of this variable (also possible * during operation, however, this will reset the buffer); supports chained invocation * * @param windowLength * @return */ @Override public OOCSILong smooth(int windowLength) { return (OOCSILong) super.smooth(windowLength); } /** * set the length of the smoothing window, i.e., the buffer of historical values of this variable (also possible * during operation, however, this will reset the buffer); supports chained invocation. the parameter sigma sets the * upper bound for the standard deviation protected variable * * @param windowLength * @param sigma * @return */ @Override public OOCSILong smooth(int windowLength, Long sigma) { return (OOCSILong) super.smooth(windowLength, sigma); } /** * creates a periodic feedback loop that feed either the last input value or the reference value into the variable * (locally). If there is no reference value set, the former applies. The period is given in milliseconds. * * @param periodMS * @return */ @Override public OOCSILong generator(long periodMS) { return (OOCSILong) super.generator(periodMS); } /** * creates a periodic feedback loop that feed either the last input value or the reference value into the variable * (locally). If there is no reference value set, the former applies. The period is given in milliseconds. In * addition, the new value of the variable is sent out to the channel "outputChannel" with the given key "outputKey" * * @param periodMS * @param outputChannel * @param outputKey * @return */ @Override public OOCSILong generator(long periodMS, String outputChannel, String outputKey) { return (OOCSILong) super.generator(periodMS, outputChannel, outputKey); } /* * (non-Javadoc) * * @see nl.tue.id.oocsi.client.data.OOCSIVariable#connect(nl.tue.id.oocsi.client.data.OOCSIVariable) */ @Override public void connect(OOCSIVariable<Long> forward) { super.connect(forward); } /* * (non-Javadoc) * * @see nl.tue.id.oocsi.client.data.OOCSIVariable#disconnect(nl.tue.id.oocsi.client.data.OOCSIVariable) */ @Override public void disconnect(OOCSIVariable<Long> forward) { super.disconnect(forward); } } <|start_filename|>client/src/nl/tue/id/oocsi/client/data/OOCSIVariable.java<|end_filename|> package nl.tue.id.oocsi.client.data; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ArrayBlockingQueue; import nl.tue.id.oocsi.OOCSIEvent; import nl.tue.id.oocsi.client.OOCSIClient; import nl.tue.id.oocsi.client.behavior.OOCSISystemCommunicator; import nl.tue.id.oocsi.client.protocol.OOCSIMessage; /** * OOCSIVariable is a system-level primitive that allows for automatic synchronizing of local variables (read and write) * with different OOCSI clients on the same channel. This realizes synchronization on a single data variable without * aggregation. OOCSIVariable is a parameterized class, that means, once the data type is set it can reliably used in * reading and writing. * * OOCSIVariable supports internal aggregation in the form of smoothing (use smooth(n) for n sample window length). The * range of the variable can be restricted by using an upper or lower bound or both. When smoothing, a mean-deviation * parameter sigma can be added to filter out outliers in the input data. * * @author matsfunk * * @param <T> */ public class OOCSIVariable<T> extends OOCSISystemCommunicator<T> { // internal representation of the variable private T internalVariable; // key of internal variable in the OOCSI network private String key; // reference or default value for variable in case nothing has been received for "timeout" milliseconds private T internalReference; // amount of milliseconds to wait until the reference value is applied to "internalVariable" private int timeout; // last time the variable was updated private long lastWrite = System.currentTimeMillis(); // bounded variable: min value protected T min = null; // bounded variable: max value protected T max = null; // protected variable: standard deviation upper bound protected T sigma = null; // protected variable: mean protected T mean = null; // historical window of past variable values protected ArrayBlockingQueue<T> values = null; // length of historical window of past variable values protected int windowLength = 0; // preserve the last input protected T lastInput = null; // list of connected variables protected List<OOCSIVariable<T>> forwarders = new LinkedList<OOCSIVariable<T>>(); private nl.tue.id.oocsi.client.protocol.RateLimitedEventHandler eventHandler; /** * Constructor for a simple OOCSI variable to sync on a given channel and key * * @param client * @param channelName * @param key */ public OOCSIVariable(OOCSIClient client, String channelName, String key) { this(client, channelName, key, null, -1); } /** * Constructor for a simple OOCSI variable to sync on a given channel and key, in case no value can be retrieved * from the channel a reference value is provided which will be set automatically after a timeout of 2000 ms (2 * seconds) * * @param client * @param channelName * @param key * @param referenceValue */ public OOCSIVariable(OOCSIClient client, String channelName, String key, T referenceValue) { this(client, channelName, key, referenceValue, -1); } /** * Constructor for a simple OOCSI variable to sync on a given channel and key, in case no value can be retrieved * from the channel a reference value is provided which will be set automatically after the given timeout * * @param client * @param channelName * @param key * @param referenceValue * @param timeout */ public OOCSIVariable(OOCSIClient client, String channelName, String key, T referenceValue, int timeout) { super(client, channelName); this.key = key; this.internalVariable = referenceValue; this.internalReference = referenceValue; this.timeout = timeout; this.eventHandler = new nl.tue.id.oocsi.client.protocol.RateLimitedEventHandler(0, 0) { @Override public void receive(OOCSIEvent event) { T object = extractValue(event, OOCSIVariable.this.key); if (object != null) { try { // set variable from the network OOCSIVariable.this.internalSet(object); // update timeout lastWrite = System.currentTimeMillis(); remoteUpdate(); } catch (Exception e) { // do nothing e.printStackTrace(); } } } @Override public void exceeded(String sender, Map<String, Object> data, long timestamp, String channel, String recipient) { System.out.println(data.toString()); } }; // subscribe client.subscribe(channelName, eventHandler); } /** * Constructor for a local OOCSI variable that does not sync on a given channel and key, a reference value is * provided which will be set automatically after the given timeout * * @param referenceValue * @param timeout */ public OOCSIVariable(T referenceValue, int timeout) { super(null, null); this.internalVariable = referenceValue; this.internalReference = referenceValue; this.timeout = timeout; } /** * retrieve the current value of the variable (will check for expiration if a timeout is given; in this case the * reference value is set) * * @return */ public T get() { // check if current value is outdated and should be set to reference value if (timeout > -1 && internalReference != null && lastWrite < System.currentTimeMillis() - timeout) { internalVariable = internalReference; } return internalVariable; } /** * set the variable and, if successful, let the channel know * * @param var */ public void set(T var) { if (internalSet(var)) { if (values != null && values.size() > 0) { message(key, last()); } else { message(key, internalVariable); } localUpdate(); for (OOCSIVariable<T> v : forwarders) { v.set(this.get()); } } } /** * update the setting of the variable, but only if it is different from the reference value; and then let the * channel know * */ public void set() { if (this.internalVariable != this.internalReference) { message(key, internalVariable); } } /** * safely extract the message value in the right type * * @param event * @return */ @SuppressWarnings("unchecked") protected T extractValue(OOCSIEvent event, String key) { return (T) event.getObject(key); } /** * internally set the variable (return true), except in case it is filtered (return false) * * @param var * @return */ private boolean internalSet(T var) { lastInput = var; // filter dynamically var = filter(var); if (var == null) { return false; } lastInput = var; // add to history if (values != null) { // make space in history while (values.remainingCapacity() == 0) { values.poll(); } // add to history values.offer(var); } // adapt and send out internalVariable = adapt(var); return true; } /** * notifier for a variable update; override to get notified about this * */ public void update() { // do nothing, only for use in sub-classes that override this method } /** * notifier for a remote variable update (from another client); override to get notified about this * */ public void remoteUpdate() { update(); } /** * notifier for a local variable update; override to get notified about this * */ public void localUpdate() { update(); } /** * filter the newly entered variable setting (if variable type is numerical, this could be a min/max filter and * additional filtering based on the standard deviation, or a different filter) * * @param var * @return */ protected T filter(T var) { return var; } /** * adaptation of the variable based on the recent history (values) and the newly entered variable setting * * @param var * @return */ protected T adapt(T var) { return var; } /** * retrieve the reference value * * @return */ public T reference() { return internalReference; } /** * retrieve the number of milliseconds that have passed since the last setting of the variable by another OOCSI * client * * @return */ public long fresh() { return System.currentTimeMillis() - lastWrite; } /** * retrieve the last input value * * @return */ public T last() { return lastInput; } /** * set the reference value (also possible during operation); supports chained invocation * * @param reference * @return */ public OOCSIVariable<T> reference(T reference) { this.internalReference = reference; if (this.internalVariable == null) { this.internalVariable = reference; } return this; } /** * set the timeout in milliseconds (also possible during operation); supports chained invocation * * @param timeoutMS * @return */ public OOCSIVariable<T> timeout(int timeoutMS) { this.timeout = timeoutMS; return this; } /** * set the limiting of incoming events in terms of "rate" and "seconds" timeframe; supports chained invocation * * @param rate * @param seconds * @return */ public OOCSIVariable<T> limit(int rate, int seconds) { eventHandler.limit(rate, seconds); return this; } /** * set the minimum value for (lower-)bounded variable (also possible during operation); supports chained invocation * * @param min * @return */ public OOCSIVariable<T> min(T min) { this.min = min; return this; } /** * set the maximum value for (upper-)bounded variable (also possible during operation); supports chained invocation * * @param max * @return */ public OOCSIVariable<T> max(T max) { this.max = max; return this; } /** * set the length of the smoothing window, i.e., the buffer of historical values of this variable (also possible * during operation, however, this will reset the buffer); supports chained invocation * * @param windowLength * @return */ public OOCSIVariable<T> smooth(int windowLength) { return this.smooth(windowLength, null); } /** * set the length of the smoothing window, i.e., the buffer of historical values of this variable (also possible * during operation, however, this will reset the buffer); supports chained invocation. the parameter sigma sets the * upper bound for the standard deviation protected variable * * @param windowLength * @param sigma * @return */ public OOCSIVariable<T> smooth(int windowLength, T sigma) { this.windowLength = windowLength; this.sigma = sigma; this.values = new ArrayBlockingQueue<T>(windowLength); return this; } /** * creates a periodic feedback loop that feed either the last input value or the reference value into the variable * (locally). If there is no reference value set, the former applies. The period is given in milliseconds. * * @param periodMS * @return */ public OOCSIVariable<T> generator(long periodMS) { return this.generator(periodMS, null, null); } /** * creates a periodic feedback loop that feed either the last input value or the reference value into the variable * (locally). If there is no reference value set, the former applies. The period is given in milliseconds. In * addition, the new value of the variable is sent out to the channel "outputChannel" with the given key "outputKey" * * @param periodMS * @param outputChannel * @param outputKey * @return */ public OOCSIVariable<T> generator(long periodMS, final String outputChannel, final String outputKey) { // start time to update this flow new Timer(true).schedule(new TimerTask() { public void run() { // update variable if (internalReference != null) { set(internalReference); } else if (last() != null) { set(last()); } // send out if (outputChannel != null && outputChannel.trim().length() > 0 && outputKey != null && outputKey.trim().length() > 0) new OOCSIMessage(client, outputChannel).data(outputKey, get()).send(); } }, periodMS, periodMS); return this; } /** * connect the given variable to this variable, so whenever this variable is set, the connected given variable will * be set as well * * @param forward */ public void connect(OOCSIVariable<T> forward) { forwarders.add(forward); } /** * disconnect the given variable from this variable; no more events will be sent * * @param forward */ public void disconnect(OOCSIVariable<T> forward) { forwarders.remove(forward); } } <|start_filename|>client/src/nl/tue/id/oocsi/OOCSIDouble.java<|end_filename|> package nl.tue.id.oocsi; import nl.tue.id.oocsi.client.OOCSIClient; import nl.tue.id.oocsi.client.data.OOCSIVariable; /** * OOCSIDouble is a system-level primitive that allows for automatic synchronizing of local variables (read and write) * with different OOCSI clients on the same channel. This realizes synchronization on a single data variable without * aggregation. * * @author matsfunk * */ public class OOCSIDouble extends OOCSIVariable<Double> { public OOCSIDouble(OOCSIClient client, String channelName, String key) { super(client, channelName, key); } public OOCSIDouble(OOCSIClient client, String channelName, String key, double referenceValue) { super(client, channelName, key, referenceValue); } public OOCSIDouble(OOCSIClient client, String channelName, String key, double referenceValue, int timeout) { super(client, channelName, key, referenceValue, timeout); } public OOCSIDouble(double referenceValue, int timeout) { super(referenceValue, timeout); } /* * (non-Javadoc) * * @see nl.tue.id.oocsi.client.data.OOCSIVariable#get() */ @Override public Double get() { if (super.get() == null) { return 0d; } return super.get(); } @Override protected Double extractValue(OOCSIEvent event, String key) { double doubleValue = event.getDouble(key, Double.MIN_VALUE); return doubleValue != Double.MIN_VALUE ? doubleValue : null; } /* * (non-Javadoc) * * @see nl.tue.id.oocsi.client.data.OOCSIVariable#filter(java.lang.Object) */ @Override protected Double filter(Double var) { // check boundaries if (min != null && var < min) { var = min; } else if (max != null && var > max) { var = max; } // check mean and sigma if (sigma != null && mean != null) { // return null if value outside sigma deviation from mean if (Math.abs(mean - var) > sigma) { var = mean - var > 0 ? mean - sigma / (float) values.size() : mean + sigma / (float) values.size(); } } // return filtered value return super.filter(var); } /* * (non-Javadoc) * * @see nl.tue.id.oocsi.client.data.OOCSIVariable#adapt(java.lang.Object) */ @Override protected Double adapt(Double var) { // history processing? if (windowLength > 0 && values != null && values.size() > 0) { // compute and store mean double sum = 0; for (Double v : values) { sum += v; } mean = (double) (sum / (float) values.size()); return mean; } else { return var; } } /** * set the reference value (also possible during operation); supports chained invocation * * @param reference * @return */ @Override public OOCSIDouble reference(Double reference) { return (OOCSIDouble) super.reference(reference); } /** * set the timeout in milliseconds (also possible during operation); supports chained invocation * * @param timeoutMS * @return */ @Override public OOCSIDouble timeout(int timeoutMS) { return (OOCSIDouble) super.timeout(timeoutMS); } /** * set the limiting of incoming events in terms of "rate" and "seconds" timeframe; supports chained invocation * * @param rate * @param seconds * @return */ public OOCSIDouble limit(int rate, int seconds) { super.limit(rate, seconds); return this; } /** * set the minimum value for (lower-)bounded variable (also possible during operation); supports chained invocation * * @param min * @return */ @Override public OOCSIDouble min(Double min) { return (OOCSIDouble) super.min(min); } /** * set the maximum value for (upper-)bounded variable (also possible during operation); supports chained invocation * * @param max * @return */ @Override public OOCSIDouble max(Double max) { return (OOCSIDouble) super.max(max); } /** * set the length of the smoothing window, i.e., the buffer of historical values of this variable (also possible * during operation, however, this will reset the buffer); supports chained invocation * * @param windowLength * @return */ @Override public OOCSIDouble smooth(int windowLength) { return (OOCSIDouble) super.smooth(windowLength); } /** * set the length of the smoothing window, i.e., the buffer of historical values of this variable (also possible * during operation, however, this will reset the buffer); supports chained invocation. the parameter sigma sets the * upper bound for the standard deviation protected variable * * @param windowLength * @param sigma * @return */ @Override public OOCSIDouble smooth(int windowLength, Double sigma) { return (OOCSIDouble) super.smooth(windowLength, sigma); } /** * creates a periodic feedback loop that feed either the last input value or the reference value into the variable * (locally). If there is no reference value set, the former applies. The period is given in milliseconds. * * @param periodMS * @return */ @Override public OOCSIDouble generator(long periodMS) { return (OOCSIDouble) super.generator(periodMS); } /** * creates a periodic feedback loop that feed either the last input value or the reference value into the variable * (locally). If there is no reference value set, the former applies. The period is given in milliseconds. In * addition, the new value of the variable is sent out to the channel "outputChannel" with the given key "outputKey" * * @param periodMS * @param outputChannel * @param outputKey * @return */ @Override public OOCSIDouble generator(long periodMS, String outputChannel, String outputKey) { return (OOCSIDouble) super.generator(periodMS, outputChannel, outputKey); } /* * (non-Javadoc) * * @see nl.tue.id.oocsi.client.data.OOCSIVariable#connect(nl.tue.id.oocsi.client.data.OOCSIVariable) */ @Override public void connect(OOCSIVariable<Double> forward) { super.connect(forward); } /* * (non-Javadoc) * * @see nl.tue.id.oocsi.client.data.OOCSIVariable#disconnect(nl.tue.id.oocsi.client.data.OOCSIVariable) */ @Override public void disconnect(OOCSIVariable<Double> forward) { super.disconnect(forward); } } <|start_filename|>client/test/ClientCallTest.java<|end_filename|> import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Test; import nl.tue.id.oocsi.OOCSIData; import nl.tue.id.oocsi.OOCSIEvent; import nl.tue.id.oocsi.client.OOCSIClient; import nl.tue.id.oocsi.client.services.OOCSICall; import nl.tue.id.oocsi.client.services.Responder; import nl.tue.id.oocsi.client.services.Service; import nl.tue.id.oocsi.client.services.Service.ServiceField; import nl.tue.id.oocsi.client.services.Service.ServiceMethod; /** * call / responder test cases * * @author matsfunk */ public class ClientCallTest { @Test public void testServiceInstantiation() throws InterruptedException { Service s = new Service(); s.name = "addition"; s.category = "Math"; s.uuid = "as8ca08sc98asc98asc8asc"; ServiceMethod serviceMethod = s.newServiceMethod(); serviceMethod.handle = "addnineteen2"; serviceMethod.name = "addnineteen2"; serviceMethod.input.add(new ServiceField<Integer>("value")); serviceMethod.output.add(new ServiceField<Integer>("additionOutput")); s.methods.add(serviceMethod); // register all methods of a service // for (ServiceMethod method : s.methods) { // method.responder(); // } // hand made responder OOCSIClient o1 = new OOCSIClient("pingS"); o1.connect("localhost", 4444); assertTrue(o1.isConnected()); final ServiceMethod serviceMethod2 = s.methods.get(0); serviceMethod2.registerResponder(o1, new Responder() { public void respond(OOCSIEvent event, OOCSIData response) { int value = event.getInt(serviceMethod2.input.get(0).name, 0); value += 29; response.data(serviceMethod2.output.get(0).name, value); } }); OOCSIClient o2 = new OOCSIClient("pongS"); o2.connect("localhost", 4444); assertTrue(o2.isConnected()); { OOCSICall call = serviceMethod2.buildCall(o2, 100, 1); assertTrue(!call.canSend()); } { OOCSICall call = serviceMethod2.buildCall(o2, 1000, 1).data("value", 1); assertTrue(call.canSend()); call.sendAndWait(); assertTrue(call.hasResponse()); if (call.hasResponse()) { int responseValue = call.getFirstResponse().getInt(serviceMethod2.output.get(0).name, 0/* * (Integer) serviceMethod2 .output .get(0 ).defaultValue */); assertEquals(30, responseValue); } } o1.disconnect(); o2.disconnect(); } @Test public void testResponse() throws InterruptedException { OOCSIClient o1 = new OOCSIClient("pingResponse"); o1.connect("localhost", 4444); assertTrue(o1.isConnected()); OOCSIClient o2 = new OOCSIClient("pongResponse"); o2.connect("localhost", 4444); assertTrue(o2.isConnected()); o2.register("addnineteen", new Responder(o2) { @Override public void respond(OOCSIEvent event, OOCSIData response) { int pp = event.getInt("addnineteen", -1); response.data("addedthat", pp + 19); } }); { OOCSICall call = new OOCSICall(o1, "addnineteen", 500, 1).data("addnineteen", 1); call.sendAndWait(); assertTrue(call.hasResponse()); OOCSIEvent response = call.getFirstResponse(); assertEquals(20, response.getInt("addedthat", -1)); } { OOCSICall call = new OOCSICall(o1, "addnineteen", 500, 1).data("addnineteen", 100); call.sendAndWait(); assertTrue(call.hasResponse()); OOCSIEvent response = call.getFirstResponse(); assertEquals(119, response.getInt("addedthat", -1)); } o1.disconnect(); o2.disconnect(); } @Test public void testResponseChannel() throws InterruptedException { OOCSIClient o1 = new OOCSIClient("pingResponse2"); o1.connect("localhost", 4444); assertTrue(o1.isConnected()); OOCSIClient o2 = new OOCSIClient("pongResponse2"); o2.connect("localhost", 4444); assertTrue(o2.isConnected()); o2.register("addnineteen", new Responder(o2) { @Override public void respond(OOCSIEvent event, OOCSIData response) { int pp = event.getInt("addnineteen", -1); response.data("addedthat", pp + 19); } }); { OOCSICall call = new OOCSICall(o1, "pongResponse2", "addnineteen", 500, 1).data("addnineteen", 1); call.sendAndWait(); assertTrue(call.hasResponse()); OOCSIEvent response = call.getFirstResponse(); assertEquals(20, response.getInt("addedthat", -1)); } { OOCSICall call = new OOCSICall(o1, "pongResponse2", "addnineteen", 500, 1).data("addnineteen", 100); call.sendAndWait(); assertTrue(call.hasResponse()); OOCSIEvent response = call.getFirstResponse(); assertEquals(119, response.getInt("addedthat", -1)); } o1.disconnect(); o2.disconnect(); } @Test public void testResponderOverlap() throws InterruptedException { OOCSIClient o1 = new OOCSIClient("pingR"); o1.connect("localhost", 4444); assertTrue(o1.isConnected()); OOCSIClient o2 = new OOCSIClient("pongR"); o2.connect("localhost", 4444); assertTrue(o2.isConnected()); o2.register("addnineteen", new Responder(o2) { @Override public void respond(OOCSIEvent event, OOCSIData response) { int pp = event.getInt("addnineteen", -1); response.data("addedthat", pp + 19); System.out.println("response from pongR"); } }); o2.register("addnine", new Responder(o2) { @Override public void respond(OOCSIEvent event, OOCSIData response) { int pp = event.getInt("addnineteen", -1); response.data("addedthat", pp + 9); } }); { OOCSICall call = new OOCSICall(o1, "addnineteen", "addnineteen", 500, 1).data("addnineteen", 1); call.sendAndWait(); assertTrue(call.hasResponse()); OOCSIEvent response = call.getFirstResponse(); assertEquals(20, response.getInt("addedthat", -1)); } { OOCSICall call = new OOCSICall(o1, "addnineteen", "addnineteen", 500, 1).data("addnineteen", 100); call.sendAndWait(); assertTrue(call.hasResponse()); OOCSIEvent response = call.getFirstResponse(); assertEquals(119, response.getInt("addedthat", -1)); } o1.disconnect(); o2.disconnect(); } @Test public void testResponderOverlap2() throws InterruptedException { OOCSIClient o1 = new OOCSIClient("pingR1"); o1.connect("localhost", 4444); assertTrue(o1.isConnected()); OOCSIClient o2 = new OOCSIClient("pongR1"); o2.connect("localhost", 4444); assertTrue(o2.isConnected()); o2.register("addnineteen2", new Responder(o2) { @Override public void respond(OOCSIEvent event, OOCSIData response) { int pp = event.getInt("addnineteen", -1); pp += 19; response.data("addedthat", pp); System.out.println("response from pongR1"); } }); OOCSIClient o3 = new OOCSIClient("pongR2"); o3.connect("localhost", 4444); assertTrue(o3.isConnected()); o3.register("addnineteen2", new Responder(o3) { @Override public void respond(OOCSIEvent event, OOCSIData response) { int pp = event.getInt("addnineteen", -1); pp += 19; response.data("addedthat", pp); System.out.println("response from pongR2"); } }); // test normal call/response handlers { OOCSICall call = new OOCSICall(o1, "addnineteen2", "addnineteen2", 500, 1).data("addnineteen", 1); call.sendAndWait(); assertTrue(call.hasResponse()); OOCSIEvent response = call.getFirstResponse(); assertEquals(20, response.getInt("addedthat", -1)); } // test direct response trigger 1 { OOCSICall call = new OOCSICall(o1, "pongR1", "addnineteen2", 500, 1).data("addnineteen", 100); call.sendAndWait(); assertTrue(call.hasResponse()); OOCSIEvent response = call.getFirstResponse(); assertEquals(119, response.getInt("addedthat", -1)); } // test direct response trigger 2 { OOCSICall call = new OOCSICall(o1, "pongR2", "addnineteen2", 500, 1).data("addnineteen", 100); call.sendAndWait(); assertTrue(call.hasResponse()); OOCSIEvent response = call.getFirstResponse(); assertEquals(119, response.getInt("addedthat", -1)); } o1.disconnect(); o2.disconnect(); o3.disconnect(); } @Test public void testResponderFail() throws InterruptedException { OOCSIClient o1 = new OOCSIClient("pingFail"); o1.connect("localhost", 4444); assertTrue(o1.isConnected()); OOCSIClient o2 = new OOCSIClient("pongFail"); o2.connect("localhost", 4444); assertTrue(o2.isConnected()); { OOCSICall call = new OOCSICall(o1, "pongFail", "addnineteen", 500, 1).data("addnineteen", 1); call.send(); assertTrue(!call.hasResponse()); } { OOCSICall call = new OOCSICall(o1, "pongFail", "addnineteen", 500, 1).data("addnineteen", 100); call.send(); assertTrue(!call.hasResponse()); } o1.disconnect(); o2.disconnect(); } @Test public void testResponderTimeout() throws InterruptedException { OOCSIClient o1 = new OOCSIClient("pingTO"); o1.connect("localhost", 4444); assertTrue(o1.isConnected()); OOCSIClient o2 = new OOCSIClient("pongTO"); o2.connect("localhost", 4444); assertTrue(o2.isConnected()); o2.register("addnineteen1", new Responder(o2) { @Override public void respond(OOCSIEvent event, OOCSIData response) { try { System.out.println("sleeping now"); Thread.sleep(600); } catch (InterruptedException e) { } } }); { OOCSICall call = new OOCSICall(o1, "pongTO", "addnineteen1", 500, 1).data("addnineteen", 1); call.send(); assertTrue(!call.hasResponse()); } { OOCSICall call = new OOCSICall(o1, "pongTO", "addnineteen1", 500, 1).data("addnineteen", 100); call.send(); assertTrue(!call.hasResponse()); } o1.disconnect(); o2.disconnect(); } } <|start_filename|>client/src/nl/tue/id/oocsi/client/protocol/DataHandler.java<|end_filename|> package nl.tue.id.oocsi.client.protocol; import java.util.Map; /** * event handler for events with structured data * * @author matsfunk */ abstract public class DataHandler extends Handler { /* * (non-Javadoc) * * @see nl.tue.id.oocsi.client.protocol.Handler#receive(java.lang.String, java.util.Map, long, java.lang.String, * java.lang.String) */ @Override public void receive(String sender, Map<String, Object> data, long timestamp, String channel, String recipient) { receive(sender, data, timestamp); } /** * abstract method to be implemented in anonymous classes that are instantiated by subscribing and registering for * events; encapsulates all incoming data as data map (mostly used for testing) * * @param sender * @param data * @param timestamp */ abstract public void receive(String sender, Map<String, Object> data, long timestamp); } <|start_filename|>client/src/nl/tue/id/oocsi/client/services/Responder.java<|end_filename|> package nl.tue.id.oocsi.client.services; import java.util.Map; import nl.tue.id.oocsi.OOCSIData; import nl.tue.id.oocsi.OOCSIEvent; import nl.tue.id.oocsi.client.OOCSIClient; import nl.tue.id.oocsi.client.protocol.Handler; import nl.tue.id.oocsi.client.protocol.OOCSIDataImpl; import nl.tue.id.oocsi.client.protocol.OOCSIMessage; /** * internal event handler for synchronized events with structured data * * @author matsfunk */ abstract public class Responder extends Handler { private OOCSIClient oocsi; private String callName; /** * constructor for easy client-side instantiation with service methods */ public Responder() { } /** * constructor for instantiation without service methods * * @param oocsi */ public Responder(OOCSIClient oocsi) { this(oocsi, null); } /** * constructor for full instantiation without service methods * * @param oocsi * @param callName */ private Responder(OOCSIClient oocsi, String callName) { this.oocsi = oocsi; this.callName = callName; } /** * set oocsi client for responses * * @param oocsi */ public void setOocsi(OOCSIClient oocsi) { this.oocsi = oocsi; } /** * set call name for responses * * @param callName */ public void setCallName(String callName) { this.callName = callName; } /* * (non-Javadoc) * * @see nl.tue.id.oocsi.client.protocol.Handler#receive(java.lang.String, java.util.Map, long, java.lang.String, * java.lang.String) */ @Override public void receive(String sender, Map<String, Object> data, long timestamp, String channel, final String recipient) { // check if this needs a response if (data.get(OOCSICall.MESSAGE_HANDLE) == null || !data.get(OOCSICall.MESSAGE_HANDLE).equals(callName)) { return; } // correct call to respond to OOCSIData response = new OOCSIDataImpl(); respond(new OOCSIEvent(channel, data, sender, timestamp) { @Override public String getRecipient() { return recipient; } }, response); // send response response.data(OOCSICall.MESSAGE_ID, data.get(OOCSICall.MESSAGE_ID)); new OOCSIMessage(oocsi, sender).data(response).send(); } /** * interface for responding to a call, needs to be implemented client-side * * @param event * @param response */ abstract public void respond(OOCSIEvent event, OOCSIData response); } <|start_filename|>client/src/nl/tue/id/oocsi/client/protocol/MultiMessage.java<|end_filename|> package nl.tue.id.oocsi.client.protocol; import java.util.LinkedList; import java.util.List; import java.util.Map; import nl.tue.id.oocsi.client.OOCSIClient; import nl.tue.id.oocsi.client.services.OOCSICall; public class MultiMessage extends OOCSIMessage { List<OOCSIMessage> messages = new LinkedList<OOCSIMessage>(); public MultiMessage(OOCSIClient oocsi) { super(oocsi, ""); } public MultiMessage(OOCSIClient oocsi, String channelName) { super(oocsi, ""); add(new OOCSIMessage(oocsi, channelName)); } public MultiMessage add(OOCSIMessage msg) { messages.add(msg); return this; } @Override public MultiMessage data(String key, String value) { for (OOCSIMessage msg : messages) { msg.data(key, value); } return this; } @Override public MultiMessage data(String key, boolean value) { for (OOCSIMessage msg : messages) { msg.data(key, value); } return this; } @Override public MultiMessage data(String key, int value) { for (OOCSIMessage msg : messages) { msg.data(key, value); } return this; } @Override public MultiMessage data(String key, float value) { for (OOCSIMessage msg : messages) { msg.data(key, value); } return this; } @Override public MultiMessage data(String key, double value) { for (OOCSIMessage msg : messages) { msg.data(key, value); } return this; } @Override public MultiMessage data(String key, long value) { for (OOCSIMessage msg : messages) { msg.data(key, value); } return this; } @Override public MultiMessage data(String key, Object value) { for (OOCSIMessage msg : messages) { msg.data(key, value); } return this; } @Override public MultiMessage data(Map<String, ? extends Object> bulkData) { for (OOCSIMessage msg : messages) { msg.data(bulkData); } return this; } @Override public void send() { for (OOCSIMessage msg : messages) { msg.send(); } } /** * send and wait for implicit timeout of 2 seconds * */ public void sendAndWait() { sendAndWait(2000); } /** * send and wait for given timeout * * @param timeoutMS */ public void sendAndWait(int timeoutMS) { boolean hasCalls = false; for (OOCSIMessage msg : messages) { msg.send(); // check if there are any calls in the list of messages if (msg instanceof OOCSICall) { hasCalls |= true; } } // start waiting try { // either in one long wait if (!hasCalls) { Thread.sleep(timeoutMS); } // or until all calls have responses else { for (int i = 0; i < 10; i++) { boolean delivered = true; for (OOCSIMessage msg : messages) { if (msg instanceof OOCSICall) { delivered &= ((OOCSICall) msg).hasResponse(); } } if (delivered) { break; } Thread.sleep(timeoutMS / 10); } } } catch (InterruptedException e) { } } /** * retrieve all messages to allow for call returns * * @return */ public List<OOCSIMessage> getMessages() { return messages; } } <|start_filename|>server/src/nl/tue/id/oocsi/server/services/OSCService.java<|end_filename|> package nl.tue.id.oocsi.server.services; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.Date; import nl.tue.id.oocsi.server.OOCSIServer; import nl.tue.id.oocsi.server.model.Channel; import nl.tue.id.oocsi.server.model.Server; import nl.tue.id.oocsi.server.protocol.Message; import com.illposed.osc.AddressSelector; import com.illposed.osc.OSCListener; import com.illposed.osc.OSCMessage; import com.illposed.osc.OSCPortIn; import com.illposed.osc.OSCPortOut; /** * OSC service component * * @author matsfunk * */ public class OSCService extends AbstractService { public static final String OSC = "OSC"; private int oscInPort; private int oscOutPort; private OSCPortOut opOut; public OSCService(final Server server, int port) { super(server); // configure OSC server oscInPort = port + 1; oscOutPort = port + 2; } @Override public void start() { try { // OSC input channel // ------------------------------------ OSCPortIn opIn = new OSCPortIn(oscInPort); OSCListener oscListener = new OSCListener() { public void acceptMessage(Date timestamp, OSCMessage message) { if (timestamp.getTime() < System.currentTimeMillis() + 1000 && timestamp.getTime() > System.currentTimeMillis() - 1000) { String address = message.getAddress(); String key = null; int index = address.lastIndexOf('/'); if (index > -1) { if (index < address.length() - 1) { key = address.substring(index); } address = address.substring(0, index); } Channel c = server.getChannel(address); Message m = new Message("osc://", address, timestamp); m.addData(key != null ? key : "data", message.getArguments()); c.send(m); } } }; opIn.addListener(new AddressSelector() { public boolean matches(String address) { int index = address.lastIndexOf('/'); if (index > -1) { address = address.substring(0, index); } return server.getChannel(address) != null; } }, oscListener); // OSC output channel // ------------------------------------ opOut = new OSCPortOut(new InetSocketAddress(oscOutPort).getAddress()); Channel oscOutPortChannel = new Channel(OSC, presence) { @Override public void send(Message message) { try { String recipient = message.recipient; if (recipient.startsWith("osc://")) { recipient = recipient.replaceFirst("osc:/", ""); opOut.send(new OSCMessage(recipient, message.data.values())); } } catch (IOException e) { // do nothing } } }; server.addChannel(oscOutPortChannel); } catch (IOException e) { OOCSIServer.log("[OSC server]: Could not listen on ports: " + oscInPort + ", " + (oscInPort + 1)); } // log output InetAddress addr; try { addr = InetAddress.getLocalHost(); String hostname = addr.getHostName(); OOCSIServer.log("[OSC server]: Started OSC service @ local address '" + hostname + "' on port " + (oscInPort + 1) + " for OSC."); } catch (UnknownHostException e) { e.printStackTrace(); } } @Override public void stop() { if (opOut != null) { opOut.close(); } } } <|start_filename|>client/test/ClientRequestTest.java<|end_filename|> import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.junit.Test; import nl.tue.id.oocsi.OOCSIEvent; import nl.tue.id.oocsi.client.OOCSIClient; import nl.tue.id.oocsi.client.protocol.DataHandler; import nl.tue.id.oocsi.client.protocol.EventHandler; import nl.tue.id.oocsi.client.protocol.OOCSIMessage; public class ClientRequestTest { @Test public void testClientAvailable() throws InterruptedException { String clientName = "test_client_client_available_1"; OOCSIClient o = new OOCSIClient(clientName); o.connect("localhost", 4444); Thread.sleep(200); assertTrue(o.isConnected()); assertTrue(o.clients().contains(clientName)); Thread.sleep(200); o.disconnect(); } @Test public void testChannelAvailable() throws InterruptedException { String clientName = "test_client_channel_available_2"; String channelName = "test_channel_123"; OOCSIClient o = new OOCSIClient(clientName); o.connect("localhost", 4444); Thread.sleep(200); assertTrue(o.isConnected()); assertTrue(o.channels().contains(clientName)); o.subscribe(channelName, new EventHandler() { public void receive(OOCSIEvent event) { // do nothing } }); Thread.sleep(200); assertTrue(o.channels().contains(channelName)); assertTrue(o.channels().contains(clientName)); Thread.sleep(200); o.disconnect(); } @Test public void testMessageContents() throws InterruptedException { String clientNameRecipient = "test_client_message_contents_1"; String clientNameSender = "test_client_message_contents_2"; final List<OOCSIEvent> events = new ArrayList<OOCSIEvent>(); // create recipient, connect and subscribe for event on a channel OOCSIClient recipient = new OOCSIClient(clientNameRecipient); recipient.connect("localhost", 4444); recipient.subscribe("mychannel", new EventHandler() { @Override public void receive(OOCSIEvent event) { events.add(event); } }); recipient.subscribe(new DataHandler() { public void receive(String sender, Map<String, Object> data, long timestamp) { System.out.println("sender"); } }); // create sender, connect and send OOCSIClient sender = new OOCSIClient(clientNameSender); sender.connect("localhost", 4444); new OOCSIMessage(sender, "mychannel").data("mykey", "myvalue").send(); // assertions Thread.sleep(200); OOCSIEvent event = events.get(0); assertEquals(clientNameSender, event.getSender()); assertEquals(clientNameRecipient, event.getRecipient()); assertEquals("mychannel", event.getChannel()); assertTrue(System.currentTimeMillis() - 300 < event.getTime()); recipient.disconnect(); sender.disconnect(); } }
Cyanogenbot/oocsi
<|start_filename|>pkg/edrRecon/collect.go<|end_filename|> package edrRecon import ( "context" "fmt" "github.com/FourCoreLabs/EDRHunt/pkg/resources" ) // GetSystemData collects the parsed list of processes, services, drivers and registry keys to be used for EDR heuristics. func GetSystemData(ctx context.Context) (resources.SystemData, error) { var err error var systemData resources.SystemData systemData.Processes, err = CheckProcesses() if err != nil { return systemData, fmt.Errorf("failed to check processes: %w", err) } systemData.Services, err = CheckServices() if err != nil { return systemData, fmt.Errorf("failed to check services: %w", err) } systemData.Registry, err = CheckRegistry(ctx) if err != nil { return systemData, fmt.Errorf("failed to check registry: %w", err) } systemData.Drivers, err = CheckDrivers() if err != nil { return systemData, fmt.Errorf("failed to check drivers: %w", err) } return systemData, nil } <|start_filename|>pkg/scanners/scan_crowdstrike.go<|end_filename|> package scanners import "github.com/FourCoreLabs/EDRHunt/pkg/resources" type CrowdstrikeDetection struct{} func (w *CrowdstrikeDetection) Name() string { return "Crowdstrike EDR Solution" } func (w *CrowdstrikeDetection) Type() resources.EDRType { return resources.CrowdstrikeEDR } var CrowdstrikeHeuristic = []string{ "CrowdStrike", "%SYSTEMROOT%\\system32\\drivers\\crowdstrike\\CsDeviceControl.inf", "%SYSTEMROOT%\\system32\\drivers\\crowdstrike\\CsFirmwareAnalysis.inf", } func (w *CrowdstrikeDetection) Detect(data resources.SystemData) (resources.EDRType, bool) { _, ok := data.CountMatchesAll(CrowdstrikeHeuristic) if !ok { return "", false } return resources.CrowdstrikeEDR, true } <|start_filename|>pkg/edrRecon/process_windows.go<|end_filename|> package edrRecon import ( "fmt" "strings" "github.com/FourCoreLabs/EDRHunt/pkg/resources" "github.com/hashicorp/go-multierror" "github.com/yusufpapurcu/wmi" ) type Win32_Process struct { Name string ExecutablePath string Description string Caption string CommandLine string ProcessId uint32 ParentProcessId uint32 // Status string // StartMode string } // CheckProcesses returns a list of processes matching any suspicious running process names present in edrdata.go. func CheckProcesses() ([]resources.ProcessMetaData, error) { var ( processList []Win32_Process multiErr error summary []resources.ProcessMetaData = make([]resources.ProcessMetaData, 0) ) query := wmi.CreateQuery(&processList, "") if err := wmi.Query(query, &processList); err != nil { return summary, err } for _, process := range processList { if process.Name == "" { continue } output, err := AnalyzeProcess(process) if err != nil { multiErr = multierror.Append(multiErr, err) continue } if len(output.ScanMatch) > 0 { summary = append(summary, output) } } return summary, multiErr } func AnalyzeProcess(process Win32_Process) (resources.ProcessMetaData, error) { analysis := resources.ProcessMetaData{ ProcessName: process.Name, ProcessPath: process.ExecutablePath, ProcessDescription: process.Description, ProcessCaption: process.Caption, ProcessCmdLine: process.CommandLine, ProcessPID: fmt.Sprint(process.ProcessId), ProcessParentPID: fmt.Sprint(process.ParentProcessId), } if analysis.ProcessPath != "" { analysis.ProcessExeMetaData, _ = GetFileMetaData(analysis.ProcessPath) } for _, edr := range EdrList { if strings.Contains( strings.ToLower(fmt.Sprint(analysis)), strings.ToLower(edr)) { analysis.ScanMatch = append(analysis.ScanMatch, edr) } } return analysis, nil } <|start_filename|>pkg/scanners/scan_mcafee.go<|end_filename|> package scanners import "github.com/FourCoreLabs/EDRHunt/pkg/resources" type McafeeDetection struct{} func (w *McafeeDetection) Name() string { return "McAfee MVISION Endpoint Detection and Response" } func (w *McafeeDetection) Type() resources.EDRType { return resources.McafeeEDR } var McafeeHeuristic = []string{ "Mcafee\\", "McAfeeAgent\\", "APPolicyName", "EPPolicyName", "OASPolicyName", } func (w *McafeeDetection) Detect(data resources.SystemData) (resources.EDRType, bool) { _, ok := data.CountMatchesAll(McafeeHeuristic) if !ok { return "", false } return resources.McafeeEDR, true } <|start_filename|>pkg/resources/systemdata.go<|end_filename|> package resources import ( "github.com/FourCoreLabs/EDRHunt/pkg/util" ) type SystemData struct { Processes []ProcessMetaData Registry RegistryMetaData Services []ServiceMetaData Drivers []DriverMetaData } // CountMatchesAll collects all the scanned matches of suspicious names and checks for passed keywords in the matches. func (s *SystemData) CountMatchesAll(keywords ...[]string) (int, bool) { var match bool var count int scanMatchList := make([]string, 0) for _, v := range s.Processes { scanMatchList = append(scanMatchList, v.ScanMatch...) } for _, v := range s.Services { scanMatchList = append(scanMatchList, v.ScanMatch...) } for _, v := range s.Drivers { scanMatchList = append(scanMatchList, v.ScanMatch...) } scanMatchList = append(scanMatchList, s.Registry.ScanMatch...) var totalLen int for _, v := range keywords { totalLen += len(v) } keywordList := make([]string, 0, totalLen) for _, v := range keywords { keywordList = append(keywordList, v...) } for _, v := range keywordList { contains := util.StrSliceContains(scanMatchList, v) if contains { match = true count++ } } return count, match } <|start_filename|>pkg/scanners/scan_elastic.go<|end_filename|> package scanners import "github.com/FourCoreLabs/EDRHunt/pkg/resources" type ElasticAgentDetection struct{} func (w *ElasticAgentDetection) Name() string { return "Elastic Endpoint Security" } func (w *ElasticAgentDetection) Type() resources.EDRType { return resources.ElasticAgentEDR } var ElasticAgentHeuristic = []string{ "Elastic Endpoint Security", "Elastic Agent", "elastic-agent.exe", "elastic-endpoint.exe", "elastic-endpoint-driver", "ElasticEndpoint", } func (w *ElasticAgentDetection) Detect(data resources.SystemData) (resources.EDRType, bool) { _, ok := data.CountMatchesAll(ElasticAgentHeuristic) if !ok { return "", false } return resources.ElasticAgentEDR, true } <|start_filename|>pkg/scanners/scan_sentinelone.go<|end_filename|> package scanners import "github.com/FourCoreLabs/EDRHunt/pkg/resources" type SentinelOneDetection struct{} func (w *SentinelOneDetection) Name() string { return "SentinelOne" } func (w *SentinelOneDetection) Type() resources.EDRType { return resources.SentinelOneEDR } var SentinelOneHeuristic = []string{ "SentinelOne\\", "CbDefense\\", "SensorVersion", } func (w *SentinelOneDetection) Detect(data resources.SystemData) (resources.EDRType, bool) { _, ok := data.CountMatchesAll(SentinelOneHeuristic) if !ok { return "", false } return resources.SentinelOneEDR, true } <|start_filename|>pkg/scanners/scan_fireeye.go<|end_filename|> package scanners import "github.com/FourCoreLabs/EDRHunt/pkg/resources" type FireEyeDetection struct{} func (w *FireEyeDetection) Name() string { return "FireEye" } func (w *FireEyeDetection) Type() resources.EDRType { return resources.FireEyeEDR } var FireEyeHeuristic = []string{ "FireEye", } func (w *FireEyeDetection) Detect(data resources.SystemData) (resources.EDRType, bool) { _, ok := data.CountMatchesAll(FireEyeHeuristic) if !ok { return "", false } return resources.FireEyeEDR, true } <|start_filename|>pkg/scanners/scan_symantec.go<|end_filename|> package scanners import "github.com/FourCoreLabs/EDRHunt/pkg/resources" type SymantecDetection struct{} func (w *SymantecDetection) Name() string { return "Symantec Endpoint Security" } func (w *SymantecDetection) Type() resources.EDRType { return resources.SymantecEDR } var SymantecHeuristic = []string{ "symantec", "symcorpu", "symefasi", "Symantec", "Symantec Endpoint Protection\\", } func (w *SymantecDetection) Detect(data resources.SystemData) (resources.EDRType, bool) { _, ok := data.CountMatchesAll(SymantecHeuristic) if !ok { return "", false } return resources.SymantecEDR, true } <|start_filename|>pkg/edrRecon/edrRecon_test.go<|end_filename|> package edrRecon import ( "context" "encoding/json" "fmt" "testing" "github.com/FourCoreLabs/EDRHunt/pkg/scanners" ) func TestCheckDrivers(t *testing.T) { summary, err := CheckDrivers() for _, driver := range summary { output := fmt.Sprintf("\nSuspicious Driver Module: %s\nDriver FilePath: %s\nDriver File Metadata: %s\nMatched Keyword: %s\n", driver.DriverBaseName, driver.DriverFilePath, FileMetaDataParser(driver.DriverSysMetaData), driver.ScanMatch) fmt.Println(output) } if err.Error() != "" { t.Error(err) } } func TestCheckRegistry(t *testing.T) { summary, err := CheckRegistry(context.TODO()) fmt.Println("Scanning registry: ") for _, match := range summary.ScanMatch { fmt.Printf("\t%s\n", match) } if err != nil { fmt.Println("error", err) } } func TestCheckServices(t *testing.T) { summary, err := CheckServices() for _, service := range summary { output := fmt.Sprintf("\nSuspicious Service Name: %s\nDisplay Name: %s\nDescription: %s\nCaption: %s\nCommandLine: %s\nStatus: %s\nProcessID: %s\nFile Metadata: %s\nMatched Keyword: %s\n", service.ServiceName, service.ServiceDisplayName, service.ServiceDescription, service.ServiceCaption, service.ServicePathName, service.ServiceState, service.ServiceProcessId, FileMetaDataParser(service.ServiceExeMetaData), service.ScanMatch) fmt.Println(output) } if err.Error() != "" { fmt.Println("error", err) } } func TestCheckProcesses(t *testing.T) { summary, err := CheckProcesses() for _, process := range summary { output := fmt.Sprintf("\nSuspicious Process Name: %s\nDescription: %s\nCaption: %s\nBinary: %s\nProcessID: %s\nParent Process: %s\nProcess CmdLine : %s\nFile Metadata: %s\nMatched Keyword: %s\n", process.ProcessName, process.ProcessDescription, process.ProcessCaption, process.ProcessPath, process.ProcessPID, process.ProcessParentPID, process.ProcessCmdLine, FileMetaDataParser(process.ProcessExeMetaData), process.ScanMatch) fmt.Println(output) } if err.Error() != "" { fmt.Println("error", err) } } func TestGetFileMetaData(t *testing.T) { fileMetaData, err := GetFileMetaData(`C:\Users\hardi\AnyDesk.exe`) if err != nil { t.Error(err) } file, _ := json.Marshal(fileMetaData) fmt.Println(string(file)) } func TestGetDirectory(t *testing.T) { _, err := CheckDirectory() if err != nil { t.Error(err) } } func TestCheckIfAdmin(t *testing.T) { status := CheckIfAdmin() if status { fmt.Println("Running as admin") } else { t.Error(status) } } func TestDeObfNames(t *testing.T) { for _, name := range EdrList { fmt.Println(name) } for _, name := range RegistryReconList { fmt.Println(name) } } type EDRHuntResult struct { Type string `json:"id"` } func TestEDRScanner(t *testing.T) { var result []EDRHuntResult = make([]EDRHuntResult, 0) systemData, err := GetSystemData(context.TODO()) if err != nil { t.Error(err) return } for _, scanner := range scanners.Scanners { _, ok := scanner.Detect(systemData) if ok { result = append(result, EDRHuntResult{ Type: string(scanner.Type()), }) } } fmt.Println(result) } <|start_filename|>Makefile<|end_filename|> all: build build: go build -ldflags="-w -s" -o EDRHunt.exe github.com/FourCoreLabs/EDRHunt/cmd/EDRHunt garble-build: garble -literals build -ldflags="-w -s" -o EDRHunt.exe github.com/FourCoreLabs/EDRHunt/cmd/EDRHunt local: go build -ldflags="-w -s" -o EDRHunt.exe github.com/FourCoreLabs/EDRHunt/cmd/EDRHunt run: go run -ldflags="-w -s" github.com/FourCoreLabs/EDRHunt/cmd/EDRHunt all drivers: go run -ldflags="-w -s" github.com/FourCoreLabs/EDRHunt/cmd/EDRHunt -d <|start_filename|>pkg/scanners/scan_kaspersky.go<|end_filename|> package scanners import "github.com/FourCoreLabs/EDRHunt/pkg/resources" type KaskperskyDetection struct{} func (w *KaskperskyDetection) Name() string { return "Kaspersky Security" } func (w *KaskperskyDetection) Type() resources.EDRType { return resources.KaskperskyEDR } var KasperskyHeuristic = []string{ "kaspersky", } func (w *KaskperskyDetection) Detect(data resources.SystemData) (resources.EDRType, bool) { _, ok := data.CountMatchesAll(KasperskyHeuristic) if !ok { return "", false } return resources.KaskperskyEDR, true } <|start_filename|>pkg/util/util.go<|end_filename|> package util import "strings" // StrSliceEqual checks wheter slice s contains a string exactly like e. func StrSliceEqual(s []string, e string) bool { for _, a := range s { if strings.EqualFold(a, e) { return true } } return false } // StrSliceContains checks wheter slice s contains a string which contains e. func StrSliceContains(s []string, e string) bool { for _, a := range s { if strings.Contains(a, e) { return true } } return false } <|start_filename|>pkg/scanners/scan_cylance.go<|end_filename|> package scanners import "github.com/FourCoreLabs/EDRHunt/pkg/resources" type CylanceDetection struct{} func (w *CylanceDetection) Name() string { return "Cylance Smart Antivirus" } func (w *CylanceDetection) Type() resources.EDRType { return resources.CylanceEDR } var CylanceHeuristic = []string{ "Cylance\\", "Cylance0", "Cylance1", "Cylance2", } func (w *CylanceDetection) Detect(data resources.SystemData) (resources.EDRType, bool) { _, ok := data.CountMatchesAll(CylanceHeuristic) if !ok { return "", false } return resources.CylanceEDR, true } <|start_filename|>pkg/scanners/scan_win_defender.go<|end_filename|> package scanners import "github.com/FourCoreLabs/EDRHunt/pkg/resources" type WinDefenderDetection struct{} func (w *WinDefenderDetection) Name() string { return "Windows Defender" } func (w *WinDefenderDetection) Type() resources.EDRType { return resources.WinDefenderEDR } var WinDefenderProcessHeuristic = []string{ "defender", "msmpeng", } var WinDefenderServicesHeuristic = []string{ "defender", "msmpeng", } var WinDefenderDriverHeuristic = []string{ "defender", } var WinDefenderRegistryHeuristic = []string{ "Windows Defender", } // Detect returnns EDRType `defender` // If // - processes list contains WinDefenderProcessHeuristic keywords // - services list contains WinDefenderServicesHeuristic keywords // - registry list contains WinDefenderRegistryHeuristic keywords // - driver list contains WinDefenderDriverHeuristic keywords func (w *WinDefenderDetection) Detect(data resources.SystemData) (resources.EDRType, bool) { _, ok := data.CountMatchesAll(WinDefenderDriverHeuristic, WinDefenderProcessHeuristic, WinDefenderRegistryHeuristic, WinDefenderServicesHeuristic) if !ok { return "", false } return resources.WinDefenderEDR, true } <|start_filename|>pkg/edrRecon/registry.go<|end_filename|> package edrRecon import ( "context" "fmt" "os/exec" "strings" "sync" "syscall" "github.com/FourCoreLabs/EDRHunt/pkg/resources" ) var ( outputLock sync.Mutex paramWg sync.WaitGroup output []string ) func runCMDCommand(ctx context.Context, command string) ([]byte, error) { params := []string{"/c", command} cmd, err := makeCmd(ctx, params...) if err != nil { return nil, err } return cmd.CombinedOutput() } func makeCmd(ctx context.Context, param ...string) (*exec.Cmd, error) { path, err := exec.LookPath("cmd") if err != nil { return nil, err } var cmdline string for _, s := range param { cmdline += s + " " } cmdline = strings.TrimSpace(cmdline) cmd := exec.CommandContext(ctx, path) cmd.SysProcAttr = &syscall.SysProcAttr{CmdLine: cmdline} return cmd, nil } func EnumRegistry(ctx context.Context) []string { for _, x := range RegistrySearchList { paramWg.Add(1) go func(args string) { defer paramWg.Done() stdout, err := runCMDCommand(ctx, args) if err != nil { return } outputLock.Lock() defer outputLock.Unlock() if len(stdout) != 0 { output = append(output, string(stdout)) } }(x) } paramWg.Wait() return output } func CheckRegistry(ctx context.Context) (resources.RegistryMetaData, error) { var analysis resources.RegistryMetaData = resources.RegistryMetaData{ScanMatch: make([]string, 0)} output := strings.Join(EnumRegistry(ctx), " ") if output != "" { processedOutput := strings.ToLower(output) for _, match := range RegistryReconList { if strings.Contains( processedOutput, strings.ToLower(match)) { analysis.ScanMatch = append(analysis.ScanMatch, match) } } } if len(analysis.ScanMatch) == 0 { return analysis, fmt.Errorf("nothing found in registry") } return analysis, nil } <|start_filename|>pkg/scanners/scan_carbonblack.go<|end_filename|> package scanners import "github.com/FourCoreLabs/EDRHunt/pkg/resources" type CarbonBlackDetection struct{} func (w *CarbonBlackDetection) Name() string { return "Carbon Black" } func (w *CarbonBlackDetection) Type() resources.EDRType { return resources.CarbonBlackEDR } var CarbonBlackHeuristic = []string{ "CarbonBlack\\", "CbDefense\\", "SensorVersion", } func (w *CarbonBlackDetection) Detect(data resources.SystemData) (resources.EDRType, bool) { _, ok := data.CountMatchesAll(CarbonBlackHeuristic) if !ok { return "", false } return resources.CarbonBlackEDR, true } <|start_filename|>pkg/scanners/scanner.go<|end_filename|> package scanners import "github.com/FourCoreLabs/EDRHunt/pkg/resources" var ( Scanners = []resources.EDRDetection{ &CarbonBlackDetection{}, &CrowdstrikeDetection{}, &CylanceDetection{}, &FireEyeDetection{}, &KaskperskyDetection{}, &McafeeDetection{}, &SymantecDetection{}, &SentinelOneDetection{}, &WinDefenderDetection{}, &ElasticAgentDetection{}, } ) <|start_filename|>pkg/edrRecon/drivers_windows.go<|end_filename|> package edrRecon import ( "errors" "fmt" "strings" "syscall" "unicode/utf16" "unsafe" "github.com/FourCoreLabs/EDRHunt/pkg/resources" "github.com/hashicorp/go-multierror" ) var ( // Library libpsapi uintptr // Functions enumDeviceDrivers uintptr getDeviceDriverBaseName uintptr getDeviceDriverFileName uintptr numberOfDrivers uint driverAddrs []uintptr ) type DWORD uint32 type LPVOID uintptr type LPVOIDARR []byte type LPWSTR *uint16 type UTF16Slice struct { Data unsafe.Pointer Len int Cap int } func init() { // Library libpsapi = doLoadLibrary("psapi.dll") // Functions enumDeviceDrivers = doGetProcAddress(libpsapi, "EnumDeviceDrivers") getDeviceDriverBaseName = doGetProcAddress(libpsapi, "GetDeviceDriverBaseNameW") getDeviceDriverFileName = doGetProcAddress(libpsapi, "GetDeviceDriverFileNameW") } func doLoadLibrary(name string) uintptr { lib, _ := syscall.LoadLibrary(name) return uintptr(lib) } func doGetProcAddress(lib uintptr, name string) uintptr { addr, _ := syscall.GetProcAddress(syscall.Handle(lib), name) return uintptr(addr) } func syscall3(trap, nargs, a1, a2, a3 uintptr) uintptr { ret, _, _ := syscall.Syscall(trap, nargs, a1, a2, a3) return ret } // func syscall6(trap, nargs, a1, a2, a3, a4, a5, a6 uintptr) uintptr { // ret, _, _ := syscall.Syscall6(trap, nargs, a1, a2, a3, a4, a5, a6) // return ret // } // dodgy function: may cause BOF func UTF16PtrToString(p *uint16) string { defer func() { if r := recover(); r != nil { return } }() if p == nil { return "" } if *p == 0 { return "" } // Find NUL terminator. n := 0 for ptr := unsafe.Pointer(p); *(*uint16)(ptr) != 0; n++ { ptr = unsafe.Pointer(uintptr(ptr) + unsafe.Sizeof(*p)) } var s []uint16 h := (*UTF16Slice)(unsafe.Pointer(&s)) h.Data = unsafe.Pointer(p) h.Len = n h.Cap = n return string(utf16.Decode(s)) } func EnumDeviceDrivers(lpImageBase []uintptr, cb DWORD, lpcbNeeded *uint32) bool { ret1 := syscall3(enumDeviceDrivers, 3, uintptr(unsafe.Pointer(&lpImageBase[0])), uintptr(cb), uintptr(unsafe.Pointer(lpcbNeeded))) return ret1 != 0 } func GetDeviceDriverBaseName(imageBase LPVOID, lpBaseName []uint16, nSize DWORD) DWORD { ret1 := syscall3(getDeviceDriverBaseName, 3, uintptr(unsafe.Pointer(imageBase)), uintptr(unsafe.Pointer(&lpBaseName[0])), uintptr(nSize)) return DWORD(ret1) } func GetDeviceDriverFileName(imageBase uintptr, lpFilename []uint16, nSize DWORD) DWORD { defer func() { if err := recover(); err != nil { fmt.Println("failure in GetDeviceDriverFilename") fmt.Println(err) return } }() ret1 := syscall3(getDeviceDriverFileName, 3, imageBase, uintptr(unsafe.Pointer(&lpFilename[0])), uintptr(nSize)) return DWORD(ret1) } func GetSizeOfDriversArray() (uint32, error) { var bytesNeeded uint32 // Golang null structs. nullBase := make([]uintptr, 1) success := EnumDeviceDrivers(nullBase, 0, &bytesNeeded) if !success { return 0, fmt.Errorf("failed to get size of Driver Array, errorcode : %v", syscall.GetLastError()) } return bytesNeeded, nil } func GetDriverFileName(driverAddrs uintptr) (string, error) { data := make([]uint16, 1024) if driverAddrs == 0 { return "", errors.New("nil driver address uintptr") } result := GetDeviceDriverFileName(driverAddrs, data, DWORD(1000)) if result == 0 { return "", fmt.Errorf("failed to get device driver file name: %v", syscall.GetLastError()) } return syscall.UTF16ToString(data), nil } func GetDriverBaseName(driverAddrs uintptr) (string, error) { data := make([]uint16, 1024) if driverAddrs == 0 { return "", errors.New("nil driver address uintptr") } result := GetDeviceDriverBaseName(LPVOID(driverAddrs), data, DWORD(1000)) if result == 0 { return "", fmt.Errorf("failed to get device driver file name: %v", syscall.GetLastError()) } return syscall.UTF16ToString(data), nil } func IterateOverDrivers(numberOfDrivers uint, driverAddrs []uintptr) ([]resources.DriverMetaData, error) { var ( multiErr error summary []resources.DriverMetaData = make([]resources.DriverMetaData, 0) ) for _, addr := range driverAddrs { driverFileName, err := GetDriverFileName(addr) if err != nil { multiErr = multierror.Append(multiErr, err) continue } driverBaseName, err := GetDriverBaseName(addr) if err != nil { multiErr = multierror.Append(multiErr, err) continue } if driverBaseName == "" { continue } output, err := AnalyzeDriver(driverFileName, driverBaseName) if err != nil { multiErr = multierror.Append(multiErr, err) } if len(output.ScanMatch) > 0 { summary = append(summary, output) } } return summary, multiErr } func AnalyzeDriver(driverFileName string, driverBaseName string) (resources.DriverMetaData, error) { fixedDriverPath := strings.ToLower(driverFileName) fixedDriverPath = strings.Replace(fixedDriverPath, `\systemroot\`, `c:\windows\`, -1) if strings.HasPrefix(fixedDriverPath, `\windows\`) { fixedDriverPath = strings.Replace(fixedDriverPath, `\windows\`, `c:\windows\`, -1) } else if strings.HasPrefix(fixedDriverPath, `\??\`) { fixedDriverPath = strings.Replace(fixedDriverPath, `\??\`, ``, -1) } analysis := resources.DriverMetaData{ DriverBaseName: driverBaseName, DriverFilePath: fixedDriverPath, ScanMatch: make([]string, 0), } analysis.DriverSysMetaData, _ = GetFileMetaData(fixedDriverPath) for _, edr := range EdrList { // regexp as alternate but saving another import. No bully. if strings.Contains( strings.ToLower(fmt.Sprint(analysis)), strings.ToLower(edr)) { analysis.ScanMatch = append(analysis.ScanMatch, edr) } } return analysis, nil } // CheckDrivers return a list of drivers matching any suspicious driver names present in edrdata.go. func CheckDrivers() ([]resources.DriverMetaData, error) { var drivers []resources.DriverMetaData = make([]resources.DriverMetaData, 0) sizeOfDriverArrayInBytes, err := GetSizeOfDriversArray() if err != nil { return drivers, err } sizeOfOneDriverAddress := uint(unsafe.Sizeof(uintptr(0))) numberOfDrivers = uint(sizeOfDriverArrayInBytes) / sizeOfOneDriverAddress driverAddrs = make([]uintptr, numberOfDrivers) success := EnumDeviceDrivers(driverAddrs, DWORD(sizeOfDriverArrayInBytes), &sizeOfDriverArrayInBytes) if !success { return drivers, fmt.Errorf("failed to enumerate device drivers, error code: %w", syscall.GetLastError()) } drivers, err = IterateOverDrivers(numberOfDrivers, driverAddrs) if err != nil { return drivers, err } return drivers, nil } <|start_filename|>pkg/edrRecon/privilege.go<|end_filename|> package edrRecon import ( "os" ) // CheckIfAdmin checks if the process has administrator privileges by trying to open the PHYSICALDRIVE0 (C:\\) raw device on Windows. func CheckIfAdmin() bool { f, err := os.Open("\\\\.\\PHYSICALDRIVE0") if err != nil { return false } f.Close() return true } // func ElevateAdmin() error { // verb := "runas" // exe, _ := os.Executable() // cwd, _ := os.Getwd() // args := strings.Join(os.Args[1:], " ") // verbPtr, _ := syscall.UTF16PtrFromString(verb) // exePtr, _ := syscall.UTF16PtrFromString(exe) // cwdPtr, _ := syscall.UTF16PtrFromString(cwd) // argPtr, _ := syscall.UTF16PtrFromString(args) // var showCmd int32 = 1 //SW_NORMAL // if err := windows.ShellExecute(0, verbPtr, exePtr, argPtr, cwdPtr, showCmd); err != nil { // return err // } // return nil // } <|start_filename|>pkg/resources/edrRecon.go<|end_filename|> package resources type Recon interface { CheckProcesses() ([]ProcessMetaData, error) CheckServices() ([]ServiceMetaData, error) CheckDrivers() ([]DriverMetaData, error) CheckRegistry() (RegistryMetaData, error) CheckDirectory() (string, error) } type FileMetaData struct { ProductName string OriginalFilename string InternalFileName string CompanyName string FileDescription string ProductVersion string Comments string LegalCopyright string LegalTrademarks string } type ServiceMetaData struct { ServiceName string ServiceDisplayName string ServiceDescription string ServiceCaption string ServicePathName string ServiceState string ServiceProcessId string ServiceExeMetaData FileMetaData ScanMatch []string } type ProcessMetaData struct { ProcessName string ProcessPath string ProcessDescription string ProcessCaption string ProcessCmdLine string ProcessPID string ProcessParentPID string ProcessExeMetaData FileMetaData ScanMatch []string } type DriverMetaData struct { DriverBaseName string DriverSysMetaData FileMetaData DriverFilePath string ScanMatch []string } type RegistryMetaData struct { ScanMatch []string } <|start_filename|>pkg/resources/scan_edr.go<|end_filename|> package resources type EDRDetection interface { Detect(data SystemData) (EDRType, bool) Name() string Type() EDRType } type EDRType string var ( WinDefenderEDR EDRType = "defender" KaskperskyEDR EDRType = "kaspersky" CrowdstrikeEDR EDRType = "crowdstrike" McafeeEDR EDRType = "mcafee" SymantecEDR EDRType = "symantec" CylanceEDR EDRType = "cylance" CarbonBlackEDR EDRType = "carbon_black" SentinelOneEDR EDRType = "sentinel_one" FireEyeEDR EDRType = "fireeye" ElasticAgentEDR EDRType = "elastic_agent" )
utkarshiam/EDRHunt
<|start_filename|>recycler-page-list/src/main/java/com/recycler/page/recycler/RecyclerViewScrollerDetection.kt<|end_filename|> package com.recycler.page.recycler import android.util.Log import android.view.View import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.OnChildAttachStateChangeListener import androidx.recyclerview.widget.SnapHelper import java.lang.Exception /** * Author:yangfeng * Data:yangfeng on 2021/12/12 10:14 * Email:<EMAIL> * * * val recyclerViewScrollerDetection = RecyclerViewScrollerDetection() * recyclerViewScrollerDetection.setCurrentListener(this) * recyclerViewScrollerDetection.attachToSnapHelper(snapHelper) * recyclerViewScrollerDetection.addOnScrollListener(mRecyclerView) */ class RecyclerViewScrollerDetection : ListItemsVisibilityCalculator { private var mSnapHelper: SnapHelper? = null private var mCurrentListener: OnSnapHelperCurrentListener? = null var position = RecyclerView.NO_POSITION private var previousPosition = RecyclerView.NO_POSITION private var isFirstAttached = false private var recyclerView: RecyclerView? = null val mSnapScrollListener = SnapScrollListener() var mSnapChildAttachStateListener: SnapChildAttachStateChangeListener? = null /** * 第一次进来,是否调用setActive */ var isFirstActive = true private var currentItemView: View? = null private var previousView: View? = null fun attachToSnapHelper(snapHelper: SnapHelper) { mSnapHelper = snapHelper } /** * 设置监听 * * @param recyclerView */ fun addOnScrollListener(recyclerView: RecyclerView) { this.recyclerView = recyclerView recyclerView.addOnScrollListener(mSnapScrollListener) mSnapChildAttachStateListener = SnapChildAttachStateChangeListener(recyclerView) mSnapChildAttachStateListener?.run { recyclerView.addOnChildAttachStateChangeListener(this) } } inner class SnapScrollListener : RecyclerView.OnScrollListener() { override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { super.onScrollStateChanged(recyclerView, newState) this@RecyclerViewScrollerDetection.onScrollStateChanged(recyclerView, newState) } } inner class SnapChildAttachStateChangeListener(var recyclerView: RecyclerView) : OnChildAttachStateChangeListener { override fun onChildViewAttachedToWindow(view: View) { if (!isFirstActive || isFirstAttached) return position = recyclerView.getChildAdapterPosition(view) currentItemView = view mCurrentListener?.setActive(view, position, null, previousPosition) previousPosition = position previousView = view isFirstAttached = true } override fun onChildViewDetachedFromWindow(view: View) { val previousPosition = recyclerView.getChildAdapterPosition(view) currentItemView?.run { val position = recyclerView.getChildAdapterPosition( this ) mCurrentListener?.let { if (position == previousPosition) { it.disActive(view, previousPosition) } } } } } fun setCurrentListener(mCurrentListener: OnSnapHelperCurrentListener?) { this.mCurrentListener = mCurrentListener } override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { try { when (newState) { RecyclerView.SCROLL_STATE_IDLE -> { val layoutManager = recyclerView.layoutManager currentItemView = mSnapHelper?.findSnapView(layoutManager) if (null == currentItemView) return val currentPosition = recyclerView.getChildAdapterPosition(currentItemView!!) if (previousPosition == currentPosition || null == mCurrentListener) return position = recyclerView.getChildAdapterPosition(currentItemView!!) val mPreviousView = previousView val mPreviousPosition = previousPosition mCurrentListener?.setActive( currentItemView, position, mPreviousView, mPreviousPosition ) previousPosition = currentPosition previousView = currentItemView } RecyclerView.SCROLL_STATE_DRAGGING -> { } RecyclerView.SCROLL_STATE_SETTLING -> { } } } catch (e: Exception) { e.printStackTrace() Log.e("yyyyy", Log.getStackTraceString(e)) } } override fun detachToSnapHelper() { recyclerView?.removeOnScrollListener(mSnapScrollListener) mSnapChildAttachStateListener?.run { recyclerView?.removeOnChildAttachStateChangeListener( this ) } } override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {} } <|start_filename|>app/src/main/java/com/video/list/player/IOUtils.java<|end_filename|> package com.video.list.player; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; public class IOUtils { public static void close(OutputStream stream) { if (stream != null) { try { stream.close(); } catch (IOException e) { e.printStackTrace(); } } } public static void close(InputStream stream) { if (stream != null) { try { stream.close(); } catch (IOException e) { e.printStackTrace(); } } } public static void close(InputStreamReader stream) { if (stream != null) { try { stream.close(); } catch (IOException e) { e.printStackTrace(); } } } public static void close(BufferedReader stream) { if (stream != null) { try { stream.close(); } catch (IOException e) { e.printStackTrace(); } } } public static void flush(OutputStream stream) { if (stream != null) { try { stream.flush(); } catch (IOException e) { e.printStackTrace(); } } } } <|start_filename|>recycler-page-list/src/main/java/com/recycler/page/recycler/ListItemsVisibilityCalculator.kt<|end_filename|> package com.recycler.page.recycler import androidx.recyclerview.widget.RecyclerView /** * Author:yangfeng * Data:yangfeng on 2021/12/12 10:09 * Email:<EMAIL> */ interface ListItemsVisibilityCalculator { /** * 滑动监听事件 */ fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) fun detachToSnapHelper() } <|start_filename|>app/src/main/java/com/video/list/player/AssetsUtil.java<|end_filename|> package com.video.list.player; import android.content.Context; import android.content.res.AssetManager; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; /** * */ public class AssetsUtil { public static String read(Context context, String fileName){ InputStreamReader inputStreamReader = null; BufferedReader bufferedReader = null; InputStream inputStream = null; StringBuilder builder = new StringBuilder(); if (context == null || fileName == null || 0 >= fileName.length()) { return null; } try { inputStream = context.getResources().getAssets().open(fileName); if (null == inputStream) { return null; } inputStreamReader = new InputStreamReader(inputStream); bufferedReader = new BufferedReader(inputStreamReader); String line; while((line = bufferedReader.readLine()) != null) { builder.append(line); } } catch (Exception e) { e.printStackTrace(); } finally { IOUtils.close(inputStreamReader); IOUtils.close(bufferedReader); IOUtils.close(inputStream); } return builder.toString(); } public static String getJson(Context context,String fileName) { StringBuilder stringBuilder = new StringBuilder(); try { AssetManager assetManager = context.getAssets(); BufferedReader bf = new BufferedReader(new InputStreamReader( assetManager.open(fileName))); String line; while ((line = bf.readLine()) != null) { stringBuilder.append(line); } } catch (IOException e) { e.printStackTrace(); } return stringBuilder.toString(); } } <|start_filename|>app/src/main/java/com/video/list/player/MainActivity.kt<|end_filename|> package com.video.list.player import android.net.Uri import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.FrameLayout import android.widget.ImageView import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.PagerSnapHelper import androidx.recyclerview.widget.RecyclerView import com.google.android.exoplayer2.MediaItem import com.google.android.exoplayer2.MediaMetadata import com.google.android.exoplayer2.Player import com.google.android.exoplayer2.SimpleExoPlayer import com.google.android.exoplayer2.analytics.AnalyticsListener import com.google.android.exoplayer2.source.ConcatenatingMediaSource import com.google.android.exoplayer2.source.MediaSource import com.google.android.exoplayer2.source.ProgressiveMediaSource import com.google.android.exoplayer2.ui.PlayerView import com.google.android.exoplayer2.upstream.DataSource import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory import com.google.android.exoplayer2.util.Util import com.google.gson.Gson import com.google.gson.reflect.TypeToken import com.recycler.page.recycler.OnSnapHelperCurrentListener import com.recycler.page.recycler.RecyclerViewScrollerDetection import com.video.list.player.bean.VideoInfo class MainActivity : AppCompatActivity(), OnSnapHelperCurrentListener { val simpleExoPlayer by lazy { SimpleExoPlayer.Builder(this).build() } val concatMedia = ConcatenatingMediaSource() val playerView by lazy { View.inflate( this, R.layout.view_exo_concat_video_play, null ) as PlayerView } val mRecyclerView by lazy { findViewById<RecyclerView>(R.id.mRecyclerView) } val lineLayout by lazy { LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false) } val mAdapter = VideoListAdapter() val snapHelper = PagerSnapHelper() var currentView: View? = null val recyclerViewScrollerDetection = RecyclerViewScrollerDetection() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) onInitView() setData() } /** * */ private fun onInitView() { simpleExoPlayer.repeatMode = Player.REPEAT_MODE_ONE playerView.player = simpleExoPlayer simpleExoPlayer.addAnalyticsListener(object : AnalyticsListener { override fun onRenderedFirstFrame( eventTime: AnalyticsListener.EventTime, output: Any, renderTimeMs: Long ) { super.onRenderedFirstFrame(eventTime, output, renderTimeMs) val mFMVideo = currentView?.findViewById<FrameLayout>(R.id.mFMVideo) val mIVCover = currentView?.findViewById<ImageView>(R.id.mIVCover) mIVCover?.visibility = View.INVISIBLE mFMVideo?.visibility = View.VISIBLE } }) mRecyclerView.layoutManager = lineLayout mRecyclerView.adapter = mAdapter snapHelper.attachToRecyclerView(mRecyclerView) recyclerViewScrollerDetection.setCurrentListener(this) recyclerViewScrollerDetection.attachToSnapHelper(snapHelper) recyclerViewScrollerDetection.addOnScrollListener(mRecyclerView) } /** * 设置数据源 */ private fun setData() { val json = AssetsUtil.getJson(this, "video_list.json") val type = object : TypeToken<ArrayList<VideoInfo>>() {}.type val data = Gson().fromJson<ArrayList<VideoInfo>>(json, type) data.forEach { concatMedia.addMediaSource(getMediaSource(it.mp4Url)) } simpleExoPlayer.setMediaSource(concatMedia) simpleExoPlayer.prepare() simpleExoPlayer.play() mAdapter.setNewData(data) } private fun getMediaSource(url: String?): MediaSource { // 在播放期间测量带宽。如果不需要,可以为空。 val bandwidthMeter = DefaultBandwidthMeter.Builder(this).build() // 生成用于加载媒体数据的数据源实例。 val dataSourceFactory: DataSource.Factory = DefaultDataSourceFactory( this, Util.getUserAgent(this, this.packageName), bandwidthMeter ) // 这是媒体资源,代表要播放的媒体。 val mUri = Uri.parse(url) val builder = MediaItem.Builder() val mediaMetadata = MediaMetadata.Builder() builder.setMediaMetadata(mediaMetadata.build()) val mediaItem = builder.setUri(mUri).build() val videoSource = ProgressiveMediaSource.Factory(dataSourceFactory).createMediaSource(mediaItem) return videoSource } /** *新增数据源 */ private fun addMediaSource(url: String?) { val json = AssetsUtil.getJson(this, "新增数据源.json") val type = object : TypeToken<ArrayList<VideoInfo>>() {}.type val data = Gson().fromJson<ArrayList<VideoInfo>>(json, type) val mediaSources = mutableListOf<MediaSource>() data.forEach { mediaSources.add(getMediaSource(it.mp4Url)) } simpleExoPlayer.addMediaSources(mediaSources) mAdapter.addData(data) } override fun onResume() { super.onResume() simpleExoPlayer.play() } override fun onPause() { super.onPause() simpleExoPlayer.pause() } override fun onDestroy() { super.onDestroy() simpleExoPlayer.release() recyclerViewScrollerDetection.detachToSnapHelper() } override fun setActive( currentView: View?, position: Int, previousView: View?, previousPosition: Int ) { this.currentView = currentView val mFMVideo = currentView?.findViewById<FrameLayout>(R.id.mFMVideo) (playerView?.parent as FrameLayout?)?.removeView(playerView) mFMVideo?.removeAllViews() mFMVideo?.addView(playerView) if (!simpleExoPlayer.isPlaying) { simpleExoPlayer.play() } simpleExoPlayer.seekToDefaultPosition(position) } override fun disActive(detachedView: View?, detachedPosition: Int) { if (null == detachedView) return val mIVCover = detachedView.findViewById<ImageView>(R.id.mIVCover) val mFMVideo = detachedView.findViewById<FrameLayout>(R.id.mFMVideo) mIVCover.visibility = View.VISIBLE mFMVideo.visibility = View.INVISIBLE if (simpleExoPlayer.isPlaying) { simpleExoPlayer.pause() } } } <|start_filename|>recycler-page-list/src/main/java/com/recycler/page/recycler/OnSnapHelperCurrentListener.kt<|end_filename|> package com.recycler.page.recycler import android.view.View interface OnSnapHelperCurrentListener { /** * 选中哪个view * * @param currentView 当前选中的View * @param position 当前选中的position * @param previousView 上一次选中的View 为null 暂不使用 * @param previousPosition 上一次选中的position */ fun setActive(currentView: View?, position: Int, previousView: View?, previousPosition: Int) /** * view detached的时候调用 * 避免快速滑动,View不被移除 * * @param detachedView 翻页过后的View * @param detachedPosition 翻页过后的position */ fun disActive(detachedView: View?, detachedPosition: Int) } <|start_filename|>app/src/main/java/com/video/list/player/VideoListAdapter.kt<|end_filename|> package com.video.list.player import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.video.list.player.bean.VideoInfo class VideoListAdapter : RecyclerView.Adapter<VideoListAdapter.VideoListHolder>() { val data = mutableListOf<VideoInfo>() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VideoListHolder { val itemView = LayoutInflater.from(parent.context).inflate(R.layout.item_video, parent, false) val holder = VideoListHolder(itemView) return holder } override fun onBindViewHolder(holder: VideoListHolder, position: Int) { val item = data[position] val context = holder.itemView.context Glide.with(context).load(item.cover).into(holder.mIVCover) } fun setNewData(newData: Collection<VideoInfo>) { data.clear() data.addAll(newData) notifyDataSetChanged() } fun addData(newData: Collection<VideoInfo>) { data.addAll(newData) val newSize = newData.size val size = data.size notifyItemRangeInserted(size - newSize, newSize) } override fun getItemCount(): Int { return data.size } class VideoListHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val mIVCover = itemView.findViewById<ImageView>(R.id.mIVCover) } } <|start_filename|>app/src/main/java/com/video/list/player/bean/VideoInfo.kt<|end_filename|> package com.video.list.player.bean class VideoInfo { var position: Int? = null var mp4Url: String? = null var title: String? = null var desc: String? = null var cover: String? = null var msg: String? = null var froms: String? = null var isMp4: String? = null }
yangfeng1994/video-list-player
<|start_filename|>Working_With_Market_Data_Example_Julia.jl<|end_filename|> # MIT license (c) 2019 by <NAME> # Julia 1.1.0. # The code illustrates some basic operations with large chunks of market data # (extracted from public sources), such as # creating histograms from the returns, and other similar operations. using Dates, JuliaDB # The historical quotes are downloaded in .csv format from nasdaq.com and are placed # in the directory "HistoricalQuotes." Before those files can be used here they # must be modified (slightly) in Excel, LibreOffice Calc, or a text editor (e.g., Emacs): # there should be no empty line, or a line that contains a time-stamp (all lines except # the first one must be identically formatted -- this may involve removing the second # line in the spreadhseet). The data for all stocks can be stored in a single variable # (note that HistoricalQuotes is the name of the sub-directory that contains all .csv files). stocksdata = loadndsparse("HistoricalQuotes"; filenamecol = :ticker, indexcols = [:ticker, :date]) # The same database can now be saved in a special binary format that makes reloading # at a later time very fast. save(stocksdata, "stocksdata.jdb") @time reloaded_stocksdata = load("stocksdata.jdb") # Test the saved database for consistency. stocksdata == reloaded_stocksdata # Look up the data associated only with Apple (symbol AAPL): stocksdata["AAPL",:] length(stocksdata["AAPL",:]) # Similarly, look up the data linked to Microsoft. stocksdata["MSFT",:] length(stocksdata["MSFT",:]) # Look up the price of Google on a specific date in the past. stocksdata["GOOGL", Date(2009,9,9)] stocksdata["GOOGL", Date(2009,9,9)].close # Extract the closing prices of Amazon *only*. selectvalues(stocksdata,:close)["AMZN",:] keytype(stocksdata) # List all dates for which the closing prices for Apple are available. AAPLdate=columns(stocksdata["AAPL",:])[1] #Extract the closing prices of Apple on those days. AAPLclose=columns(stocksdata["AAPL",:])[2] stocksdata["AAPL", Date(2008,8,11)].close # Produce some plots. using Plots pyplot() plot(AAPLdate, AAPLclose,label="AAPL closing price") # Calculate and plot the daily returns for AAPL. begin llc=length(AAPLclose); AAPLreturns=(AAPLclose[2:llc]-AAPLclose[1:llc-1])./AAPLclose[1:llc-1]; scatter(AAPLdate[2:llc],AAPLreturns,label="AAPL daily returns",markersize=2) end # Now build the histogram from the returns using a custom made 'histogram' function # (called 'hstgram' to avoid the confucion with the standard 'histogram'). # It takes as an input a single 1-dimensional array of data. The number of bins in # the histogram is determined automatically by using the Diaconis-Friedman rule. # The function returns two arrays: the mid-points of the bins and the (unnormalized) # heights of the bars. using StatsBase function hstgram(data_sample::Array{Float64,1}) data_sorted=sort(data_sample) first=data_sorted[1] last=data_sorted[end] nmb=length(data_sorted) IQR=percentile(data_sorted,75)-percentile(data_sorted,25) bin_size_loc = 2*IQR*(nmb^(-1.0/3)) num_bins=Int(floor((last-first)/bin_size_loc)) bin_size=(last-first)/(num_bins) bin_end_points=[first+(i-1)*bin_size for i=1:(num_bins+1)] ahist_val=[length(data_sorted[data_sorted .< u]) for u in bin_end_points] hist_val=[ahist_val[i+1]-ahist_val[i] for i=1:num_bins] mid_bins=[first-bin_size/2+i*bin_size for i=1:num_bins] return mid_bins, hist_val end # Normalize the bars so that the area of the histogram equals 1. begin U,V=hstgram(AAPLreturns); VV=V/(sum(V)*(U[2]-U[1])); end begin plot(U,VV,line=(:sticks,0.75),label="") xlabel!("returns") ylabel!("normalized frequency") title!("Histogram from the 10y daily returns from AAPL.") end # Test that the area of the histogram is indeed 1. sum(VV)*(U[2]-U[1]) # Another variation of the same histogram. begin plot(U.+(U[2]-U[1])/2,VV,label="",line=(:steppre,1),linewidth=0.05) xlabel!("samples") ylabel!("normalized frequency") end # Normalize the bars to give the probabilities for hitting the bins. begin VVV=V/sum(V); plot(U.+(U[2]-U[1])/2,VVV,label="",line=(:steppre,1),linewidth=0.05) xlabel!("samples") ylabel!("probability") end # Test that the probabilities do sum to 1. sum(VVV) <|start_filename|>Num-Prog-US-Call-Julia-functions.jl<|end_filename|> ## MIT license (C) 2019 by <NAME> ## ## note the formula ## $\int_a^bf(t)dt={1\over2}(b-a)\int_{-1}^{+1}f\bigl({1\over2}(b-a)s+{1\over2}(a+b)\bigr)d s$ ##(Used by FastGaussQuadrature) ## begin using SpecialFunctions using Interpolations using Roots using FastGaussQuadrature function EUcall(S::Float64,t::Float64,K::Float64,σ::Float64,r::Float64,δ::Float64) local v1,v2 v1=(δ-r+σ^2/2.0)*t+log(K/S) v2=(-δ + r + σ^2/2.0)*t - log(K/S) v3=σ*sqrt(2.0*t) return -K*(exp(-t*r)/2)+K*(exp(-t*r)/2)*erf(v1/v3)+S*(exp(-t*δ)/2)*erf(v2/v3)+S*(exp(-t*δ)/2) end function F(ϵ::Int64,t::Float64,u::Float64,v::Float64,r::Float64,δ::Float64,σ::Float64) v1=(r-δ+ϵ*σ^2/2)*(u-t)-log(v) v2=σ*sqrt(2*(u-t)) return 1.0+erf(v1/v2) end function ah(t::Float64,z::Float64,r::Float64,δ::Float64,σ::Float64,f) return (exp(-δ*(z-t))*(δ/2)*F(1,t,z,f(z)/f(t),r,δ,σ)) end function bh(t::Float64,z::Float64,r::Float64,δ::Float64,σ::Float64,K::Float64,f) return (exp(-r*(z-t))*(r*K/2)*F(-1,t,z,f(z)/f(t),r,δ,σ)) end function make_grid0(step::Float64,size::Int64) return 0.0:step:(step+(size-1)*step) end end function mainF(start_iter::Int64,nmb_of_iter::Int64,conv_tol::Float64,K::Float64,σ::Float64,δ::Float64,r::Float64,T::Float64,Δ::Float64,nmb_grd_pnts::Int64,vls::Array{Float64,1},nds::Array{Float64,1},wghts::Array{Float64,1}) local no_iter,conv_check,absc,absc0,valPrev,val,loc,f absc=range(0.0,length=nmb_grd_pnts+1,stop=T) absc0=range(0.0,length=nmb_grd_pnts,stop=(T-Δ)); val=vls; f=CubicSplineInterpolation(absc,val,extrapolation_bc = Interpolations.Line()) no_iter=start_iter; conv_check=100.0 while no_iter<nmb_of_iter&&conv_check>conv_tol no_iter+=1 loc=[max(K,K*(r/δ))] for ttt=Iterators.reverse(absc0) an=[(1/2)*(T-ttt)*ah(ttt,(1/2)*(T-ttt)*s+(1/2)*(ttt+T),r,δ,σ,f) for s in nodes] bn=[(1/2)*(T-ttt)*bh(ttt,(1/2)*(T-ttt)*s+(1/2)*(ttt+T),r,δ,σ,K,f) for s in nodes] aaa=weights'*an bbb=weights'*bn; LRT=find_zero(x->x-K-EUcall(x,T-ttt,K,σ,r,δ)-aaa*x+bbb,(K-10,K+20)); pushfirst!(loc,LRT) end valPrev=val val=loc f=CubicSplineInterpolation(absc,val,extrapolation_bc = Interpolations.Line()) conv_check=maximum(abs.(valPrev-val)) end return absc,val,conv_check,no_iter end <|start_filename|>Num-Prog-US-Call-Julia-parallel-functions.jl<|end_filename|> ## MIT license (c) 2019 by <NAME> ## ## note the formula ## $\int_a^bf(t)dt={1\over2}(b-a)\int_{-1}^{+1}f\bigl({1\over2}(b-a)s+{1\over2}(a+b)\bigr)d s$ ##(Used by FastGaussQuadrature) ## begin @everywhere using SpecialFunctions @everywhere using Interpolations @everywhere using Roots @everywhere using FastGaussQuadrature @everywhere function EUcall(S::Float64,t::Float64,K::Float64,σ::Float64,r::Float64,δ::Float64) local v1,v2 v1=(δ-r+σ^2/2.0)*t+log(K/S) v2=(-δ + r + σ^2/2.0)*t - log(K/S) v3=σ*sqrt(2.0*t) return -K*(exp(-t*r)/2)+K*(exp(-t*r)/2)*erf(v1/v3)+S*(exp(-t*δ)/2)*erf(v2/v3)+S*(exp(-t*δ)/2) end @everywhere function F(ϵ::Int64,t::Float64,u::Float64,v::Float64,r::Float64,δ::Float64,σ::Float64) v1=(r-δ+ϵ*σ^2/2)*(u-t)-log(v) v2=σ*sqrt(2*(u-t)) return 1.0+erf(v1/v2) end @everywhere function ah(t::Float64,z::Float64,r::Float64,δ::Float64,σ::Float64,f) return (exp(-δ*(z-t))*(δ/2)*F(1,t,z,f(z)/f(t),r,δ,σ)) end @everywhere function bh(t::Float64,z::Float64,r::Float64,δ::Float64,σ::Float64,K::Float64,f) return (exp(-r*(z-t))*(r*K/2)*F(-1,t,z,f(z)/f(t),r,δ,σ)) end @everywhere function mke_grd(bgn::Float64,step::Float64,size::Int64) return bgn:step:(bgn+step+(size-1)*step) end @everywhere function workerF(loc_range::StepRangeLen{Float64,Base.TwicePrecision{Float64},Base.TwicePrecision{Float64}},r::Float64,δ::Float64,σ::Float64,T::Float64,K::Float64,nds::Array{Float64,1},wghts::Array{Float64,1},f) local loc,LRT,aaa,bbb,an,bn,lnlr lnlr=length(loc_range) loc=zeros(lnlr) for i=lnlr:-1:1 t=loc_range[i] an=[(1/2)*(T-t)*ah(t,(1/2)*(T-t)*s+(1/2)*(t+T),r,δ,σ,f) for s in nds] bn=[(1/2)*(T-t)*bh(t,(1/2)*(T-t)*s+(1/2)*(t+T),r,δ,σ,K,f) for s in nds] aaa=wghts'*an bbb=wghts'*bn; LRT=find_zero(x->x-K-EUcall(x,T-t,K,σ,r,δ)-aaa*x+bbb,(K-10,K+20)); loc[i]=LRT end return loc end function cmbn(varg::Array{Array{Float64,1},1}) if length(varg)>1 loc=varg[1] for i=2:length(varg) loc=vcat(loc,varg[i]) end return loc else return varg end end end function masterF(prnmb::Int64, start_iter::Int64,nmb_of_iter::Int64,conv_tol::Float64,K::Float64,σ::Float64,δ::Float64,r::Float64,T::Float64,Δ::Float64,no_grd_pnts::Int64,vls::Array{Float64,1},nds::Array{Float64,1},wghts::Array{Float64,1}) local no_iter,conv_check,absc,absc0,val,valPrev,loc,f absc=range(0.0,length=pnmb*no_grd_pnts+1,stop=T) absc0=range(0.0,length=pnmb*no_grd_pnts,stop=(T-Δ)) all_grid=[range((T/prnmb)*i,length=no_grd_pnts,stop=((T/prnmb)*(i+1)-Δ)) for i=0:(pnmb-1)] val=vls; f=CubicSplineInterpolation(absc,val,extrapolation_bc = Interpolations.Line()) for i=2:(prnmb+1) remotecall_fetch(()->K, i) remotecall_fetch(()->σ, i) remotecall_fetch(()->δ, i) remotecall_fetch(()->r, i) remotecall_fetch(()->T, i) remotecall_fetch(()->all_grid, i) remotecall_fetch(()->f, i) remotecall_fetch(()->nds, i) remotecall_fetch(()->wghts, i) end no_iter=start_iter; conv_check=1000.0 while no_iter<nmb_of_iter&&conv_check>conv_tol valPrev=val; no_iter+=1 lst=[@spawnat i workerF(all_grid[myid()-1],r,δ,σ,T,K,nds,wghts,f) for i=2:(prnmb+1)] val0=[fetch(lst[i]) for i=1:prnmb]; val=cmbn(val0) push!(val,max(K,K*(r/δ))) f=CubicSplineInterpolation(absc,val,extrapolation_bc = Interpolations.Line()) for i=2:(prnmb+1) remotecall_fetch(()->f, i) end conv_check=maximum(abs.(valPrev-val)) end return absc,val,conv_check,no_iter end <|start_filename|>Multivariate-Normal-Dist-Examples-Julia.jl<|end_filename|> ## MIT license (C) 2019 by <NAME> # Julia 1.1.0 code to illustrate the construction of univariate histograms # and the Monte Carlo simulation technique for multivariate Gaussian samples with a given covariance matrix. #See (3.67), p.91, in "Stochastic Methods in Asset Pricing." begin using LinearAlgebra using SpecialFunctions using StatsBase using Random using Plots pyplot() end #We write our own histogram function. It takes as an input a single 1-dimensional array of data. #The number of bins in the histogram is determined automatically by using the Diaconis-Friedman rule. #The function returns two arrays: the mid-points of the bins and the (unnormalized) heights of the bars. function hstgram(data_sample::Array{Float64,1}) data_sorted=sort(data_sample) first=data_sorted[1] last=data_sorted[end] nmb=length(data_sorted) IQR=percentile(data_sorted,75)-percentile(data_sorted,25) bin_size_loc = 2*IQR*(nmb^(-1.0/3)) num_bins=Int(floor((last-first)/bin_size_loc)) bin_size=(last-first)/(num_bins) bin_end_points=[first+(i-1)*bin_size for i=1:(num_bins+1)] ahist_val=[length(data_sorted[data_sorted .< u]) for u in bin_end_points] hist_val=[ahist_val[i+1]-ahist_val[i] for i=1:num_bins] mid_bins=[first-bin_size/2+i*bin_size for i=1:num_bins] return mid_bins, hist_val end ## First, create data sampled from the standard univariate normal density. val=(x->((2*π)^(-1/2)*exp(-x^2/2))).(-3.3:0.05:3.3); Random.seed!(0xabcdef12); # if needed to generate the same samples #simulate 10,000 standard normals and generate the histogram begin nval=randn!(zeros(10000)); U,V=hstgram(nval); VV=V/(sum(V)*(U[2]-U[1])); end #check the length of the bin length(VV) begin plot(U.+(U[2]-U[1])/2,VV,line=(:steppre,1),linewidth=0.05,label="histogram") xlabel!("samples") ylabel!("frequency") plot!(-3.3:0.05:3.3,val,label="normal density") end #generate another sample begin nval=randn(10000); U,V=hstgram(nval); VV=V/(sum(V)*(U[2]-U[1])); plot(U.+(U[2]-U[1])/2,VV,line=(:steppre,1),linewidth=0.05,label="histogram") xlabel!("samples") ylabel!("frequency") plot!(-3.3:0.05:3.3,val,label="normal density") end # standard normals can be generated by sampling from the uniform distribution begin uval=rand(10000); nval=(x->sqrt(2)*erfinv(2*x-1)).(uval); U,V=hstgram(nval); VV=V/(sum(V)*(U[2]-U[1])); plot(U.+(U[2]-U[1])/2,VV,line=(:steppre,1),linewidth=0.05,label="histogram") xlabel!("samples") ylabel!("frequency") plot!(-3.3:0.05:3.3,val,label="normal density") end #simulate 10,000 standard bi-variate normals begin nval=randn!(zeros(10000)); nnval=randn!(zeros(10000)); end scatter(nval,nnval,ratio=1,markersize=1,label="") # to simulate bi-variate normals with a given covariance matrix # first create a fictitios covariance matrix begin A=rand(2,2); #Cov=A'A; # another alternative that always yields a positive definite matrix Cov=Symmetric(A) # may not produce a positive definite matrix end #check if Cov is positive definite; if not, repeat the last step eigvals(Cov) begin eigdCov=Diagonal(eigvals(Cov).^0.5) eigCov=eigvecs(Cov); # matrix of eigen vectors chlCov=cholesky(Cov); # Cholesky "square root" of Cov MM=eigdCov*eigCov; # Spectral "square root" of Cov end # check that the factorizations give what is expected Cov-MM'*MM Cov-chlCov.L*chlCov.U Cov-(chlCov.U)'*chlCov.U Cov-(chlCov.L)*(chlCov.L)' #this should be an orthogonal matrix eigCov'*eigCov #Transform the randomly generated standard bi-variate sample through the "square root" of the covariance matrix. #method 1 begin NN=hcat(nval,nnval)'; data_2_dim=MM'NN; scatter(data_2_dim[1,:],data_2_dim[2,:],ratio=1,markersize=1,label="") end #method 2 begin data_2_dim=(chlCov.L)*NN; scatter(data_2_dim[1,:],data_2_dim[2,:],ratio=1,markersize=1,label="") end <|start_filename|>Num-Prog-US-Call-Julia.jl<|end_filename|> ## MIT license (c) 2019 by <NAME> ## ## Julia 1.1.0. ## This code implements on single CPUs the numerical program for computing the exercise boundary ## and the price of an American-style call option described in Sec. 18.4 of ## "Stochastic Methods in Asset Pricing" (pp. 514-516). ## The same program is implemented in Python in Appendix B.3 of SMAP. ## begin ## The number if grid points in the time domain is set below. ## 5000 is excessively large and is meant to test Julia's capabilities. total_grid_no=5000 #this number must be divisible by pnmb include("Num-Prog-US-Call-Julia-functions.jl") nodes,weights=gausslegendre( 200 ); end #set the parameters in the model begin KK=40.0; # strike price sigma=0.3; delta=0.07; # dividend rate rr=0.02; # interest rate TT=0.5; # time to maturity in years DLT=TT/(total_grid_no); # distance between two grid points in the time domain ABSC=range(0.0,length=total_grid_no+1,stop=TT) # the entire grid on the time domain VAL=[max(KK,KK*(rr/delta)) for x in ABSC]; # first guess for the exercise boundary end ## run the main routine ## The third argument is an upper bound on the total iterations to run. ## The last two arguments control FastGaussQuadrature. ## masterF(start_iter,nmb_of_iter,conv_tol,K,σ,δ,r,T,Δ,no_grd_pnts,vls,nds,wghts) ## @time ABSC,VAL,conv,iterations=mainF(0,100,1.0e-5,KK,sigma,delta,rr,TT,DLT,total_grid_no,VAL,nodes,weights); ## 15.649206 seconds (406.60 M allocations: 9.109 GiB, 4.51% gc time) # The call to masterF can be repeated with the most recent VAL # and the second argument set to the number of already performed iterations. conv #The achived convergence #9.63110706209136e-6 iterations #23 f=CubicSplineInterpolation(ABSC,VAL,extrapolation_bc = Interpolations.Line()); begin using Plots pyplot() end begin plotgrid=ABSC[1]:.001:ABSC[end]; pval=[f(x) for x in plotgrid]; plot(plotgrid,pval,label="exercise boundary") xlabel!("real time") ylabel!("underlying spot price") end f(0) #53.58270125587188 ## The price of the EU at-the-money call with 0.5 years to expiry. EUcall(KK,TT,KK,sigma,rr,delta) #2.8378265020118754 ## The early exercise premium for a US at-the-money call with 0.5 years to expiry. begin an=[(0.5*(TT-0.0))*exp(-delta*((1/2)*(TT-0.0)*s+(1/2)*(0.0+TT)-0.0))*(KK*delta/2)*F(1,0.0,(1/2)*(TT-0.0)*s+(1/2)*(0.0+TT),f((1/2)*(TT-0.0)*s+(1/2)*(0.0+TT))/KK,rr,delta,sigma) for s in nodes] bn=[(0.5*(TT-0.0))*exp(-rr*((1/2)*(TT-0.0)*s+(1/2)*(0.0+TT)-0.0))*(rr*KK/2)*F(-1,0.0,(1/2)*(TT-0.0)*s+(1/2)*(0.0+TT),f((1/2)*(TT-0.0)*s+(1/2)*(0.0+TT))/KK,rr,delta,sigma) for s in nodes] aaa=weights'*an; bbb=weights'*bn; EEP=aaa-bbb; end EEP #0.10081943488743587 ## The early exercise premium for a US at-the-money call with 0.5 years to expiry. EUcall(KK,TT,KK,sigma,rr,delta)+EEP #2.938645936899311
AndrewLyasoff/SMAP
<|start_filename|>demo/test-object.h<|end_filename|> #ifndef TEST_OBJECT_H #define TEST_OBJECT_H #include <glib.h> #include <glib-object.h> #define TEST_OBJECT_TYPE (test_object_get_type()) #define TEST_OBJECT(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), TEST_OBJECT_TYPE, TestObject)) #define IS_TEST_OBJCET(obj) (G_TYPE_CHECK_INSTANCE_TYPE ((obj), TEST_OBJCET_TYPE)) #define TEST_OBJECT_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), TEST_OBJECT_TYPE, TestObjectClass)) #define IS_TEST_OBJECT_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), TEST_OBJECT_TYPE)) #define TEST_OBJECT_GET_CLASS(obj) (G_TYPE_INSTANCE_GET_CLASS ((obj), TEST_OBJECT_TYPE, TestObjectClass)) typedef struct _TestObject TestObject; typedef struct _TestObjectClass TestObjectClass; struct _TestObject { GObject parent; int len; gchar *str; gboolean equal; }; struct _TestObjectClass { GObjectClass parent_class; }; #endif <|start_filename|>tests/main.c<|end_filename|> /* * Copyright (c) <NAME>. All rights reserved. * * This file is part of clar, distributed under the ISC license. * For full terms see the included COPYING file. */ #include <glib.h> #include <glib-object.h> #include "clar_test.h" /* * Minimal main() for clar tests. * * Modify this with any application specific setup or teardown that you need. * The only required line is the call to `clar_test(argc, argv)`, which will * execute the test suite. If you want to check the return value of the test * application, main() should return the same value returned by clar_test(). */ #ifdef _WIN32 int __cdecl main(int argc, char *argv[]) #else int main(int argc, char *argv[]) #endif { #if !GLIB_CHECK_VERSION(2, 36, 0) g_type_init (); #endif #ifndef WIN32 signal (SIGPIPE, SIG_IGN); #endif /* Run the test suite */ return clar_test(argc, argv); } <|start_filename|>demo/test-object.c<|end_filename|> #include "test-object.h" G_DEFINE_TYPE (TestObject, test_object, G_TYPE_OBJECT); enum { PROP_0, PROP_LEN, PROP_STR, PROP_EQU, N_PROPERTIES }; static GParamSpec *obj_properties[N_PROPERTIES] = { NULL, }; static void test_object_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) { TestObject *self = TEST_OBJECT (object); switch (property_id) { case PROP_LEN: self->len = g_value_get_int (value); break; case PROP_STR: g_free (self->str); self->str = g_value_dup_string (value); break; case PROP_EQU: self->equal = g_value_get_boolean (value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void test_object_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) { TestObject *self = TEST_OBJECT (object); switch (property_id) { case PROP_LEN: g_value_set_int (value, self->len); break; case PROP_STR: g_value_set_string (value, self->str); break; case PROP_EQU: g_value_set_boolean (value, self->equal); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); } } static void test_object_dispose (GObject *object) { G_OBJECT_CLASS (test_object_parent_class)->dispose(object); } static void test_object_finalize (GObject *object) { TestObject *self = TEST_OBJECT (object); g_free(self->str); G_OBJECT_CLASS (test_object_parent_class)->finalize(object); } static void test_object_class_init(TestObjectClass *klass) { GObjectClass *gobject_class = G_OBJECT_CLASS (klass); gobject_class->set_property = test_object_set_property; gobject_class->get_property = test_object_get_property; gobject_class->dispose = test_object_dispose; gobject_class->finalize = test_object_finalize; obj_properties[PROP_LEN] = g_param_spec_int ("len", "", "", -1, 256, 0, G_PARAM_READWRITE); obj_properties[PROP_STR] = g_param_spec_string ("str", "", "", "Hello world!", G_PARAM_READWRITE); obj_properties[PROP_EQU] = g_param_spec_boolean ("equal", "", "", FALSE, G_PARAM_READWRITE); g_object_class_install_properties (gobject_class, N_PROPERTIES, obj_properties); } static void test_object_init(TestObject *self) { self->len = 0; self->str = g_strdup("Hello world!"); self->equal = FALSE; }
syncwerk/syncwerk-server-librpc
<|start_filename|>StepCounter.Android/Helpers/Utils.cs<|end_filename|> /* * My StepCounter: * Copyright (C) 2014 Refractored LLC | http://refractored.com * <NAME> | http://twitter.com/JamesMontemagno | http://MotzCod.es * * <NAME> | http://twitter.com/micjames6 | http://micjames.co.uk/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using Android.Content.PM; using Android.OS; using System.Globalization; namespace StepCounter.Helpers { public static class Utils { public static bool IsKitKatWithStepCounter(PackageManager pm) { // Require at least Android KitKat int currentApiVersion = (int)Build.VERSION.SdkInt; // Check that the device supports the step counter and detector sensors return currentApiVersion >= 19 && pm.HasSystemFeature (Android.Content.PM.PackageManager.FeatureSensorStepCounter) && pm.HasSystemFeature (Android.Content.PM.PackageManager.FeatureSensorStepDetector); } public static string DateString { get { var day = CultureInfo.CurrentCulture.DateTimeFormat.GetDayName(DateTime.Now.DayOfWeek); var month = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(DateTime.Now.Month); var dayNum = DateTime.Now.Day; if(Helpers.Settings.UseKilometeres) return day + " " + dayNum + " " + month; return day + " " + month+ " " + dayNum; } } public static string GetDateStaring(DateTime date) { string day = date.ToString("ddd"); string month = date.ToString("MMM"); int dayNum = date.Day; if(Helpers.Settings.UseKilometeres) return day + " " + dayNum + " " + month; return day + " " + month+ " " + dayNum; } public static bool IsSameDay{ get { return DateTime.Today.DayOfYear == Helpers.Settings.CurrentDay.DayOfYear && DateTime.Today.Year == Helpers.Settings.CurrentDay.Year; } } public static string FormatSteps (Int64 steps) { return steps.ToString ("N0"); } } } <|start_filename|>StepCounter/Helpers/Settings.cs<|end_filename|> using Foundation; namespace StepCounter.Helpers { public static class Settings { public static bool DistanceIsMetric { get { return NSUserDefaults.StandardUserDefaults.BoolForKey ("DistanceInKM"); } set { NSUserDefaults.StandardUserDefaults.SetBool (value, "DistanceInKM"); NSUserDefaults.StandardUserDefaults.Synchronize (); } } public static bool OverideDistance { get { return NSUserDefaults.StandardUserDefaults.BoolForKey ("OverideDistance"); } set { NSUserDefaults.StandardUserDefaults.SetBool (value, "OverideDistance"); NSUserDefaults.StandardUserDefaults.Synchronize (); } } public static bool HealthKitHeightEnabled { get { return NSUserDefaults.StandardUserDefaults.BoolForKey ("HealthKitHeightEnabled"); } set { NSUserDefaults.StandardUserDefaults.SetBool (value, "HealthKitHeightEnabled"); NSUserDefaults.StandardUserDefaults.Synchronize (); } } } } <|start_filename|>StepCounter.Android/Controls/IntEditTextPreference.cs<|end_filename|> /* * My StepCounter: * Copyright (C) 2014 Refractored LLC | http://refractored.com * <NAME> | http://twitter.com/JamesMontemagno | http://MotzCod.es * * <NAME> | http://twitter.com/micjames6 | http://micjames.co.uk/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Android.Content; using Android.Preferences; using Android.Util; namespace StepCounter.Controls { /// <summary> /// Enforces and integer be entered in the edit text preference /// </summary> public class IntEditTextPreference : EditTextPreference { public IntEditTextPreference (Context context) : base (context) { } public IntEditTextPreference (Context context, IAttributeSet attrs) : base (context, attrs) { } public IntEditTextPreference (Context context, IAttributeSet attrs, int defStyle) : base (context, attrs, defStyle) { } protected override string GetPersistedString (string defaultReturnValue) { return GetPersistedInt (1).ToString (); } protected override bool PersistString (string value) { int persistValue; int.TryParse (value, out persistValue); return PersistInt (persistValue); } } } <|start_filename|>StepCounter.iOS.UITest/StepCounterUITests.cs<|end_filename|> using System; using NUnit.Framework; using System.Reflection; using System.IO; using Xamarin.UITest.iOS; using Xamarin.UITest; using Xamarin.UITest.Queries; using System.Linq; namespace StepCounter.iOS.UITests { [TestFixture] public class GestureValidationTests { iOSApp _app; public string PathToIPA { get; set; } [TestFixtureSetUp] public void TestFixtureSetup() { string currentFile = new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath; FileInfo fi = new FileInfo(currentFile); string dir = fi.Directory.Parent.Parent.Parent.FullName; PathToIPA = Path.Combine(dir, "StepCounter", "bin", "iPhoneSimulator", "Debug", "StepCounteriOS.app"); } [SetUp] public void SetUp() { _app = ConfigureApp.iOS.AppBundle(PathToIPA).ApiKey("0c4aec6adb022f65167bde1dc14de100").StartApp(); } [Test] public void SwipeDownToReset() { _app.Repl(); } } } <|start_filename|>StepCounter.Android/Database/StepEntryDatabaseADO.cs<|end_filename|> /* * My StepCounter: * Copyright (C) 2014 Refractored LLC | http://refractored.com * <NAME> | http://twitter.com/JamesMontemagno | http://MotzCod.es * * <NAME> | http://twitter.com/micjames6 | http://micjames.co.uk/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using Mono.Data.Sqlite; using System.IO; using System.Data; using System.Globalization; namespace StepCounter.Database { public class StepEntryDatabase { static object locker = new object (); public SqliteConnection connection; public string path; public StepEntryDatabase (string dbPath) { var output = ""; path = dbPath; // create the tables bool exists = File.Exists (dbPath); if (!exists) { using (connection = new SqliteConnection ("Data Source=" + dbPath)) { connection.Open (); var commands = new[] { "CREATE TABLE [Items] (_id INTEGER PRIMARY KEY ASC, Steps BIGINT, Date NTEXT);" }; foreach (var command in commands) { using (var c = connection.CreateCommand ()) { c.CommandText = command; var i = c.ExecuteNonQuery (); } } connection.Close (); } } else { // already exists, do nothing. } Console.WriteLine (output); } /// <summary>Convert from DataReader to Task object</summary> StepEntry FromReader (SqliteDataReader r) { var t = new StepEntry (); t.ID = Convert.ToInt32 (r ["_id"]); t.Steps = Convert.ToInt64(r ["Steps"]); var date = r ["Date"].ToString (); var culture = CultureInfo.CreateSpecificCulture("en-US"); var styles = DateTimeStyles.None; DateTime dateOut; if (!DateTime.TryParse (date, culture, styles, out dateOut)) { //back compat, but will never come in here really. DateTime.TryParse (date, out dateOut); } t.Date = dateOut; return t; } public IEnumerable<StepEntry> GetItems (int count) { var tl = new List<StepEntry> (); lock (locker) { using (connection = new SqliteConnection ("Data Source=" + path)) { connection.Open (); using (var contents = connection.CreateCommand ()) { if (count == 0) contents.CommandText = "SELECT [_id], [Steps], [Date] from [Items]"; else contents.CommandText = "SELECT [_id], [Steps], [Date] from [Items] ORDER BY _id DESC LIMIT " + count; var r = contents.ExecuteReader (); while (r.Read ()) { tl.Add (FromReader (r)); } r.Close (); } connection.Close (); } } return tl; } public StepEntry GetItem (DateTime date) { var t = new StepEntry (); lock (locker) { using (connection = new SqliteConnection ("Data Source=" + path)) { connection.Open (); using (var command = connection.CreateCommand ()) { command.CommandText = "SELECT [_id], [Steps], [Date] from [Items] WHERE [Date] = ?"; var culture = CultureInfo.CreateSpecificCulture ("en-US"); command.Parameters.Add (new SqliteParameter (DbType.String) { Value = date.ToString ("MM/dd/yyyy", culture) }); var r = command.ExecuteReader (); while (r.Read ()) { t = FromReader (r); break; } r.Close (); } connection.Close (); } } return t; } public int SaveItem (StepEntry item) { int r; lock (locker) { if (item.ID != 0) { using (connection = new SqliteConnection ("Data Source=" + path)) { connection.Open (); using (var command = connection.CreateCommand ()) { command.CommandText = "UPDATE [Items] SET [Steps] = ?, [Date] = ? WHERE [_id] = ?;"; command.Parameters.Add (new SqliteParameter (DbType.Int64) { Value = item.Steps }); var culture = CultureInfo.CreateSpecificCulture ("en-US"); command.Parameters.Add (new SqliteParameter (DbType.String) { Value = item.Date.ToString ("MM/dd/yyyy", culture) }); command.Parameters.Add (new SqliteParameter (DbType.Int32) { Value = item.ID }); r = command.ExecuteNonQuery (); } connection.Close (); } return r; } else { using (connection = new SqliteConnection ("Data Source=" + path)) { connection.Open (); using (var command = connection.CreateCommand ()) { command.CommandText = "INSERT INTO [Items] ([Steps], [Date]) VALUES (? ,?)"; command.Parameters.Add (new SqliteParameter (DbType.Int64) { Value = item.Steps }); var culture = CultureInfo.CreateSpecificCulture ("en-US"); command.Parameters.Add (new SqliteParameter (DbType.String) { Value = item.Date.ToString ("MM/dd/yyyy", culture) }); r = command.ExecuteNonQuery (); } connection.Close (); } return r; } } } public int DeleteItem(int id) { lock (locker) { int r; using (connection = new SqliteConnection ("Data Source=" + path)) { connection.Open (); using (var command = connection.CreateCommand ()) { command.CommandText = "DELETE FROM [Items] WHERE [_id] = ?;"; command.Parameters.Add (new SqliteParameter (DbType.Int32) { Value = id }); r = command.ExecuteNonQuery (); } connection.Close (); } return r; } } } } <|start_filename|>StepCounter/Helpers/Keys.cs<|end_filename|> using System; namespace StepCounter.Helpers { public class Keys { public static string InsightsKey = ""; } } <|start_filename|>StepCounter.Android/Adapters/HistorySpinnerAdapter.cs<|end_filename|> /* * My StepCounter: * Copyright (C) 2014 Refractored LLC | http://refractored.com * <NAME> | http://twitter.com/JamesMontemagno | http://MotzCod.es * * <NAME> | http://twitter.com/micjames6 | http://micjames.co.uk/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Android.App; using Android.Views; using Android.Widget; using System; namespace StepCounter.Adapters { public class HistoryActionBarWrapper : Java.Lang.Object { public TextView Title { get; set; } public TextView Subtitle { get; set; } } public class HistoryDropDownWrapper : Java.Lang.Object { public TextView Title { get; set; } } public class HistorySpinnerAdapter : BaseAdapter, ISpinnerAdapter { public string Text1 { get; set; } public string Text2 { get; set; } private Activity context; string[] entries; public HistorySpinnerAdapter(Activity context) { Text1 = string.Empty; Text2 = string.Empty; this.context = context; entries = this.context.Resources.GetTextArray (Resource.Array.history_spinner); } public override int ViewTypeCount { get { return 1; } } public override Java.Lang.Object GetItem (int position) { return entries[position]; } //This view will appear in the action bar public override View GetView(int position, View convertView, ViewGroup parent) { HistoryActionBarWrapper wrapper = null; var view = convertView; if(view != null) wrapper = view.Tag as HistoryActionBarWrapper; if (wrapper == null) { view = context.LayoutInflater.Inflate(Resource.Layout.simple_spinner_item_2, null); wrapper = new HistoryActionBarWrapper(); wrapper.Title = view.FindViewById<TextView>(Android.Resource.Id.Text1); wrapper.Subtitle = view.FindViewById<TextView>(Android.Resource.Id.Text2); view.Tag = wrapper; } wrapper.Title.Text = Text1; wrapper.Subtitle.Text = Text2; return view; } //this is displayed in the spinner drop down public override View GetDropDownView (int position, View convertView, ViewGroup parent) { HistoryDropDownWrapper wrapper = null; var view = convertView; if(view != null) wrapper = view.Tag as HistoryDropDownWrapper; if (wrapper == null) { view = context.LayoutInflater.Inflate(Resource.Layout.simple_spinner_item_1, null); wrapper = new HistoryDropDownWrapper(); wrapper.Title = view.FindViewById<TextView>(Android.Resource.Id.Text1); view.Tag = wrapper; } var entry = entries[position]; wrapper.Title.Text = entry; return view; } public override int Count { get { return entries.Length; } } public override long GetItemId(int position) { return position; } } } <|start_filename|>StepCounter/Views/StepCounterController.designer.cs<|end_filename|> // WARNING // // This file has been generated automatically by Xamarin Studio from the outlets and // actions declared in your storyboard file. // Manual changes to this file will not be maintained. // using Foundation; using System; using System.CodeDom.Compiler; using UIKit; namespace StepCounter { [Register ("StepCounterController")] partial class StepCounterController { [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIButton btnDistance { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIButton btnShare { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UILabel lblCalories { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UILabel lblDate { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UILabel lblPercentage { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UILabel lblStepCount { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UILabel lblSteps { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UILabel lblTodayYouveTaken { get; set; } [Action ("btnDistance_TouchUpInside:")] [GeneratedCode ("iOS Designer", "1.0")] partial void btnDistance_TouchUpInside (UIButton sender); [Action ("btnShare_TouchUpInside:")] [GeneratedCode ("iOS Designer", "1.0")] partial void btnShare_TouchUpInside (UIButton sender); void ReleaseDesignerOutlets () { if (btnDistance != null) { btnDistance.Dispose (); btnDistance = null; } if (btnShare != null) { btnShare.Dispose (); btnShare = null; } if (lblCalories != null) { lblCalories.Dispose (); lblCalories = null; } if (lblDate != null) { lblDate.Dispose (); lblDate = null; } if (lblPercentage != null) { lblPercentage.Dispose (); lblPercentage = null; } if (lblStepCount != null) { lblStepCount.Dispose (); lblStepCount = null; } if (lblSteps != null) { lblSteps.Dispose (); lblSteps = null; } if (lblTodayYouveTaken != null) { lblTodayYouveTaken.Dispose (); lblTodayYouveTaken = null; } } } } <|start_filename|>StepCounter.Android/Services/StepServiceBinder.cs<|end_filename|> /* * My StepCounter: * Copyright (C) 2014 Refractored LLC | http://refractored.com * <NAME> | http://twitter.com/JamesMontemagno | http://MotzCod.es * * <NAME> | http://twitter.com/micjames6 | http://micjames.co.uk/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Android.OS; namespace StepCounter.Services { public class StepServiceBinder : Binder { StepService stepService; public StepServiceBinder (StepService service) { this.stepService = service; } public StepService StepService { get { return stepService; } } } } <|start_filename|>StepCounter/Views/SettingsViewController.designer.cs<|end_filename|> // WARNING // // This file has been generated automatically by Xamarin Studio from the outlets and // actions declared in your storyboard file. // Manual changes to this file will not be maintained. // using System; using Foundation; using UIKit; using System.CodeDom.Compiler; namespace StepCounter { [Register ("SettingsViewController")] partial class SettingsViewController { [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIBarButtonItem btnBack { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIImageView imgLogo { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UILabel lblBuiltWithXamarin { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UILabel lblByMJJM { get; set; } [Action ("btnBack_Activated:")] [GeneratedCode ("iOS Designer", "1.0")] partial void btnBack_Activated (UIBarButtonItem sender); void ReleaseDesignerOutlets () { if (btnBack != null) { btnBack.Dispose (); btnBack = null; } if (imgLogo != null) { imgLogo.Dispose (); imgLogo = null; } if (lblBuiltWithXamarin != null) { lblBuiltWithXamarin.Dispose (); lblBuiltWithXamarin = null; } if (lblByMJJM != null) { lblByMJJM.Dispose (); lblByMJJM = null; } } } } <|start_filename|>StepCounter.Android/Database/StepEntryRepositoryADO.cs<|end_filename|> /* * My StepCounter: * Copyright (C) 2014 Refractored LLC | http://refractored.com * <NAME> | http://twitter.com/JamesMontemagno | http://MotzCod.es * * <NAME> | http://twitter.com/micjames6 | http://micjames.co.uk/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.IO; namespace StepCounter.Database { public class StepEntryRepositoryADO { StepEntryDatabase db = null; protected static string dbLocation; protected static StepEntryRepositoryADO me; static StepEntryRepositoryADO () { me = new StepEntryRepositoryADO(); } protected StepEntryRepositoryADO () { // set the db location dbLocation = DatabaseFilePath; // instantiate the database db = new StepEntryDatabase(dbLocation); } public static string DatabaseFilePath { get { var sqliteFilename = "MyStepCounter.db3"; #if NETFX_CORE var path = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, sqliteFilename); #else #if SILVERLIGHT // Windows Phone expects a local path, not absolute var path = sqliteFilename; #else #if __ANDROID__ // Just use whatever directory SpecialFolder.Personal returns string libraryPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); #else // we need to put in /Library/ on iOS5.1 to meet Apple's iCloud terms // (they don't want non-user-generated data in Documents) string documentsPath = Environment.GetFolderPath (Environment.SpecialFolder.Personal); // Documents folder string libraryPath = Path.Combine (documentsPath, "..", "Library"); // Library folder #endif var path = Path.Combine (libraryPath, sqliteFilename); #endif #endif return path; } } public static StepEntry GetStepEntry(DateTime time) { return me.db.GetItem(time); } public static IEnumerable<StepEntry> GetStepEntries () { return me.db.GetItems(31); } public static int SaveStepEntry (StepEntry item) { return me.db.SaveItem(item); } public static int DeleteStepEntry(int id) { return me.db.DeleteItem(id); } } } <|start_filename|>StepCounter.Android/Adapters/HistoryItemAdapter.cs<|end_filename|> /* * My StepCounter: * Copyright (C) 2014 Refractored LLC | http://refractored.com * <NAME> | http://twitter.com/JamesMontemagno | http://MotzCod.es * * <NAME> | http://twitter.com/micjames6 | http://micjames.co.uk/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Android.App; using Android.Views; using Android.Widget; using StepCounter.Database; using System.Collections.Generic; using System; using StepCounter.Helpers; using StepCounter.Controls; namespace StepCounter.Adapters { public class HistoryWrapper : Java.Lang.Object { public ProgressView Completed { get; set; } public FrameLayout Remaining { get; set; } public TextView Steps { get; set; } public TextView Day {get;set;} public ImageView HighScore { get; set; } } public class HistoryAdapter : BaseAdapter<StepEntry> { private Activity context; private IList<StepEntry> entries; public HistoryAdapter(Activity context, IList<StepEntry> entries) { this.entries = entries; this.context = context; } public override View GetView(int position, View convertView, ViewGroup parent) { HistoryWrapper wrapper = null; var view = convertView; if(view != null) wrapper = view.Tag as HistoryWrapper; if (wrapper == null) { view = context.LayoutInflater.Inflate(Resource.Layout.item_history, null); wrapper = new HistoryWrapper(); wrapper.Completed = view.FindViewById<ProgressView>(Resource.Id.completed); wrapper.Remaining = view.FindViewById<FrameLayout>(Resource.Id.remaining); wrapper.Day = view.FindViewById<TextView>(Resource.Id.day); wrapper.Steps = view.FindViewById<TextView>(Resource.Id.steps); wrapper.HighScore = view.FindViewById<ImageView> (Resource.Id.high_score); view.Tag = wrapper; } var entry = entries[position]; wrapper.Day.Text = Utils.GetDateStaring (entry.Date); wrapper.Steps.Text = Utils.FormatSteps (entry.Steps); var percent = (int)Conversion.StepCountToPercentage(entry.Steps); if (percent > 100) percent = 100; else if (percent < 0) percent = 0; LinearLayout.LayoutParams paramCompleted = new LinearLayout.LayoutParams( 0, ViewGroup.LayoutParams.FillParent, percent); LinearLayout.LayoutParams paramRemaining = new LinearLayout.LayoutParams( 0, ViewGroup.LayoutParams.FillParent, 100 - percent); wrapper.Remaining.LayoutParameters = paramRemaining; wrapper.Completed.LayoutParameters = paramCompleted; wrapper.Completed.SetStepCount (entry.Steps); bool isHighScore = false; if (entry.Date.DayOfYear == Helpers.Settings.HighScoreDay.DayOfYear && entry.Date.Year == Helpers.Settings.HighScoreDay.Year) { if (Helpers.Settings.FirstDayOfUse.DayOfYear == Helpers.Settings.HighScoreDay.DayOfYear && Helpers.Settings.FirstDayOfUse.Year == Helpers.Settings.HighScoreDay.Year) { } else { isHighScore = true; } } wrapper.HighScore.Visibility = isHighScore ? ViewStates.Visible : ViewStates.Invisible; return view; } public override StepEntry this[int index] { get { return entries[index]; } } public override int Count { get { return entries.Count; } } public override long GetItemId(int position) { return position; } } } <|start_filename|>StepCounter.Android/Services/StepServiceConnection.cs<|end_filename|> /* * My StepCounter: * Copyright (C) 2014 Refractored LLC | http://refractored.com * <NAME> | http://twitter.com/JamesMontemagno | http://MotzCod.es * * <NAME> | http://twitter.com/micjames6 | http://micjames.co.uk/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Android.Content; using Android.OS; using StepCounter.Activities; namespace StepCounter.Services { public class StepServiceConnection : Java.Lang.Object, IServiceConnection { MainActivity activity; public StepServiceConnection (MainActivity activity) { this.activity = activity; } public void OnServiceConnected (ComponentName name, IBinder service) { var serviceBinder = service as StepServiceBinder; if (serviceBinder != null) { activity.Binder = serviceBinder; activity.IsBound = true; } } public void OnServiceDisconnected (ComponentName name) { activity.IsBound = false; } } } <|start_filename|>StepCounter/AppDelegate.cs<|end_filename|> using Foundation; using UIKit; namespace StepCounter.Views { [Register("AppDelegate")] public partial class AppDelegate : UIApplicationDelegate { public override UIWindow Window { get; set; } // This method is invoked when the application is about to move from active to inactive state. // OpenGL applications should use this method to pause. public override void OnResignActivation(UIApplication application) { } // This method should be used to release shared resources and it should store the application state. // If your application supports background exection this method is called instead of WillTerminate // when the user quits. public override void DidEnterBackground(UIApplication application) { } // This method is called as part of the transiton from background to active state. public override void WillEnterForeground(UIApplication application) { _stepCounter.RefreshView(); } // This method is called when the application is about to terminate. Save data, if needed. public override void WillTerminate(UIApplication application) { } public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions) { _stepCounter = new StepCounterController(new System.IntPtr()); UIApplication.SharedApplication.SetStatusBarStyle(UIStatusBarStyle.LightContent, false); Xamarin.Insights.Initialize(Helpers.Keys.InsightsKey); return true; } public override void OnActivated(UIApplication application) { if (_stepCounter == null) _stepCounter = new StepCounterController(new System.IntPtr()); _stepCounter.RefreshView(); } StepCounterController _stepCounter; } } <|start_filename|>StepCounter/Views/SettingsViewController.cs<|end_filename|> using System; using Foundation; using UIKit; using System.CodeDom.Compiler; namespace StepCounter { partial class SettingsViewController : UIViewController { public SettingsViewController (IntPtr handle) : base (handle) { } partial void btnBack_Activated(UIBarButtonItem sender) { this.DismissViewController(true, null); } } } <|start_filename|>StepCounter/Views/StepCounterController.cs<|end_filename|> using System; using System.Collections.Generic; using System.Drawing; using System.Globalization; using CoreAnimation; using CoreMotion; using Foundation; using UIKit; using StepCounter.Helpers; using StepCounter.Views; using CoreGraphics; using Xamarin; namespace StepCounter { partial class StepCounterController : UIViewController { private readonly StepManager _stepManager; private ProgressView _progressView; public StepCounterController(IntPtr handle) : base(handle) { _stepManager = new StepManager(); } private static string DateString { get { string day = DateTime.Now.DayOfWeek.ToString(); string month = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(DateTime.Now.Month); int dayNum = DateTime.Now.Day; return day + " " + dayNum + " " + month; } } public void RefreshView() { _stepManager.ForceUpdate(); } //Private Methods private void ConvertDistance() { Settings.DistanceIsMetric = Settings.DistanceIsMetric == false; _stepManager.ForceUpdate(); } private void TodaysStepCountChanged(nint stepCount) { //Setup Animation var stepCountAnimation = new CATransition(); stepCountAnimation.Duration = 0.7f; stepCountAnimation.Type = "kCATransitionFade"; stepCountAnimation.TimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.EaseInEaseOut); lblStepCount.Layer.AddAnimation(stepCountAnimation, "changeTextTransition"); lblStepCount.Text = stepCount.ToString(); var percentageCountAnimation = new CATransition(); percentageCountAnimation.Duration = 0.7f; percentageCountAnimation.Type = "kCATransitionFade"; percentageCountAnimation.TimingFunction = CAMediaTimingFunction.FromName(CAMediaTimingFunction.EaseInEaseOut); lblPercentage.Layer.AddAnimation(percentageCountAnimation, "changeTextTransition"); if (stepCount == 0) { lblCalories.Text = ""; } else { lblCalories.Text = Conversion.CaloriesBurnt(Conversion.StepsToMiles(stepCount)) + " Calories"; } //Percentage Complete Label if (stepCount <= 10000) { lblPercentage.Text = Conversion.StepCountToPercentage(stepCount) + "% Complete"; } else { lblPercentage.Text = "Completed"; } //Date lblDate.Text = DateString; //Distance if (Settings.DistanceIsMetric == false) { btnDistance.SetTitle(Conversion.StepsToMiles(stepCount).ToString("N2") + " mi", UIControlState.Normal); } else { btnDistance.SetTitle(Conversion.StepsToKilometers(stepCount).ToString("N2") + " km", UIControlState.Normal); } //Update progress filler view _progressView.SetStepCount(stepCount); if (stepCount <= 10000) { AnimateToPercentage(Conversion.StepCountToPercentage(stepCount)); } else { AnimateToPercentage(100); //I want to show something... } } void AnimateToPercentage(double targetPercentage) { var duration = 2.0 / 100 * targetPercentage; var inverseDuration = 100 - (100 / 100 * duration); UIView.AnimateNotify(inverseDuration, 0.0, 1.6f, 2.0f, 0, () => { _progressView.Frame = GetTargetPositionFromPercent(targetPercentage); }, null); _progressView.SetPercentage((byte)targetPercentage); //Stops flashing through red } void SetupParallax() { var xCenterEffect = new UIInterpolatingMotionEffect("center.x", UIInterpolatingMotionEffectType.TiltAlongHorizontalAxis) { MinimumRelativeValue = new NSNumber(-20), MaximumRelativeValue = new NSNumber(20) }; var yCenterEffect = new UIInterpolatingMotionEffect("center.y", UIInterpolatingMotionEffectType.TiltAlongVerticalAxis) { MinimumRelativeValue = new NSNumber(-20), MaximumRelativeValue = new NSNumber(20) }; var effectGroup = new UIMotionEffectGroup { MotionEffects = new UIMotionEffect[] { xCenterEffect, yCenterEffect } }; lblTodayYouveTaken.AddMotionEffect(effectGroup); lblStepCount.AddMotionEffect(effectGroup); lblSteps.AddMotionEffect(effectGroup); lblCalories.AddMotionEffect(effectGroup); lblDate.AddMotionEffect(effectGroup); lblPercentage.AddMotionEffect(effectGroup); btnDistance.AddMotionEffect(effectGroup); } CGRect GetTargetPositionFromPercent(double percentageComplete) { var height = View.Frame.Size.Height; var inversePercentage = 100 - (100 / 100 * percentageComplete); var position = (height / 100) * inversePercentage; return new CGRect(0, (float)position, _progressView.Frame.Size.Width, View.Frame.Size.Height); } #region View lifecycle public override void ViewDidAppear(bool animated) { base.ViewDidAppear(animated); if (Settings.OverideDistance == false) { NSLocale locale = NSLocale.CurrentLocale; Settings.DistanceIsMetric = locale.UsesMetricSystem; } SetupParallax(); View.UserInteractionEnabled = true; View.AddGestureRecognizer(new UISwipeGestureRecognizer(gesture => _stepManager.StartCountingFrom(DateTime.Now)) { Direction = UISwipeGestureRecognizerDirection.Down, }); View.AddGestureRecognizer(new UISwipeGestureRecognizer(gesture => _stepManager.StartCountingFrom(DateTime.Today)) { Direction = UISwipeGestureRecognizerDirection.Up, }); // Perform any additional setup after loading the view, typically from a nib. _progressView = new ProgressView(); _progressView.Frame = this.View.Frame; this.View.AddSubview(_progressView); this.View.SendSubviewToBack(_progressView); _stepManager.DailyStepCountChanged += TodaysStepCountChanged; #if !DEBUG if (CMStepCounter.IsStepCountingAvailable == false) { var unsupportedDevice = new UnsupportedDevice(); unsupportedDevice.View.Frame = View.Frame; View.Add(unsupportedDevice.View); } #endif btnDistance.SetTitleColor(UIColor.White, UIControlState.Normal); btnDistance.SetTitleColor(UIColor.White, UIControlState.Selected); btnDistance.SetTitleColor(UIColor.White, UIControlState.Highlighted); lblDate.Text = DateString; } public override UIStatusBarStyle PreferredStatusBarStyle() { return UIStatusBarStyle.LightContent; } #endregion partial void btnShare_TouchUpInside(UIButton sender) { UIGraphics.BeginImageContext(View.Frame.Size); View.DrawViewHierarchy(View.Frame, true); UIImage image = UIGraphics.GetImageFromCurrentImageContext(); UIGraphics.EndImageContext(); var shareText = string.Format("I've taken {0} steps today using #MyStepCounter!", lblStepCount.Text); var social = new UIActivityViewController(new NSObject[] { new NSString(shareText), image }, new UIActivity[] { new UIActivity() }); Insights.Track("SharedButtonPressed", "Steps Taken", lblStepCount.Text); PresentViewController(social, true, null); } partial void btnDistance_TouchUpInside(UIButton sender) { Settings.OverideDistance = true; ConvertDistance(); } } } <|start_filename|>StepCounter.Android/Database/StepEntryManager.cs<|end_filename|> /* * My StepCounter: * Copyright (C) 2014 Refractored LLC | http://refractored.com * <NAME> | http://twitter.com/JamesMontemagno | http://MotzCod.es * * <NAME> | http://twitter.com/micjames6 | http://micjames.co.uk/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; namespace StepCounter.Database { /// <summary> /// Manager classes are an abstraction on the data access layers /// </summary> public static class StepEntryManager { static StepEntryManager () { } public static StepEntry GetStepEntry(DateTime time) { return StepEntryRepositoryADO.GetStepEntry(time); } public static IList<StepEntry> GetStepEntries () { return new List<StepEntry>(StepEntryRepositoryADO.GetStepEntries()); } public static int SaveStepEntry(StepEntry item) { return StepEntryRepositoryADO.SaveStepEntry(item); } public static int DeleteStepEntry(int id) { return StepEntryRepositoryADO.DeleteStepEntry(id); } } } <|start_filename|>StepCounter.Android/Helpers/Settings.cs<|end_filename|> /* * My StepCounter: * Copyright (C) 2014 Refractored LLC | http://refractored.com * <NAME> | http://twitter.com/JamesMontemagno | http://MotzCod.es * * <NAME> | http://twitter.com/micjames6 | http://micjames.co.uk/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System.Globalization; using Android.Content; using Android.Preferences; using System; using Android.App; namespace StepCounter.Helpers { /// <summary> /// This is the Settings static class that can be used in your Core solution or in any /// of your client applications. All settings are laid out the same exact way with getters /// and setters. /// </summary> public static class Settings { private static SettingsHelper appSettings; private static SettingsHelper AppSettings { get { return appSettings ?? (appSettings = new SettingsHelper()); } } #region Setting Constants public const string DailyStepGoalKey = "DailyStepGoal"; public static readonly int DailyStepGoalDefault = 10000; public const string WeightKey = "Weight"; private static readonly int WeightDefault = 0; public const string CadenceKey = "Cadence3"; private static readonly string CadenceDefault = "3"; public const string EnhancedKey = "Enhanced"; private static readonly bool EnhancedDefault = false; public const string ProgressNotificationsKey = "ProgressNotifications"; private static readonly bool ProgressNotificationsDefault = true; public const string AccumulativeNotificationsKey = "AccumulativeNotifications"; private static readonly bool AccumulativeNotificationsDefault = true; private const string CurrentDayKey = "CurrentDay"; private static readonly DateTime CurrentDayDefault = DateTime.Today; private const string CurrentDayStepsKey = "CurrentDaySteps"; private static readonly Int64 CurrentDayStepsDefault = 0; private const string StepsBeforeTodayKey = "StepsBeforeToday"; private static readonly Int64 StepsBeforeTodayDefault = 0; private const string TotalStepsKey = "TotalSteps"; private static readonly Int64 TotalStepsDefault = 0; private const string GoalTodayMessageKey = "GoalTodayMessage"; private static readonly string GoalTodayMessageDefault = string.Empty; private const string GoalTodayDayKey = "GoalTodayDay"; private static readonly DateTime GoalTodayDayDefault = DateTime.Today.AddDays(-1); private const string NextGoalKey = "NextGoal"; private const Int64 NextGoalDefault = 100000; private const string HighScoreKey = "HighScore"; public const Int64 HighScoreDefault = 0; private const string HighScoreDayKey = "HighScoreDay"; private static readonly DateTime HighScoreDayDefault = DateTime.Today; private const string FirstDayOfUseKey = "FirstDayOfUse"; private static readonly DateTime FirstDayOfUseDefault = DateTime.Today; #endregion /// <summary> /// Gets or sets the next goal. for total /// </summary> /// <value>The next goal.</value> public static Int64 NextGoal { get { return AppSettings.GetValueOrDefault(NextGoalKey, NextGoalDefault); } set { //if value has changed then save it! if (AppSettings.AddOrUpdateValue(NextGoalKey, value)) AppSettings.Save(); } } /// <summary> /// Gets or sets a value indicating whether to show progress notifications. /// </summary> /// <value><c>true</c> if progress notifications; otherwise, <c>false</c>.</value> public static bool ProgressNotifications { get { return AppSettings.GetValueOrDefault(ProgressNotificationsKey, ProgressNotificationsDefault); } set { //if value has changed then save it! if (AppSettings.AddOrUpdateValue(ProgressNotificationsKey, value)) AppSettings.Save(); } } /// <summary> /// Gets or sets a value indicating whether to show accumulative notifications. /// </summary> /// <value><c>true</c> if accumulative notifications; otherwise, <c>false</c>.</value> public static bool AccumulativeNotifications { get { return AppSettings.GetValueOrDefault(AccumulativeNotificationsKey, AccumulativeNotificationsDefault); } set { //if value has changed then save it! if (AppSettings.AddOrUpdateValue(AccumulativeNotificationsKey, value)) AppSettings.Save(); } } /// <summary> /// Gets or sets the high score day. /// </summary> /// <value>The high score day.</value> public static DateTime FirstDayOfUse { get { var firstDay = AppSettings.GetValueOrDefault (FirstDayOfUseKey, (long)-1); if (firstDay == -1) { FirstDayOfUse = DateTime.Today; CurrentDay = DateTime.Today; return DateTime.Today; } else return new DateTime(firstDay); } set { //if value has changed then save it! if (AppSettings.AddOrUpdateValue(FirstDayOfUseKey, value)) AppSettings.Save(); } } /// <summary> /// Ensure that high score is not today /// </summary> /// <value><c>true</c> if today is high score; otherwise, <c>false</c>.</value> public static bool TodayIsHighScore { get { //if first day then always return false; if (FirstDayOfUse.DayOfYear == HighScoreDay.DayOfYear && FirstDayOfUse.Year == HighScoreDay.Year) return false; //else is same day. return DateTime.Today.DayOfYear == HighScoreDay.DayOfYear && DateTime.Today.Year == HighScoreDay.Year; } } /// <summary> /// Gets or sets the goal message to display to user /// </summary> /// <value>The goal today message.</value> public static string GoalTodayMessage { get { return AppSettings.GetValueOrDefault(GoalTodayMessageKey, GoalTodayMessageDefault); } set { //if value has changed then save it! if (AppSettings.AddOrUpdateValue(GoalTodayMessageKey, value)) AppSettings.Save(); } } /// <summary> /// Gets or sets the high score. /// </summary> /// <value>The high score.</value> public static Int64 HighScore { get { return AppSettings.GetValueOrDefault(HighScoreKey, HighScoreDefault); } set { //if value has changed then save it! if (AppSettings.AddOrUpdateValue(HighScoreKey, value)) AppSettings.Save(); } } /// <summary> /// Gets or sets the goal today day. /// Only display messages if it is currenlty the same day. /// </summary> /// <value>The goal today day.</value> public static DateTime GoalTodayDay { get { return AppSettings.GetValueOrDefault(GoalTodayDayKey, GoalTodayDayDefault); } set { //if value has changed then save it! if (AppSettings.AddOrUpdateValue(GoalTodayDayKey, value)) AppSettings.Save(); } } /// <summary> /// Gets or sets the high score day. /// </summary> /// <value>The high score day.</value> public static DateTime HighScoreDay { get { return AppSettings.GetValueOrDefault(HighScoreDayKey, HighScoreDayDefault); } set { //if value has changed then save it! if (AppSettings.AddOrUpdateValue(HighScoreDayKey, value)) AppSettings.Save(); } } /// <summary> /// Gets or sets the day we are currently tracking /// </summary> /// <value>The current day.</value> public static DateTime CurrentDay { get { return AppSettings.GetValueOrDefault(CurrentDayKey, CurrentDayDefault); } set { //if value has changed then save it! if (AppSettings.AddOrUpdateValue(CurrentDayKey, value)) AppSettings.Save(); } } /// <summary> /// Gets or sets the steps before today. /// </summary> /// <value>The steps before today.</value> public static Int64 StepsBeforeToday { get { return AppSettings.GetValueOrDefault(StepsBeforeTodayKey, StepsBeforeTodayDefault); } set { //if value has changed then save it! if (AppSettings.AddOrUpdateValue(StepsBeforeTodayKey, value)) AppSettings.Save(); } } /// <summary> /// Gets or sets the cadence. (pace of walking) /// </summary> /// <value>The cadence.</value> public static string Cadence { get { return AppSettings.GetValueOrDefault(CadenceKey, CadenceDefault); } set { //if value has changed then save it! if (AppSettings.AddOrUpdateValue(CadenceKey, value)) AppSettings.Save(); } } /// <summary> /// Gets or sets the current day steps. /// </summary> /// <value>The current day steps.</value> public static Int64 CurrentDaySteps { get { return AppSettings.GetValueOrDefault(CurrentDayStepsKey, CurrentDayStepsDefault); } set { //if value has changed then save it! if (AppSettings.AddOrUpdateValue(CurrentDayStepsKey, value)) AppSettings.Save(); } } /// <summary> /// Gets or sets the total steps since the beginning of tracking /// </summary> /// <value>The total steps.</value> public static Int64 TotalSteps { get { return AppSettings.GetValueOrDefault(TotalStepsKey, TotalStepsDefault); } set { //if value has changed then save it! if (AppSettings.AddOrUpdateValue(TotalStepsKey, value)) AppSettings.Save(); } } /// <summary> /// Gets or sets the weight. (used for calulations) /// </summary> /// <value>The weight.</value> public static int Weight { get { return AppSettings.GetValueOrDefault(WeightKey, WeightDefault); } set { //if value has changed then save it! if (AppSettings.AddOrUpdateValue(WeightKey, value)) AppSettings.Save(); } } /// <summary> /// Gets or sets a value indicating whether we want to use enhanced tracking /// </summary> /// <value><c>true</c> if enhanced; otherwise, <c>false</c>.</value> public static bool Enhanced { get { return AppSettings.GetValueOrDefault(EnhancedKey, EnhancedDefault); } set { //if value has changed then save it! if (AppSettings.AddOrUpdateValue(EnhancedKey, value)) AppSettings.Save(); } } /// <summary> /// Gets a value indicating whether to use kilometeres. /// </summary> /// <value><c>true</c> if use kilometeres; otherwise, <c>false</c>.</value> public static bool UseKilometeres { get { return CultureInfo.CurrentCulture.Name != "en-US"; } } private class SettingsHelper { public static ISharedPreferences SharedPreferences { get; set; } private static ISharedPreferencesEditor SharedPreferencesEditor { get; set; } private readonly object locker = new object(); public SettingsHelper() { SharedPreferences = PreferenceManager.GetDefaultSharedPreferences(Application.Context); SharedPreferencesEditor = SharedPreferences.Edit(); } /// <summary> /// Gets the current value or the default that you specify. /// </summary> /// <typeparam name="T">Vaue of t (bool, int, float, long, string)</typeparam> /// <param name="key">Key for settings</param> /// <param name="defaultValue">default value if not set</param> /// <returns>Value or default</returns> public T GetValueOrDefault<T>(string key, T defaultValue = default(T)) { lock (locker) { Type typeOf = typeof(T); if (typeOf.IsGenericType && typeOf.GetGenericTypeDefinition() == typeof(Nullable<>)) { typeOf = Nullable.GetUnderlyingType(typeOf); } object value = null; var typeCode = Type.GetTypeCode(typeOf); switch (typeCode) { case TypeCode.Boolean: value = SharedPreferences.GetBoolean(key, Convert.ToBoolean(defaultValue)); break; case TypeCode.Int64: value = SharedPreferences.GetLong(key, Convert.ToInt64(defaultValue)); break; case TypeCode.String: value = SharedPreferences.GetString(key, Convert.ToString(defaultValue)); break; case TypeCode.Int32: value = SharedPreferences.GetInt(key, Convert.ToInt32(defaultValue)); break; case TypeCode.Single: value = SharedPreferences.GetFloat(key, Convert.ToSingle(defaultValue)); break; case TypeCode.DateTime: var ticks = SharedPreferences.GetLong(key, -1); if (ticks == -1) value = defaultValue; else value = new DateTime(ticks); break; } return null != value ? (T)value : defaultValue; } } /// <summary> /// Adds or updates a value /// </summary> /// <param name="key">key to update</param> /// <param name="value">value to set</param> /// <returns>True if added or update and you need to save</returns> public bool AddOrUpdateValue(string key, object value) { lock (locker) { Type typeOf = value.GetType(); if (typeOf.IsGenericType && typeOf.GetGenericTypeDefinition() == typeof(Nullable<>)) { typeOf = Nullable.GetUnderlyingType(typeOf); } var typeCode = Type.GetTypeCode(typeOf); switch (typeCode) { case TypeCode.Boolean: SharedPreferencesEditor.PutBoolean(key, Convert.ToBoolean(value)); break; case TypeCode.Int64: SharedPreferencesEditor.PutLong(key, Convert.ToInt64(value)); break; case TypeCode.String: SharedPreferencesEditor.PutString(key, Convert.ToString(value)); break; case TypeCode.Int32: SharedPreferencesEditor.PutInt(key, Convert.ToInt32(value)); break; case TypeCode.Single: SharedPreferencesEditor.PutFloat(key, Convert.ToSingle(value)); break; case TypeCode.DateTime: SharedPreferencesEditor.PutLong(key, ((DateTime)(object)value).Ticks); break; } } return true; } /// <summary> /// Saves out all current settings /// </summary> public void Save() { lock (locker) { SharedPreferencesEditor.Commit(); } } } } } <|start_filename|>StepCounter.Android/Activities/MainActivity.cs<|end_filename|> /* * My StepCounter: * Copyright (C) 2014 Refractored LLC | http://refractored.com * <NAME> | http://twitter.com/JamesMontemagno | http://MotzCod.es * * <NAME> | http://twitter.com/micjames6 | http://micjames.co.uk/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Android.App; using Android.Content; using Android.OS; using Android.Widget; using Android.Content.PM; using System; using StepCounter.Helpers; using StepCounter.Controls; using Android.Views.Animations; using StepCounter.Services; using System.Collections.Generic; namespace StepCounter.Activities { [Activity (Label = "Step Counter", Icon="@drawable/ic_launcher", LaunchMode = LaunchMode.SingleTask, MainLauncher = true, Theme = "@style/MyTheme", ScreenOrientation = ScreenOrientation.Portrait)] public class MainActivity : Activity { public bool IsBound { get; set; } private StepServiceBinder binder; private bool registered; private string calorieString, distanceString, percentString, completedString; private ProgressView progressView; private FrameLayout topLayer; private bool canAnimate = true; private bool fullAnimation = true; private Handler handler; private bool firstRun = true; private ImageView highScore, warning; public StepServiceBinder Binder { get{ return binder; } set { binder = value; if (binder == null) return; HandlePropertyChanged (null, new System.ComponentModel.PropertyChangedEventArgs ("StepsToday")); if(registered) binder.StepService.PropertyChanged -= HandlePropertyChanged; binder.StepService.PropertyChanged += HandlePropertyChanged; registered = true; } } private StepServiceConnection serviceConnection; //private int testSteps = 1; private TextView stepCount, calorieCount, distance, percentage; private TranslateAnimation animation; private float height, lastY; protected override void OnCreate (Bundle savedInstanceState) { base.OnCreate (savedInstanceState); // Set our view from the "main" layout resource SetContentView (Resource.Layout.main); topLayer = FindViewById<FrameLayout> (Resource.Id.top_layer); handler = new Handler (); if (!Utils.IsKitKatWithStepCounter(PackageManager)) { //no step detector detected :( var counter_layout = FindViewById<FrameLayout> (Resource.Id.counter_layout); var no_sensor = FindViewById<LinearLayout> (Resource.Id.no_sensor_box); var sensor_image = FindViewById<ImageView> (Resource.Id.no_sensor_image); sensor_image.SetImageResource (Resource.Drawable.ic_unsupporteddevice); no_sensor.Visibility = Android.Views.ViewStates.Visible; counter_layout.Visibility = Android.Views.ViewStates.Gone; this.Title = Resources.GetString (Resource.String.app_name); handler.PostDelayed (() => AnimateTopLayer (0), 500); return; } stepCount = FindViewById<TextView> (Resource.Id.stepcount); calorieCount = FindViewById<TextView> (Resource.Id.calories); distance = FindViewById<TextView> (Resource.Id.distance); percentage = FindViewById<TextView> (Resource.Id.percentage); progressView = FindViewById<ProgressView> (Resource.Id.progressView); highScore = FindViewById<ImageView> (Resource.Id.high_score); warning = FindViewById<ImageView> (Resource.Id.warning); calorieString = Resources.GetString (Resource.String.calories); distanceString = Resources.GetString (Helpers.Settings.UseKilometeres ? Resource.String.kilometeres : Resource.String.miles); percentString = Resources.GetString (Resource.String.percent_complete); completedString = Resources.GetString (Resource.String.completed); this.Title = Utils.DateString; handler.PostDelayed (() => UpdateUI (), 500); StartStepService (); //for testing /*stepCount.Clickable = true; stepCount.Click += (object sender, EventArgs e) => { if(binder != null) { //if(testSteps == 1) // testSteps = (int)binder.StepService.StepsToday; testSteps += 100; if(testSteps > 10000) testSteps += 1000; //binder.StepService.AddSteps(testSteps); HandlePropertyChanged (null, new System.ComponentModel.PropertyChangedEventArgs ("StepsToday")); } };*/ } private void StartStepService() { try { var service = new Intent (this, typeof(StepService)); var componentName = StartService (service); } catch(Exception ex) { } } private void AnimateTopLayer(float percent, bool force = false) { if (!canAnimate) return; if (height <= 0) { height = (float)topLayer.MeasuredHeight; if (height <= 0) return; } canAnimate = false; var start = animation == null ? -height : lastY; var time = 300; IInterpolator interpolator; if (percent < 0) percent = 0; else if (percent > 100) percent = 100; lastY = -height * (percent / 100F); if ((int)lastY == (int)start && !force) { canAnimate = true; return; } //is new so do bound, else linear if (fullAnimation || !Utils.IsSameDay) { interpolator = new BounceInterpolator (); time = 3000; fullAnimation = false; } else { interpolator = new LinearInterpolator (); } animation = new TranslateAnimation (Dimension.Absolute, 0, Dimension.Absolute, 0, Dimension.Absolute, start, Dimension.Absolute, lastY); animation.Duration = time; animation.Interpolator = interpolator; animation.AnimationEnd += (object sender, Animation.AnimationEndEventArgs e) => { canAnimate = true; }; animation.FillAfter = true; topLayer.StartAnimation(animation); if (topLayer.Visibility != Android.Views.ViewStates.Visible) topLayer.Visibility = Android.Views.ViewStates.Visible; } protected override void OnStop () { base.OnStop (); if (IsBound) { UnbindService (serviceConnection); IsBound = false; } } protected override void OnDestroy () { base.OnDestroy (); if (IsBound) { UnbindService (serviceConnection); IsBound = false; } } protected override void OnStart () { base.OnStart (); if (!Utils.IsKitKatWithStepCounter (PackageManager)) { Console.WriteLine("Not compatible with sensors, stopping service."); return; } if(!firstRun) StartStepService (); if (IsBound) return; var serviceIntent = new Intent (this, typeof(StepService)); serviceConnection = new StepServiceConnection (this); BindService (serviceIntent, serviceConnection, Bind.AutoCreate); } protected override void OnPause () { base.OnPause (); if (registered && binder != null) { binder.StepService.PropertyChanged -= HandlePropertyChanged; registered = false; } } protected override void OnResume () { base.OnResume (); if (!firstRun) { if (handler == null) handler = new Handler (); handler.PostDelayed (() => UpdateUI (true), 500); } firstRun = false; if (!registered && binder != null) { binder.StepService.PropertyChanged += HandlePropertyChanged; registered = true; } } public override bool OnCreateOptionsMenu (Android.Views.IMenu menu) { MenuInflater.Inflate (Resource.Menu.main, menu); return base.OnCreateOptionsMenu (menu); } public override bool OnOptionsItemSelected (Android.Views.IMenuItem item) { switch (item.ItemId) { case Resource.Id.menu_settings: var intent = new Intent (this, typeof(SettingsActivity)); StartActivity (intent); return true; case Resource.Id.menu_history: var intent2 = new Intent (this, typeof(HistoryActivity)); StartActivity (intent2); return true; case Resource.Id.menu_share: var intent3 = new Intent(Intent.ActionSend); intent3.PutExtra(Intent.ExtraText,string.Format(Resources.GetString(Resource.String.share_steps_today), stepCount.Text)); intent3.SetType("text/plain"); StartActivity(Intent.CreateChooser(intent3, Resources.GetString(Resource.String.share_steps_on))); return true; } return base.OnOptionsItemSelected (item); } void HandlePropertyChanged (object sender, System.ComponentModel.PropertyChangedEventArgs e) { if (e.PropertyName != "StepsToday") return; UpdateUI (); } private void UpdateUI(bool force = false) { if (progressView == null) return; RunOnUiThread (() => { Int64 steps = 0; var showWaring = false; if(Binder == null){ if(Utils.IsSameDay) steps = Helpers.Settings.CurrentDaySteps; }else{ steps = Binder.StepService.StepsToday; showWaring = binder.StepService.WarningState; } progressView.SetStepCount(steps); stepCount.Text = Utils.FormatSteps(steps); var miles = Conversion.StepsToMiles(steps); distance.Text = string.Format(distanceString, Helpers.Settings.UseKilometeres ? Conversion.StepsToKilometers(steps).ToString("N2") : miles.ToString("N2")); var lbs = Helpers.Settings.UseKilometeres ? Helpers.Settings.Weight * 2.20462 : Helpers.Settings.Weight; calorieCount.Text = string.Format(calorieString, Helpers.Settings.Enhanced ? Conversion.CaloriesBurnt(miles, (float)lbs, Helpers.Settings.Cadence) : Conversion.CaloriesBurnt(miles)); var percent = Conversion.StepCountToPercentage(steps); var percent2 = percent / 100; if(steps <= 10000) percentage.Text = steps == 0 ? string.Empty : string.Format(percentString, percent2.ToString("P2")); else percentage.Text = completedString; //set high score day highScore.Visibility = Settings.TodayIsHighScore ? Android.Views.ViewStates.Visible : Android.Views.ViewStates.Invisible; //detect warning warning.Visibility = showWaring ? Android.Views.ViewStates.Visible : Android.Views.ViewStates.Invisible; //Show daily goal message. if(!string.IsNullOrWhiteSpace(Settings.GoalTodayMessage) && Settings.GoalTodayDay.DayOfYear == DateTime.Today.DayOfYear && Settings.GoalTodayDay.Year == DateTime.Today.Year){ Toast.MakeText(this, Settings.GoalTodayMessage, ToastLength.Long).Show(); Settings.GoalTodayMessage = string.Empty; } AnimateTopLayer((float)percent, force); this.Title = Utils.DateString; }); } } } <|start_filename|>StepCounter/Helpers/Fonts.cs<|end_filename|> using System; using System.Collections.Generic; using System.Linq; using System.Text; using Foundation; using UIKit; namespace StepCounter.Helpers { public static class Fonts { public static UIFont SemiBold { get { return UIFont.FromName("Raleway-SemiBold", 75); } } public static UIFont Light { get { return UIFont.FromName("Raleway-Light", 18); } } } } <|start_filename|>StepCounter.Android/Services/BootReceiver.cs<|end_filename|> /* * My StepCounter: * Copyright (C) 2014 Refractored LLC | http://refractored.com * <NAME> | http://twitter.com/JamesMontemagno | http://MotzCod.es * * <NAME> | http://twitter.com/micjames6 | http://micjames.co.uk/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Android.App; using Android.Content; namespace StepCounter.Services { [BroadcastReceiver] [IntentFilter(new []{"android.intent.action.BOOT_COMPLETED", "android.intent.action.MY_PACKAGE_REPLACED"})] public class BootReceiver : BroadcastReceiver { public override void OnReceive (Context context, Intent intent) { var stepServiceIntent = new Intent(context, typeof(StepService)); context.StartService(stepServiceIntent); } } } <|start_filename|>StepCounter/Views/Custom Views/BackgroundView.cs<|end_filename|> using System; using UIKit; using Foundation; using System.Drawing; using CoreGraphics; using System.ComponentModel; namespace StepCounter { [Register("BackgroundView"), DesignTimeVisible(true)] public class BackgroundView : UIView { #region constructor public BackgroundView () { } public BackgroundView (IntPtr handle) : base (handle) { Initialize (); } private void Initialize () { } #endregion //Generated with PaintCode 2.2 public override void Draw(CGRect rect) { base.Draw(rect); // General Declarations var colorSpace = CGColorSpace.CreateDeviceRGB(); var context = UIGraphics.GetCurrentContext(); // Color Declarations var darkBlue = UIColor.FromRGBA(0.053f, 0.123f, 0.198f, 1.000f); var lightBlue = UIColor.FromRGBA(0.191f, 0.619f, 0.845f, 1.000f); // Gradient Declarations var backgroundGradientColors = new CGColor [] {lightBlue.CGColor, darkBlue.CGColor}; var backgroundGradientLocations = new nfloat [] {0.0f, 1.0f}; var backgroundGradient = new CGGradient(colorSpace, backgroundGradientColors, backgroundGradientLocations); // Rectangle Drawing var rectangleRect = new CGRect(rect.GetMinX() + (float)Math.Floor(rect.Width * -0.12917f + 0.5f), rect.GetMinY() + (float)Math.Floor(rect.Height * 0.00000f + 0.5f), (float)Math.Floor(rect.Width * 1.00000f + 0.5f) - (float)Math.Floor(rect.Width * -0.12917f + 0.5f), (float)Math.Floor(rect.Height * 1.00000f + 0.5f) - (float)Math.Floor(rect.Height * 0.00000f + 0.5f)); var rectanglePath = UIBezierPath.FromRect(rectangleRect); context.SaveState(); rectanglePath.AddClip(); context.DrawLinearGradient(backgroundGradient, new PointF((float)rectangleRect.GetMidX(), (float)rectangleRect.GetMinY()), new PointF((float)rectangleRect.GetMidX(), (float)rectangleRect.GetMaxY()), 0); context.RestoreState(); } } } <|start_filename|>StepCounter/Views/UnsupportedDevice.cs<|end_filename|> using UIKit; namespace StepCounter.Views { public partial class UnsupportedDevice : UIViewController { public UnsupportedDevice() : base("UnsupportedDevice", null) { } public override void AwakeFromNib() { base.AwakeFromNib(); lblUnsupportedDevice.Font = UIFont.FromName("Raleway-Light", 18); View.BackgroundColor = UIColor.FromRGB(252, 61, 57); } public override void ViewDidLoad() { base.ViewDidLoad(); // Perform any additional setup after loading the view, typically from a nib. btnMoreInfo.Hidden = true; } } } <|start_filename|>StepCounter.Android/Controls/FontFitTextView.cs<|end_filename|> /* * My StepCounter: * Copyright (C) 2014 Refractored LLC | http://refractored.com * <NAME> | http://twitter.com/JamesMontemagno | http://MotzCod.es * * <NAME> | http://twitter.com/micjames6 | http://micjames.co.uk/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using Android.Widget; using Android.Content; using Android.Util; using Android.Runtime; using Android.Graphics; namespace StepCounter.Controls { public class FontFitTextView : TextView { public FontFitTextView (Context context) : base(context) { Initialise(); } public FontFitTextView(Context context, IAttributeSet attrs) : base(context, attrs) { Initialise(); } public FontFitTextView(Context context, IAttributeSet attrs, int defStyle) : base(context, attrs, defStyle) { } public FontFitTextView(IntPtr pointer, JniHandleOwnership handle) : base (pointer, handle) { } Android.Graphics.Paint mTestPaint { get; set; } void Initialise () { mTestPaint = new Paint(); mTestPaint.Set(this.Paint); //max size defaults to the initially specified text size unless it is too small } /* Re size the font so the specified text fits in the text box * assuming the text box is the specified width. */ private void RefitText(String text, int textWidth) { if (textWidth <= 0) return; int targetWidth = textWidth - this.PaddingLeft - this.PaddingRight; float hi = (float)MeasuredHeight * .8f; float lo = 2; float threshold = 0.5f; // How close we have to be mTestPaint.Set(this.Paint); while((hi - lo) > threshold) { float size = (hi+lo)/2; mTestPaint.TextSize = (size); if(mTestPaint.MeasureText(text) >= targetWidth) hi = size; // too big else lo = size; // too small } // Use lo so that we undershoot rather than overshoot this.SetTextSize(ComplexUnitType.Px, lo); } protected override void OnMeasure (int widthMeasureSpec, int heightMeasureSpec) { base.OnMeasure (widthMeasureSpec, heightMeasureSpec); int parentWidth = MeasureSpec.GetSize(widthMeasureSpec); int height = MeasuredHeight; RefitText(Text.ToString(), parentWidth); this.SetMeasuredDimension(parentWidth, height); } protected override void OnTextChanged (Java.Lang.ICharSequence text, int start, int before, int after) { RefitText(text.ToString(), Width); } protected override void OnSizeChanged (int w, int h, int oldw, int oldh) { if (w != oldw) { RefitText(Text, w); } } } } <|start_filename|>StepCounter.Android/Controls/ProgressViewCommon.cs<|end_filename|> using System; #if __ANDROID__ using Android.Graphics; #elif __IOS__ using MonoTouch.UIKit; using Color = MonoTouch.UIKit.UIColor; #endif #if __ANDROID__ namespace StepCounter.Controls #elif __IOS__ namespace StepCounter.Views #endif { public partial class ProgressView { private const int TotalStepsToTake = 10000; private byte[] _blueArray; private byte[] _greenArray; private byte[] _redArray; private Color _tmpCol; void Initialize () { //TODO Find a nicer way to deal with using nicer colours. _redArray = new byte[101] { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 251, 247, 244, 240, 237, 233, 229, 226, 222, 219, 215, 212, 208, 204, 201, 197, 194, 190, 186, 183, 179, 176, 172, 169, 165, 161, 158, 154, 151, 147, 144, 140, 136, 133, 129, 126, 122, 118, 115, 111, 108, 104, 101, 97, 93, 90, 86, 83, 79, 76, 76 }; _greenArray = new byte[101] { 59, 61, 64, 67, 70, 73, 76, 79, 82, 85, 88, 90, 93, 96, 99, 102, 105, 108, 111, 114, 117, 119, 122, 125, 128, 131, 134, 137, 140, 143, 146, 148, 151, 154, 157, 160, 163, 166, 169, 172, 175, 177, 180, 183, 186, 189, 192, 195, 198, 201, 204, 204, 204, 204, 205, 205, 205, 205, 206, 206, 206, 206, 207, 207, 207, 207, 208, 208, 208, 208, 209, 209, 209, 209, 210, 210, 210, 210, 211, 211, 211, 211, 212, 212, 212, 212, 213, 213, 213, 213, 214, 214, 214, 214, 215, 215, 215, 215, 216, 217, 217 }; _blueArray = new byte[101] { 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 09, 08, 07, 06, 05, 04, 03, 02, 01, 0, 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100, 100 }; SetStepCount (0); } public void SetStepCount(Int64 count) { if (count <= 0) { SetPercentage (0); return; } var percentage = count > 10000 ? 100F : (float)count/(float)TotalStepsToTake *100F; SetPercentage((int)percentage); } public void SetStepCount(int count) { if (count <= 0) { SetPercentage (0); return; } var percentage = count > 10000 ? 100F : (float)count/(float)TotalStepsToTake *100F; SetPercentage((int)percentage); } public void SetPercentage(int percentage) { var col = CalculateColor(percentage); #if __ANDROID__ this.SetBackgroundColor(col); #elif __IOS__ if (col != null) View.BackgroundColor = col; #endif } //TODO Convert to HSV or HSB to bump the saturation to something more iOS looking. public Color CalculateColor(Int64 percentage) { if ((percentage < 0) || (percentage > 100)) return _tmpCol; #if __ANDROID__ var tempCol = new Color(_redArray[percentage], _greenArray[percentage], _blueArray[percentage]); #elif __IOS__ var tempCol = UIColor.FromRGB(_redArray[percentage], _greenArray[percentage], _blueArray[percentage]); #endif _tmpCol = tempCol; return tempCol; } } } <|start_filename|>StepCounter.Android/Services/StepService.cs<|end_filename|> /* * My StepCounter: * Copyright (C) 2014 Refractored LLC | http://refractored.com * <NAME> | http://twitter.com/JamesMontemagno | http://MotzCod.es * * <NAME> | http://twitter.com/micjames6 | http://micjames.co.uk/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using Android.App; using Android.Hardware; using Android.Content; using System.ComponentModel; using StepCounter.Helpers; using StepCounter.Database; using StepCounter.Activities; #if PRO using Android.Support.V4.App; #endif using Android.Graphics; namespace StepCounter.Services { [Service(Enabled = true)] [IntentFilter(new String[]{"com.refractored.mystepcounter.StepService"})] public class StepService : Service, ISensorEventListener, INotifyPropertyChanged { private bool isRunning; private Int64 stepsToday = 0; public bool WarningState { get; set; } public Int64 StepsToday { get{ return stepsToday; } set{ if (stepsToday == value) return; stepsToday = value; OnPropertyChanged ("StepsToday"); Helpers.Settings.CurrentDaySteps = value; } } public override StartCommandResult OnStartCommand (Intent intent, StartCommandFlags flags, int startId) { Console.WriteLine ("StartCommand Called, setting alarm"); #if DEBUG Android.Util.Log.Debug ("STEPSERVICE", "Start command result called, incoming startup"); #endif var alarmManager = ((AlarmManager)ApplicationContext.GetSystemService (Context.AlarmService)); var intent2 = new Intent (this, typeof(StepService)); intent2.PutExtra ("warning", WarningState); var stepIntent = PendingIntent.GetService (ApplicationContext, 10, intent2, PendingIntentFlags.UpdateCurrent); // Workaround as on Android 4.4.2 START_STICKY has currently no // effect // -> restart service every 60 mins alarmManager.Set(AlarmType.Rtc, Java.Lang.JavaSystem .CurrentTimeMillis() + 1000 * 60 * 60, stepIntent); var warning = false; if (intent != null) warning = intent.GetBooleanExtra ("warning", false); Startup (); return StartCommandResult.Sticky; } public override void OnTaskRemoved (Intent rootIntent) { base.OnTaskRemoved (rootIntent); UnregisterListeners (); #if DEBUG Console.WriteLine ("OnTaskRemoved Called, setting alarm for 500 ms"); Android.Util.Log.Debug ("STEPSERVICE", "Task Removed, going down"); #endif var intent = new Intent (this, typeof(StepService)); intent.PutExtra ("warning", WarningState); // Restart service in 500 ms ((AlarmManager) GetSystemService(Context.AlarmService)).Set(AlarmType.Rtc, Java.Lang.JavaSystem .CurrentTimeMillis() + 500, PendingIntent.GetService(this, 11, intent, 0)); } private void Startup(bool warning = false) { //check if kit kat can sensor compatible if (!Utils.IsKitKatWithStepCounter(PackageManager)) { Console.WriteLine("Not compatible with sensors, stopping service."); StopSelf (); return; } CrunchDates (true); if (!isRunning) { RegisterListeners (warning ? SensorType.StepDetector : SensorType.StepCounter); WarningState = warning; } isRunning = true; } public override void OnDestroy () { base.OnDestroy (); UnregisterListeners (); isRunning = false; CrunchDates (); } void RegisterListeners(SensorType sensorType) { var sensorManager = (SensorManager) GetSystemService(Context.SensorService); var sensor = sensorManager.GetDefaultSensor(sensorType); //get faster why not, nearly fast already and when //sensor gets messed up it will be better sensorManager.RegisterListener(this, sensor, SensorDelay.Normal); Console.WriteLine("Sensor listener registered of type: " + sensorType); } void UnregisterListeners() { if (!isRunning) return; try{ var sensorManager = (SensorManager) GetSystemService(Context.SensorService); sensorManager.UnregisterListener(this); Console.WriteLine("Sensor listener unregistered."); #if DEBUG Android.Util.Log.Debug ("STEPSERVICE", "Sensor listener unregistered."); #endif isRunning = false; } catch(Exception ex) { #if DEBUG Android.Util.Log.Debug ("STEPSERVICE", "Unable to unregister: " + ex); #endif } } StepServiceBinder binder; public override Android.OS.IBinder OnBind (Android.Content.Intent intent) { binder = new StepServiceBinder (this); return binder; } public void OnAccuracyChanged (Sensor sensor, SensorStatus accuracy) { //do nothing here } public void AddSteps(Int64 count){ //if service rebooted or rebound then this will null out to 0, but count will still be since last boot. if (lastSteps == 0) { lastSteps = count; } //calculate new steps newSteps = count - lastSteps; //ensure we are never negative //if so, no worries as we are about to re-set the lastSteps to the //current count if (newSteps < 0) newSteps = 1; else if (newSteps > 100) newSteps = 1; lastSteps = count; //ensure we don't need to re-boot day :) CrunchDates (); CrunchHighScores (); //save total steps! Helpers.Settings.TotalSteps += newSteps; StepsToday = Helpers.Settings.TotalSteps - Helpers.Settings.StepsBeforeToday; Console.WriteLine ("New step detected by STEP_COUNTER sensor. Total step count: " + stepsToday ); #if DEBUG Android.Util.Log.Debug ("STEPSERVICE", "New steps: " + newSteps + " total: " + stepsToday); #endif } Int64 newSteps = 0; Int64 lastSteps = 0; public void OnSensorChanged (SensorEvent e) { switch (e.Sensor.Type) { case SensorType.StepCounter: if (lastSteps < 0) lastSteps = 0; //grab out the current value. var count = (Int64)e.Values [0]; //in some instances if things are running too long (about 4 days) //the value flips and gets crazy and this will be -1 //so switch to step detector instead, but put up warning sign. if (count < 0) { UnregisterListeners (); RegisterListeners (SensorType.StepDetector); isRunning = true; #if DEBUG Android.Util.Log.Debug ("STEPSERVICE", "Something has gone wrong with the step counter, simulating steps, 2."); #endif count = lastSteps + 3; WarningState = true; } else { WarningState = false; } AddSteps (count); break; case SensorType.StepDetector: count = lastSteps + 1; AddSteps (count); break; } } private void CrunchHighScores () { bool notification = Helpers.Settings.ProgressNotifications; int halfGoal = 5000; int fullGoal = 10000; int doubleGoal = 20000; if (stepsToday < halfGoal && stepsToday + newSteps >= halfGoal) { Helpers.Settings.GoalTodayDay = DateTime.Today; Helpers.Settings.GoalTodayMessage = Resources.GetString (Resource.String.goal_half); } else if (stepsToday < fullGoal && stepsToday + newSteps >= fullGoal) { Helpers.Settings.GoalTodayDay = DateTime.Today; Helpers.Settings.GoalTodayMessage = string.Format(Resources.GetString (Resource.String.goal_full), (fullGoal).ToString("N0")); } else if (stepsToday < doubleGoal && stepsToday + newSteps >= doubleGoal) { Helpers.Settings.GoalTodayDay = DateTime.Today; Helpers.Settings.GoalTodayMessage = string.Format(Resources.GetString (Resource.String.goal_double), (doubleGoal).ToString("N0")); } else { notification = false; } if (notification) { PopUpNotification (0, Resources.GetString (Resource.String.goal_update), Helpers.Settings.GoalTodayMessage); } notification = false; if (stepsToday + newSteps > Helpers.Settings.HighScore) { Helpers.Settings.HighScore = stepsToday + newSteps; //if not today if (!Helpers.Settings.TodayIsHighScore) { //if first day of use then no notifications, else pop it up if (Helpers.Settings.FirstDayOfUse.DayOfYear == DateTime.Today.DayOfYear && Helpers.Settings.FirstDayOfUse.Year == DateTime.Today.Year) { notification = false; } else { notification = Helpers.Settings.ProgressNotifications; } } //this triggers a new high score day so the next tiem it comes in TodayIsHighScore will be true Helpers.Settings.HighScoreDay = DateTime.Today; } //notifcation for high score if (notification) { PopUpNotification (1, Resources.GetString (Resource.String.high_score_title), string.Format(Resources.GetString(Resource.String.high_score), Utils.FormatSteps(Helpers.Settings.HighScore))); } notification = Helpers.Settings.AccumulativeNotifications; var notificationString = string.Empty; if (Helpers.Settings.TotalSteps + newSteps > Helpers.Settings.NextGoal) { notificationString = string.Format (Resources.GetString (Resource.String.awesome), Utils.FormatSteps(Helpers.Settings.NextGoal)); if (Settings.NextGoal < 500000) { Settings.NextGoal = 500000; } else if (Helpers.Settings.NextGoal < 1000000) { Settings.NextGoal = 1000000; } else { Settings.NextGoal += 1000000; } } else { notification = false; } //notifcation for accumulative records if (notification) { PopUpNotification (2, Resources.GetString (Resource.String.awesome_title), notificationString); } } #if PRO //This requires support v4 NuGet Package. Not supported on Starter. private void PopUpNotification(int id, string title, string message){ var wearableExtender = new NotificationCompat.WearableExtender () .SetHintHideIcon (true); Bitmap bitmap = null; try{ bitmap = BitmapFactory.DecodeResource (Resources, Resource.Drawable.wear_background); }catch(Exception ex) { } if(bitmap != null) wearableExtender.SetBackground(bitmap); var builder = new NotificationCompat.Builder (this) .SetSmallIcon (Resource.Drawable.ic_notification) .SetContentTitle (title) .SetContentText (message) .Extend(wearableExtender) .SetAutoCancel (true); // Creates an explicit intent for an Activity in your app var resultIntent = new Intent(this, typeof(MainActivity)); resultIntent.SetFlags(ActivityFlags.NewTask|ActivityFlags.ClearTask); // The stack builder object will contain an artificial back stack for the // started Activity. // This ensures that navigating backward from the Activity leads out of // your application to the Home screen. var stackBuilder = Android.Support.V4.App.TaskStackBuilder.Create(this); // Adds the back stack for the Intent (but not the Intent itself) //stackBuilder.AddParentStack(); // Adds the Intent that starts the Activity to the top of the stack stackBuilder.AddNextIntent(resultIntent); var resultPendingIntent = stackBuilder.GetPendingIntent( 0, (int)PendingIntentFlags.UpdateCurrent ); builder.SetContentIntent(resultPendingIntent); var notificationManager = NotificationManagerCompat.From (this); // mId allows you to update the notification later on. notificationManager.Notify(id, builder.Build()); } #else private void PopUpNotification(int id, string title, string message){ Notification.Builder mBuilder = new Notification.Builder (this) .SetSmallIcon (Resource.Drawable.ic_notification) .SetContentTitle (title) .SetContentText (message) .SetAutoCancel (true); // Creates an explicit intent for an Activity in your app Intent resultIntent = new Intent(this, typeof(MainActivity)); resultIntent.SetFlags(ActivityFlags.NewTask|ActivityFlags.ClearTask); // The stack builder object will contain an artificial back stack for the // started Activity. // This ensures that navigating backward from the Activity leads out of // your application to the Home screen. var stackBuilder = Android.App.TaskStackBuilder.Create(this); // Adds the back stack for the Intent (but not the Intent itself) //stackBuilder.AddParentStack(); // Adds the Intent that starts the Activity to the top of the stack stackBuilder.AddNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.GetPendingIntent( 0, PendingIntentFlags.UpdateCurrent ); mBuilder.SetContentIntent(resultPendingIntent); NotificationManager mNotificationManager = (NotificationManager) GetSystemService(Context.NotificationService); // mId allows you to update the notification later on. mNotificationManager.Notify(id, mBuilder.Build()); } #endif private void CrunchDates(bool startup = false) { if (!Utils.IsSameDay) { //save our day from yesterday, we dont' do datetime.adddays(-1) because phone might have been off //for more then 1 day and it would not be correct! var yesterday = Helpers.Settings.CurrentDay; var dayEntry = StepEntryManager.GetStepEntry (yesterday); if (dayEntry == null || dayEntry.Date.DayOfYear != yesterday.DayOfYear) { dayEntry = new StepEntry (); } dayEntry.Date = yesterday; dayEntry.Steps = Helpers.Settings.CurrentDaySteps; Helpers.Settings.CurrentDay = DateTime.Today; Helpers.Settings.CurrentDaySteps = 0; Helpers.Settings.StepsBeforeToday = Helpers.Settings.TotalSteps; StepsToday = 0; try{ StepEntryManager.SaveStepEntry (dayEntry); }catch(Exception ex){ Console.WriteLine ("Something horrible has gone wrong attempting to save database entry, it is lost forever :("); } } else if (startup) { StepsToday = Helpers.Settings.TotalSteps - Helpers.Settings.StepsBeforeToday; } } #region INotifyPropertyChanged implementation public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string name) { if (PropertyChanged == null) return; PropertyChanged(this, new PropertyChangedEventArgs(name)); } #endregion } } <|start_filename|>StepCounter/Helpers/DateHelpers.cs<|end_filename|> using System; using Foundation; namespace StepCounter.Helpers { public static class DateHelpers { public static DateTime NSDateToDateTime(NSDate date) { return (new DateTime(2001,1,1,0,0,0)).AddSeconds(date.SecondsSinceReferenceDate); } public static NSDate DateTimeToNSDate(DateTime date) { return NSDate.FromTimeIntervalSinceReferenceDate((date-(new DateTime(2001,1,1,0,0,0))).TotalSeconds); } } } <|start_filename|>Artwork/Website/style.css<|end_filename|> body { text-rendering: optimizeLegibility; font-size: 14px; background-color: #2A89AD; font-family: 'Roboto', sans-serif; color: #fbf7ef; } a:link {color:#FFFFFF;} /* unvisited link */ a:visited {color:#FFFFFF;} /* visited link */ a:hover {color:#B4BCBC;} /* mouse over link */ a:active {color:#B4BCBC;} /* selected link */ h1 { font-size: 450%; margin-bottom: 5px; margin-top: 0; padding-top: 15px; text-align: center; font-weight: 100; } h2 { font-size: 150%; text-align: center; margin: 0 0 0px 200px; font-weight: 300; } h1#mobileh1 { font-size: 250%; margin-bottom: 5px; margin-top: 0; padding-top: 15px; text-align: center; font-weight: 100; } h2#mobileh2{ font-size: 125%; text-align: center; margin: 0 0 0px 100px; font-weight: 300; } p { text-align: center; } p.bottomline { font-size: 13px; } img { margin: auto; } img.mobile_hero{ max-width: 80%; } @media screen and (orientation: portrait) { img.mobile_hero { max-width: 90%; } } @media screen and (orientation: landscape) { img.mobile_hero { max-height: 90%; } } div#contain { width: 100%; overflow: visible; display: flex; flex-direction: row; flex-wrap: wrap; justify-content: center; align-items: center; box-align:center; } div#leftdiv { display: block; width: 49%; float: left; background: url('frame_bg.png') no-repeat no-repeat; background-size: 100% 100%; } div#leftdiv video { display: block; width: 65%; margin: auto; padding-top: 25%; padding-bottom: 25%; } div#rightdiv { display: block; width: 49%; float: left; background: url('frame_bg_iphone.png') no-repeat no-repeat; background-size: 100% 100%; } div#rightdiv video { display: block; width: 59%; margin: auto; padding-top: 28%; padding-bottom: 33%; } .clear{ clear:both; } img.appstore { display: block; margin: -10% auto 0 auto; height: 40px; position:relative; z-index:1000 } img.gplay { display: block; margin: -10% auto 0 auto; height: 45px; width: 129px; position:relative; z-index:1000 } div#contain_footer { padding-top: 30px; width: 90%; margin: auto; overflow: hidden; } img.starter { display: inline-block; height: 60px; vertical-align: middle; margin-right: 5px; } .copyright { display: inline-block; vertical-align: middle; font-size: 90%; font-weight: 300; } <|start_filename|>StepCounter.Android/Controls/ProgressView.cs<|end_filename|> /* * My StepCounter: * Copyright (C) 2014 Refractored LLC | http://refractored.com * <NAME> | http://twitter.com/JamesMontemagno | http://MotzCod.es * * <NAME> | http://twitter.com/micjames6 | http://micjames.co.uk/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using Android.Content; using Android.Util; using Android.Widget; using Android.Graphics; using Android.Runtime; namespace StepCounter.Controls { public partial class ProgressView : FrameLayout { public ProgressView (Context context) : base (context) { Initialize (); } public ProgressView (Context context, IAttributeSet attrs) : base (context, attrs) { Initialize (); } public ProgressView (Context context, IAttributeSet attrs, int defStyle) : base (context, attrs, defStyle) { Initialize (); } public ProgressView(IntPtr pointer, JniHandleOwnership handle) : base (pointer, handle) { Initialize (); } } } <|start_filename|>StepCounter/StepManager.cs<|end_filename|> using System; using CoreMotion; using Foundation; namespace StepCounter { public class StepManager { public delegate void DailyStepCountChangedEventHandler(nint stepCount); private NSOperationQueue _queue; private DateTime _resetTime; private CMStepCounter _stepCounter; public StepManager() { ForceUpdate(); _stepCounter.StartStepCountingUpdates(_queue, 1, Updater); } public void ForceUpdate() { //If the last reset date wasn't today then we should update this. if (_resetTime.Date.Day != DateTime.Now.Date.Day) { _resetTime = DateTime.Today; //Forces update as the day may have changed. } NSDate sMidnight = Helpers.DateHelpers.DateTimeToNSDate(_resetTime); _queue = _queue ?? NSOperationQueue.CurrentQueue; if (_stepCounter == null) _stepCounter = new CMStepCounter(); _stepCounter.QueryStepCount(sMidnight, NSDate.Now, _queue, DailyStepQueryHandler); } public void StartCountingFrom(DateTime date) { _resetTime = date; ForceUpdate(); } private void DailyStepQueryHandler(nint stepCount, NSError error) { if (DailyStepCountChanged == null) return; #if DEBUG stepCount = 1245; //stepCount = 6481; //stepCount = 9328; #endif DailyStepCountChanged(stepCount); } private void Updater(nint stepCount, NSDate date, NSError error) { NSDate sMidnight = Helpers.DateHelpers.DateTimeToNSDate(_resetTime); _stepCounter.QueryStepCount(sMidnight, NSDate.Now, _queue, DailyStepQueryHandler); } public event DailyStepCountChangedEventHandler DailyStepCountChanged; } } <|start_filename|>StepCounter/Helpers/Conversion.cs<|end_filename|> using System; namespace StepCounter.Helpers { public static class Conversion { public static double StepCountToPercentage(int stepCount) { var per = (stepCount/(decimal) 10000)*100; return ((double) per); } public static double StepCountToPercentage(Int64 stepCount) { var per = (stepCount/(decimal) 10000)*100; return ((double) per); } public static int PercentageToStepCount(double percent) { if (!(percent > 0)) return 0; var steps = (10000/(decimal) percent)*100; return ((int) steps); } public static float StepsToMiles(int stepCount) { if (stepCount <= 0) return 0.00f; //Average steps in a mile const float stepsPerMile = 2000; return stepCount/stepsPerMile; } public static float StepsToMiles(Int64 stepCount) { if (stepCount <= 0) return 0.00f; //Average steps in a mile const float stepsPerMile = 2000; return stepCount/stepsPerMile; } public static float StepsToKilometers(int stepCount) { var miles = StepsToMiles(stepCount); return miles*1.609344f; } public static float StepsToKilometers(Int64 stepCount) { var miles = StepsToMiles(stepCount); return miles*1.609344f; } public static string CaloriesBurnt(float miles) { const int caloriesBurntPerMile = 100; var val = miles*caloriesBurntPerMile; return val <= 0 ? "0" : val.ToString("N0"); } /// <summary> /// Calorieses the burnt with weight entered /// view-source:http://walking.about.com/library/cal/uccalc1.htm /// </summary> /// <returns>The burnt calories.</returns> /// <param name="miles">Miles.</param> /// <param name="lbs">Lbs.</param> public static string CaloriesBurnt(float miles, float lbs, string cadence) { if (lbs <= 0) return CaloriesBurnt (miles); var met = 3.5; var pace = 3.0; switch (cadence) { case "0": met = 2.0; pace = 2.0; break; case "1": met = 2.5; pace = 2.0; break; case "2": met = 3.0; pace = 2.5; break; case "3": met = 3.5; pace = 3.0; break; case "4": met = 5.0; pace = 4.0; break; case "5": met = 6.3; pace = 4.5; break; case "6": met = 8.0; pace = 5.0; break; } var adjusted_weight = lbs / 2.2; var val = Math.Round (((adjusted_weight * met) / pace) * miles); return val <= 0 ? "0" : val.ToString ("N0"); } } }
lifeonland/My-StepCounter
<|start_filename|>web/.prettierrc.json<|end_filename|> { "semi": false, "singleQuote": true, "endOfLine": "auto", "@typescript-eslint/no-explicit-any": ["off"] } <|start_filename|>web/src/mixin/tableHeight.js<|end_filename|> export default { data() { return { tableHeight: window.innerHeight - 160, // table高度 } }, mounted() { try { const outHeight = document.getElementsByClassName('app-bar')[0].clientHeight + 140 // 除了table外 查询与按钮的高度 + 其他的高度150 const maxHeight = window.innerHeight - outHeight this.tableHeight = maxHeight } catch (e) { console.log('缺少节点app-bar') } }, }
wuchunfu/goploy-agent
<|start_filename|>.github/scripts/update-prerelease-beta-version.js<|end_filename|> 'use strict'; const semverInc = require( 'semver/functions/inc' ); const packageJson = require( '../../package.json' ); const fs = require( 'fs' ); const bumpVersion = (relativeVersion, lastVersionTagName, bumpsFromCurrentVersion = 1) => { const lastVersion = packageJson[lastVersionTagName] || ''; let expectedVersion = relativeVersion; (new Array( bumpsFromCurrentVersion ).fill( 1 )).forEach(() => { expectedVersion = semverInc( expectedVersion, 'minor' ); }); let currentLastVersionNumber = 0; if (lastVersion) { const splitVersion = lastVersion.split( `-beta` ); if (splitVersion[0] === expectedVersion) { const currentLastVersion = splitVersion[splitVersion.length - 1]; currentLastVersionNumber = Number( currentLastVersion ); if (Number.isNaN( currentLastVersionNumber )) { console.error( `invalid beta version: ${currentLastVersion}` ); process.exit( 1 ); return; } } } const newVersion = `${expectedVersion}-beta${currentLastVersionNumber + 1}`; packageJson[lastVersionTagName] = newVersion; fs.writeFileSync( './package.json', JSON.stringify( packageJson, null, 4 ) ); console.log( newVersion ); } const relativeVersion = packageJson.version; bumpVersion( relativeVersion, 'last_beta_version' ); <|start_filename|>assets/dev/js/frontend/hello-frontend.js<|end_filename|> class elementorHelloThemeHandler { constructor() { this.initSettings(); this.initElements(); this.bindEvents(); } initSettings() { this.settings = { selectors: { header: 'header.site-header', footer: 'footer.site-footer', menuToggle: '.site-header .site-navigation-toggle', menuToggleHolder: '.site-header .site-navigation-toggle-holder', dropdownMenu: '.site-header .site-navigation-dropdown', }, }; } initElements() { this.elements = { $window: jQuery( window ), $document: jQuery( document ), $header: jQuery( this.settings.selectors.header ), $footer: jQuery( this.settings.selectors.footer ), $menuToggle: jQuery( this.settings.selectors.menuToggle ), $menuToggleHolder: jQuery( this.settings.selectors.menuToggleHolder ), $dropdownMenu: jQuery( this.settings.selectors.dropdownMenu ), }; } bindEvents() { this.elements.$menuToggle.on( 'click', () => this.handleMenuToggle() ); this.elements.$dropdownMenu.on( 'click', '.menu-item-has-children > a', this.handleMenuChildren ); } closeMenuItems() { this.elements.$menuToggleHolder.removeClass( 'elementor-active' ); this.elements.$window.off( 'resize', () => this.closeMenuItems() ); } handleMenuToggle() { const isDropdownVisible = ! this.elements.$menuToggleHolder.hasClass( 'elementor-active' ); this.elements.$menuToggle.attr( 'aria-expanded', isDropdownVisible ); this.elements.$dropdownMenu.attr( 'aria-hidden', ! isDropdownVisible ); this.elements.$menuToggleHolder.toggleClass( 'elementor-active', isDropdownVisible ); // Always close all sub active items. this.elements.$dropdownMenu.find( '.elementor-active' ).removeClass( 'elementor-active' ); if ( isDropdownVisible ) { this.elements.$window.on( 'resize', () => this.closeMenuItems() ); } else { this.elements.$window.off( 'resize', () => this.closeMenuItems() ); } } handleMenuChildren( event ) { const $anchor = jQuery( event.currentTarget ), $parentLi = $anchor.parent( 'li' ), isSubmenuVisible = $parentLi.hasClass( 'elementor-active' ); if ( ! isSubmenuVisible ) { $parentLi.addClass( 'elementor-active' ); } else { $parentLi.removeClass( 'elementor-active' ); } } } jQuery( () => { new elementorHelloThemeHandler(); } ); <|start_filename|>assets/dev/js/editor/hello-editor.js<|end_filename|> import HelloComponent from './component'; $e.components.register( new HelloComponent() ); <|start_filename|>.github/scripts/get-changelog-from-readme-txt.js<|end_filename|> 'use strict'; const marked = require("marked"); const fs = require('fs'); const { VERSION } = process.env; if (!VERSION) { console.error('missing VERSION env var'); process.exit(1); return; } (async () => { try { const changelogText = fs.readFileSync('readme.txt', 'utf-8'); const data = marked.lexer(changelogText); const headerIndex = data.findIndex((section) => section.type === 'paragraph' && section.text.startsWith(`= ${VERSION}`)); if (headerIndex === -1) { console.error(`Failed to find version: ${VERSION} in readme.txt file`); process.exit(1); return; } const versionLog = data[headerIndex + 1].raw; fs.writeFileSync('temp-changelog-from-readme.txt', versionLog); } catch (err) { process.exit(1); } })(); <|start_filename|>assets/dev/js/editor/hooks/ui/controls-hook.js<|end_filename|> export default class ControlsHook extends $e.modules.hookUI.After { getCommand() { // Command to listen. return 'document/elements/settings'; } getId() { // Unique id for the hook. return 'hello-elementor-editor-controls-handler'; } /** * Get Hello Theme Controls * * Returns an object in which the keys are control IDs, and the values are the selectors of the elements that need * to be targeted in the apply() method. * * Example return value: * { * hello_elementor_show_logo: '.site-header .site-header-logo', * hello_elementor_show_menu: '.site-header .site-header-menu', * } */ getHelloThemeControls() { return { hello_header_logo_display: { selector: '.site-header .site-logo, .site-header .site-title', callback: ( $element, args ) => { this.toggleShowHideClass( $element, args.settings.hello_header_logo_display ); }, }, hello_header_menu_display: { selector: '.site-header .site-navigation, .site-header .site-navigation-toggle-holder', callback: ( $element, args ) => { this.toggleShowHideClass( $element, args.settings.hello_header_menu_display ); }, }, hello_header_tagline_display: { selector: '.site-header .site-description', callback: ( $element, args ) => { this.toggleShowHideClass( $element, args.settings.hello_header_tagline_display ); }, }, hello_header_logo_type: { selector: '.site-header .site-branding', callback: ( $element, args ) => { const classPrefix = 'show-', inputOptions = args.container.controls.hello_header_logo_type.options, inputValue = args.settings.hello_header_logo_type; this.toggleLayoutClass( $element, classPrefix, inputOptions, inputValue ); }, }, hello_header_layout: { selector: '.site-header', callback: ( $element, args ) => { const classPrefix = 'header-', inputOptions = args.container.controls.hello_header_layout.options, inputValue = args.settings.hello_header_layout; this.toggleLayoutClass( $element, classPrefix, inputOptions, inputValue ); }, }, hello_header_width: { selector: '.site-header', callback: ( $element, args ) => { const classPrefix = 'header-', inputOptions = args.container.controls.hello_header_width.options, inputValue = args.settings.hello_header_width; this.toggleLayoutClass( $element, classPrefix, inputOptions, inputValue ); }, }, hello_header_menu_layout: { selector: '.site-header', callback: ( $element, args ) => { const classPrefix = 'menu-layout-', inputOptions = args.container.controls.hello_header_menu_layout.options, inputValue = args.settings.hello_header_menu_layout; // No matter what, close the mobile menu $element.find( '.site-navigation-toggle-holder' ).removeClass( 'elementor-active' ); $element.find( '.site-navigation-dropdown' ).removeClass( 'show' ); this.toggleLayoutClass( $element, classPrefix, inputOptions, inputValue ); }, }, hello_header_menu_dropdown: { selector: '.site-header', callback: ( $element, args ) => { const classPrefix = 'menu-dropdown-', inputOptions = args.container.controls.hello_header_menu_dropdown.options, inputValue = args.settings.hello_header_menu_dropdown; this.toggleLayoutClass( $element, classPrefix, inputOptions, inputValue ); }, }, hello_footer_logo_display: { selector: '.site-footer .site-logo, .site-footer .site-title', callback: ( $element, args ) => { this.toggleShowHideClass( $element, args.settings.hello_footer_logo_display ); }, }, hello_footer_tagline_display: { selector: '.site-footer .site-description', callback: ( $element, args ) => { this.toggleShowHideClass( $element, args.settings.hello_footer_tagline_display ); }, }, hello_footer_menu_display: { selector: '.site-footer .site-navigation', callback: ( $element, args ) => { this.toggleShowHideClass( $element, args.settings.hello_footer_menu_display ); }, }, hello_footer_copyright_display: { selector: '.site-footer .copyright', callback: ( $element, args ) => { const $footerContainer = $element.closest( '#site-footer' ), inputValue = args.settings.hello_footer_copyright_display; this.toggleShowHideClass( $element, inputValue ); $footerContainer.toggleClass( 'footer-has-copyright', 'yes' === inputValue ); }, }, hello_footer_logo_type: { selector: '.site-footer .site-branding', callback: ( $element, args ) => { const classPrefix = 'show-', inputOptions = args.container.controls.hello_footer_logo_type.options, inputValue = args.settings.hello_footer_logo_type; this.toggleLayoutClass( $element, classPrefix, inputOptions, inputValue ); }, }, hello_footer_layout: { selector: '.site-footer', callback: ( $element, args ) => { const classPrefix = 'footer-', inputOptions = args.container.controls.hello_footer_layout.options, inputValue = args.settings.hello_footer_layout; this.toggleLayoutClass( $element, classPrefix, inputOptions, inputValue ); }, }, hello_footer_width: { selector: '.site-footer', callback: ( $element, args ) => { const classPrefix = 'footer-', inputOptions = args.container.controls.hello_footer_width.options, inputValue = args.settings.hello_footer_width; this.toggleLayoutClass( $element, classPrefix, inputOptions, inputValue ); }, }, hello_footer_copyright_text: { selector: '.site-footer .copyright', callback: ( $element, args ) => { const inputValue = args.settings.hello_footer_copyright_text; $element.find( 'p' ).text( inputValue ); }, }, }; } /** * Toggle show and hide classes on containers * * This will remove the .show and .hide clases from the element, then apply the new class * */ toggleShowHideClass( element, inputValue ) { element.removeClass( 'hide' ).removeClass( 'show' ).addClass( inputValue ? 'show' : 'hide' ); } /** * Toggle layout classes on containers * * This will cleanly set classes onto which ever container we want to target, removing the old classes and adding the new one * */ toggleLayoutClass( element, classPrefix, inputOptions, inputValue ) { // Loop through the possible classes and remove the one that's not in use Object.entries( inputOptions ).forEach( ( [ key ] ) => { element.removeClass( classPrefix + key ); } ); // Append the class which we want to use onto the element if ( '' !== inputValue ) { element.addClass( classPrefix + inputValue ); } } /** * Set the conditions under which the hook will run. */ getConditions( args ) { const isKit = 'kit' === elementor.documents.getCurrent().config.type, changedControls = Object.keys( args.settings ), isSingleSetting = 1 === changedControls.length; // If the document is not a kit, or there are no changed settings, or there is more than one single changed // setting, don't run the hook. if ( ! isKit || ! args.settings || ! isSingleSetting ) { return false; } // If the changed control is in the list of theme controls, return true to run the hook. // Otherwise, return false so the hook doesn't run. return !! Object.keys( this.getHelloThemeControls() ).includes( changedControls[ 0 ] ); } /** * The hook logic. */ apply( args ) { const allThemeControls = this.getHelloThemeControls(), // Extract the control ID from the passed args controlId = Object.keys( args.settings )[ 0 ], controlConfig = allThemeControls[ controlId ], // Find the element that needs to be targeted by the control. $element = elementor.$previewContents.find( controlConfig.selector ); controlConfig.callback( $element, args ); } } <|start_filename|>.github/scripts/update-version-in-files.js<|end_filename|> 'use strict'; const replaceInFile = require( 'replace-in-file' ); const { VERSION } = process.env; const replaceInFileWithLog = async ( options ) => { const results = await replaceInFile( options ); console.log( 'Replacement results:', results, 'options: ', options ); }; const run = async () => { try { await replaceInFileWithLog( { files: './assets/scss/style.scss', from: /Version:.*$/m, to: `Version: ${ VERSION }`, } ); await replaceInFileWithLog( { files: './assets/scss/style.scss', from: /Stable tag:.*$/m, to: `Stable tag: ${ VERSION }`, } ); await replaceInFileWithLog( { files: './functions.php', from: /HELLO_ELEMENTOR_VERSION', '(.*?)'/m, to: `HELLO_ELEMENTOR_VERSION', '${ VERSION }'`, } ); await replaceInFileWithLog( { files: './readme.txt', from: /Version:.*$/m, to: `Version: ${ VERSION }`, } ); await replaceInFileWithLog( { files: './readme.txt', from: /Stable tag:.*$/m, to: `Stable tag: ${ VERSION }`, } ); } catch ( err ) { // eslint-disable-next-line no-console console.error( 'Error occurred:', err ); process.exit( 1 ); } }; run(); <|start_filename|>webpack.config.js<|end_filename|> /** * Grunt webpack task config * @package Elementor */ const path = require( 'path' ); const CopyPlugin = require( 'copy-webpack-plugin' ); const TerserPlugin = require( 'terser-webpack-plugin' ); const copyPluginConfig = new CopyPlugin( { patterns: [ { from: '**/*', context: __dirname, to: path.resolve( __dirname, 'build' ), // Terser skip this file for minimization info: { minimized: true }, globOptions: { ignore: [ '**.zip', '**.css', '**/karma.conf.js', '**/assets/dev/**', '**/assets/scss/**', '**/assets/js/qunit-tests*', '**/bin/**', '**/build/**', '**/composer.json', '**/composer.lock', '**/Gruntfile.js', '**/node_modules/**', '**/npm-debug.log', '**/package-lock.json', '**/package.json', '**/phpcs.xml', '**/README.md', '**/webpack.config.js', '**/vendor/**', ], }, }, ], } ); const moduleRules = { rules: [ { test: /\.js$/, exclude: /node_modules/, use: [ { loader: 'babel-loader', options: { presets: [ '@babel/preset-env' ], plugins: [ [ '@babel/plugin-proposal-class-properties' ], [ '@babel/plugin-transform-runtime' ], [ '@babel/plugin-transform-modules-commonjs' ], [ '@babel/plugin-proposal-optional-chaining' ], ], }, }, ], }, ], }; const entry = { 'hello-editor': path.resolve( __dirname, './assets/dev/js/editor/hello-editor.js' ), 'hello-frontend': path.resolve( __dirname, './assets/dev/js/frontend/hello-frontend.js' ), }; const webpackConfig = { target: 'web', context: __dirname, module: moduleRules, entry: entry, mode: 'development', output: { path: path.resolve( __dirname, './build/assets/js' ), filename: '[name].js', devtoolModuleFilenameTemplate: './[resource]', }, }; const webpackProductionConfig = { target: 'web', context: __dirname, module: moduleRules, entry: { ...entry, }, optimization: { minimize: true, minimizer: [ new TerserPlugin( { terserOptions: { keep_fnames: true, }, include: /\.min\.js$/, } ), ], }, mode: 'production', output: { path: path.resolve( __dirname, './build/assets/js' ), filename: '[name].js', }, performance: { hints: false }, }; // Add minified entry points Object.entries( webpackProductionConfig.entry ).forEach( ( [ wpEntry, value ] ) => { webpackProductionConfig.entry[ wpEntry + '.min' ] = value; delete webpackProductionConfig.entry[ wpEntry ]; } ); const localOutputPath = { ...webpackProductionConfig.output, path: path.resolve( __dirname, './assets/js' ) }; module.exports = ( env ) => { if ( env.developmentLocalWithWatch ) { return { ...webpackConfig, watch: true, devtool: 'source-map', output: localOutputPath }; } if ( env.productionLocalWithWatch ) { return { ...webpackProductionConfig, watch: true, devtool: 'source-map', output: localOutputPath }; } if ( env.productionLocal ) { return { ...webpackProductionConfig, devtool: 'source-map', output: localOutputPath }; } if ( env.developmentLocal ) { return { ...webpackConfig, devtool: 'source-map', output: localOutputPath }; } if ( env.production ) { return webpackProductionConfig; } if ( env.development ) { return { ...webpackConfig, plugins: [ copyPluginConfig ] }; } throw new Error( 'missing or invalid --env= development/production/developmentWithWatch/productionWithWatch' ); }; <|start_filename|>assets/dev/js/editor/component.js<|end_filename|> import ControlsHook from './hooks/ui/controls-hook'; export default class extends $e.modules.ComponentBase { pages = {}; getNamespace() { return 'hello-elementor'; } defaultHooks() { return this.importHooks( { ControlsHook } ); } } <|start_filename|>Gruntfile.js<|end_filename|> /** * Elementor Hello Theme Makefile */ 'use strict'; module.exports = function( grunt ) { require( 'matchdep' ).filterDev( 'grunt-*' ).forEach( grunt.loadNpmTasks ); const sass = require( 'node-sass' ); // Project configuration. grunt.initConfig( { pkg: grunt.file.readJSON( 'package.json' ), sass: { options: { implementation: sass, }, dist: { files: 'production' === grunt.option( 'environment' ) ? [ { expand: true, cwd: 'assets/scss', src: '*.scss', dest: './build', ext: '.css', } ] : [ { expand: true, cwd: 'assets/scss', src: '*.scss', dest: './', ext: '.css', } ], }, }, postcss: { dev: { options: { //map: true, processors: [ require( 'autoprefixer' )( { browsers: 'last 3 versions', } ), ], }, files: [ { src: [ '*.css', '!*.min.css', ], } ], }, minify: { options: { processors: [ require( 'autoprefixer' )( { browsers: 'last 3 versions', } ), require( 'cssnano' )( { reduceIdents: false, zindex: false, } ), ], }, files: [ { expand: true, src: 'production' === grunt.option( 'environment' ) ? [ 'build/*.css', '!build/*.min.css', ] : [ '*.css', '!*.min.css', ], ext: '.min.css', } ], }, }, watch: { styles: { files: [ 'assets/scss/**/*.scss', ], tasks: [ 'styles' ], }, }, checktextdomain: { options: { text_domain: 'hello-elementor', correct_domain: true, keywords: [ // WordPress keywords '__:1,2d', '_e:1,2d', '_x:1,2c,3d', 'esc_html__:1,2d', 'esc_html_e:1,2d', 'esc_html_x:1,2c,3d', 'esc_attr__:1,2d', 'esc_attr_e:1,2d', 'esc_attr_x:1,2c,3d', '_ex:1,2c,3d', '_n:1,2,4d', '_nx:1,2,4c,5d', '_n_noop:1,2,3d', '_nx_noop:1,2,3c,4d', ], }, files: { src: [ '**/*.php', '!docs/**', '!bin/**', '!node_modules/**', '!build/**', '!tests/**', '!.github/**', '!vendor/**', '!*~', ], expand: true, }, }, wp_readme_to_markdown: { readme: { files: { 'README.md': 'readme.txt', }, }, }, } ); grunt.registerTask( 'i18n', [ 'checktextdomain', ] ); grunt.registerTask( 'wp_readme', [ 'wp_readme_to_markdown', ] ); grunt.registerTask( 'styles', [ 'sass', 'postcss', ] ); // Default task(s). grunt.registerTask( 'default', [ 'i18n', 'styles', 'wp_readme', ] ); }; <|start_filename|>composer.json<|end_filename|> { "name": "elementor/hello-theme", "require": { "squizlabs/php_codesniffer": "^3.6", "dealerdirect/phpcodesniffer-composer-installer": "^0.7.1", "wp-coding-standards/wpcs": "^2.3" }, "scripts": { "lint": "phpcs --extensions=php -p" } }
AHDCreative/hello-theme-ffxvita
<|start_filename|>Dockerfile<|end_filename|> FROM alpine:latest ENTRYPOINT ["/run.sh"] ENV CLEAN_PERIOD=**None** \ DELAY_TIME=**None** \ KEEP_IMAGES=**None** \ KEEP_CONTAINERS=**None** \ LOOP=true \ DEBUG=0 \ DOCKER_API_VERSION=1.20 # run.sh script uses some bash specific syntax RUN apk add --update bash docker grep # Install cleanup script ADD docker-cleanup-volumes.sh /docker-cleanup-volumes.sh ADD run.sh /run.sh
AspirationPartners/docker-cleanup
<|start_filename|>gapic/templates/docs/_static/custom.css<|end_filename|> dl.field-list > dt { min-width: 100px }
Kache/gapic-generator-python
<|start_filename|>cancel.go<|end_filename|> package pipeline import ( "context" ) // Cancel passes an `interface{}` from the `in <-chan interface{}` directly to the out `<-chan interface{}` until the `Context` is canceled. // After the context is canceled, everything from `in <-chan interface{}` is sent to the `cancel` func instead with the `ctx.Err()`. func Cancel(ctx context.Context, cancel func(interface{}, error), in <-chan interface{}) <-chan interface{} { out := make(chan interface{}) go func() { defer close(out) for { select { // When the context isn't canceld, pass everything to the out chan // until in is closed case i, open := <-in: if !open { return } out <- i // When the context is canceled, pass all ins to the // cancel fun until in is closed case <-ctx.Done(): for i := range in { cancel(i, ctx.Err()) } return } } }() return out } <|start_filename|>split.go<|end_filename|> package pipeline // Split takes an interface from Collect and splits it back out into individual elements // Useful for batch processing pipelines (`input chan -> Collect -> Process -> Split -> Cancel -> output chan`). func Split(in <-chan interface{}) <-chan interface{} { out := make(chan interface{}) go func() { defer close(out) for is := range in { for _, i := range is.([]interface{}) { out <- i } } }() return out } <|start_filename|>process_batch_test.go<|end_filename|> package pipeline import ( "context" "reflect" "testing" "time" ) func TestProcessBatch(t *testing.T) { const maxTestDuration = time.Second type args struct { ctxTimeout time.Duration maxSize int maxDuration time.Duration processor *mockProcessor in <-chan interface{} } tests := []struct { name string args args wantOpen bool }{{ name: "out stays open if in is open", args: args{ // Cancel the pipeline context half way through the test ctxTimeout: maxTestDuration / 2, maxDuration: maxTestDuration, // Process 2 elements 33% of the total test duration maxSize: 2, processor: &mockProcessor{ processDuration: maxTestDuration / 3, cancelDuration: maxTestDuration / 3, }, // * 10 elements = 165% of the test duration in: Emit(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), }, // Therefore the out chan should still be open when the test times out wantOpen: true, }, { name: "out closes if in is closed", args: args{ // Cancel the pipeline context half way through the test ctxTimeout: maxTestDuration / 2, maxDuration: maxTestDuration, // Process 5 elements 33% of the total test duration maxSize: 5, processor: &mockProcessor{ processDuration: maxTestDuration / 3, cancelDuration: maxTestDuration / 3, }, // * 10 elements = 66% of the test duration in: Emit(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), }, // Therefore the out channel should be closed when the test ends wantOpen: false, }} for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), tt.args.ctxTimeout) defer cancel() // Process the batch with a timeout of maxTestDuration open := true outChan := ProcessBatch(ctx, tt.args.maxSize, tt.args.maxDuration, tt.args.processor, tt.args.in) timeout := time.After(maxTestDuration) loop: for { select { case <-timeout: break loop case _, ok := <-outChan: if !ok { open = false break loop } } } // Expecting the channels open state if open != tt.wantOpen { t.Errorf("open = %t, wanted %t", open, tt.wantOpen) } }) } } func TestProcessBatchConcurrently(t *testing.T) { const maxTestDuration = time.Second type args struct { ctxTimeout time.Duration concurrently int maxSize int maxDuration time.Duration processor *mockProcessor in <-chan interface{} } tests := []struct { name string args args wantOpen bool }{{ name: "out stays open if in is open", args: args{ ctxTimeout: maxTestDuration / 2, maxDuration: maxTestDuration, // Process 1 element for 33% of the total test duration maxSize: 1, // * 2x concurrently concurrently: 2, processor: &mockProcessor{ processDuration: maxTestDuration / 3, cancelDuration: maxTestDuration / 3, }, // * 10 elements = 165% of the test duration in: Emit(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), }, // Therefore the out chan should still be open when the test times out wantOpen: true, }, { name: "out closes if in is closed", args: args{ ctxTimeout: maxTestDuration / 2, maxDuration: maxTestDuration, // Process 1 element for 33% of the total test duration maxSize: 1, // * 5x concurrently concurrently: 5, processor: &mockProcessor{ processDuration: maxTestDuration / 3, cancelDuration: maxTestDuration / 3, }, // * 10 elements = 66% of the test duration in: Emit(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), }, // Therefore the out channel should be closed by the end of the test wantOpen: false, }} for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), tt.args.ctxTimeout) defer cancel() // Process the batch with a timeout of maxTestDuration open := true out := ProcessBatchConcurrently(ctx, tt.args.concurrently, tt.args.maxSize, tt.args.maxDuration, tt.args.processor, tt.args.in) timeout := time.After(maxTestDuration) loop: for { select { case <-timeout: break loop case _, ok := <-out: if !ok { open = false break loop } } } // Expecting the channels open state if open != tt.wantOpen { t.Errorf("open = %t, wanted %t", open, tt.wantOpen) } }) } } func Test_processBatch(t *testing.T) { drain := make(chan interface{}, 10000) const maxTestDuration = time.Second type args struct { ctxTimeout time.Duration maxSize int maxDuration time.Duration processor *mockProcessor in <-chan interface{} out chan<- interface{} } type want struct { open bool processed []interface{} canceled []interface{} errs []interface{} } tests := []struct { name string args args want want }{{ name: "returns instantly if in is closed", args: args{ ctxTimeout: maxTestDuration, maxSize: 20, maxDuration: maxTestDuration, processor: new(mockProcessor), in: func() <-chan interface{} { in := make(chan interface{}) close(in) return in }(), out: drain, }, want: want{ open: false, }, }, { name: "processes slices of inputs", args: args{ ctxTimeout: maxTestDuration, maxSize: 2, maxDuration: maxTestDuration, processor: new(mockProcessor), in: Emit(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), out: drain, }, want: want{ open: false, processed: []interface{}{[]interface{}{ 1, 2, }, []interface{}{ 3, 4, }, []interface{}{ 5, 6, }, []interface{}{ 7, 8, }, []interface{}{ 9, 10, }}, }, }, { name: "cancels slices of inputs if process returns an error", args: args{ ctxTimeout: maxTestDuration / 2, maxSize: 5, maxDuration: maxTestDuration, processor: &mockProcessor{ processReturnsErrs: true, }, in: Emit(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), out: drain, }, want: want{ open: false, canceled: []interface{}{[]interface{}{ 1, 2, 3, 4, 5, }, []interface{}{ 6, 7, 8, 9, 10, }}, errs: []interface{}{ "process error: [1 2 3 4 5]", "process error: [6 7 8 9 10]", }, }, }, { name: "cancels slices of inputs when the context is canceled", args: args{ ctxTimeout: maxTestDuration / 2, maxSize: 1, maxDuration: maxTestDuration, processor: &mockProcessor{ // this will take longer to complete than the maxTestDuration by a few micro seconds processDuration: maxTestDuration / 10, // 5 calls to Process > maxTestDuration / 2 cancelDuration: maxTestDuration/10 + 25*time.Millisecond, // 5 calls to Cancel > maxTestDuration / 2 }, in: Emit(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), out: drain, }, want: want{ open: true, processed: []interface{}{ []interface{}{1}, []interface{}{2}, []interface{}{3}, []interface{}{4}, }, canceled: []interface{}{ []interface{}{5}, []interface{}{6}, []interface{}{7}, []interface{}{8}, }, errs: []interface{}{ "context deadline exceeded", "context deadline exceeded", "context deadline exceeded", "context deadline exceeded", }, }, }} for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), tt.args.ctxTimeout) defer cancel() // Process the batch with a timeout of maxTestDuration timeout := time.After(maxTestDuration) open := true loop: for { select { case <-timeout: break loop default: open = processOneBatch(ctx, tt.args.maxSize, tt.args.maxDuration, tt.args.processor, tt.args.in, tt.args.out) if !open { break loop } } } // Processing took longer than expected if open != tt.want.open { t.Errorf("open = %t, wanted %t", open, tt.want.open) } // Expecting processed inputs if !reflect.DeepEqual(tt.args.processor.processed, tt.want.processed) { t.Errorf("processed = %+v, want %+v", tt.args.processor.processed, tt.want.processed) } // Expecting canceled inputs if !reflect.DeepEqual(tt.args.processor.canceled, tt.want.canceled) { t.Errorf("canceled = %+v, want %+v", tt.args.processor.canceled, tt.want.canceled) } // Expecting canceled errors if !reflect.DeepEqual(tt.args.processor.errs, tt.want.errs) { t.Errorf("errs = %+v, want %+v", tt.args.processor.errs, tt.want.errs) } }) } } <|start_filename|>processor.go<|end_filename|> package pipeline import "context" // Processor represents a blocking operation in a pipeline. Implementing `Processor` will allow you to add // business logic to your pipelines without directly managing channels. This simplifies your unit tests // and eliminates channel management related bugs. type Processor interface { // Process processes an input and returns an output or an error, if the output could not be processed. // When the context is canceled, process should stop all blocking operations and return the `Context.Err()`. Process(ctx context.Context, i interface{}) (interface{}, error) // Cancel is called if process returns an error or if the context is canceled while there are still items in the `in <-chan interface{}`. Cancel(i interface{}, err error) } // NewProcessor creates a process and cancel func func NewProcessor( process func(ctx context.Context, i interface{}) (interface{}, error), cancel func(i interface{}, err error), ) Processor { return &processor{process, cancel} } // processor implements Processor type processor struct { process func(ctx context.Context, i interface{}) (interface{}, error) cancel func(i interface{}, err error) } func (p *processor) Process(ctx context.Context, i interface{}) (interface{}, error) { return p.process(ctx, i) } func (p *processor) Cancel(i interface{}, err error) { p.cancel(i, err) } <|start_filename|>semaphore/semaphore.go<|end_filename|> // package semaphore is like a sync.WaitGroup with an upper limit. // It's useful for limiting concurrent operations. // // Example Usage // // // startMultiplying is a pipeline step that concurrently multiplies input numbers by a factor // func startMultiplying(concurrency, factor int, in <-chan int) <-chan int { // out := make(chan int) // go func() { // sem := semaphore.New(concurrency) // for i := range in { // // Multiply up to 'concurrency' inputs at once // sem.Add(1) // go func() { // out <- factor * i // sem.Done() // }() // } // // Wait for all multiplications to finish before closing the output chan // sem.Wait() // close(out) // }() // return out // } // package semaphore // Semaphore is like a sync.WaitGroup, except it has a maximum // number of items that can be added. If that maximum is reached, // Add will block until Done is called. type Semaphore chan struct{} // New returns a new Semaphore func New(max int) Semaphore { // There are probably more memory efficient ways to implement // a semaphore using runtime primitives like runtime_SemacquireMutex return make(Semaphore, max) } // Add adds delta, which may be negative, to the semaphore buffer. // If the buffer becomes 0, all goroutines blocked by Wait are released. // If the buffer goes negative, Add will block until another goroutine makes it positive. // If the buffer exceeds max, Add will block until another goroutine decrements the buffer. func (s Semaphore) Add(delta int) { // Increment the semaphore for i := delta; i > 0; i-- { s <- struct{}{} } // Decrement the semaphore for i := delta; i < 0; i++ { <-s } } // Done decrements the semaphore by 1 func (s Semaphore) Done() { s.Add(-1) } // Wait blocks until the semaphore is buffer is empty func (s Semaphore) Wait() { // Filling the buffered channel ensures that its empty s.Add(cap(s)) // Free the buffer before closing (unsure if this matters) s.Add(-cap(s)) close(s) } <|start_filename|>split_test.go<|end_filename|> package pipeline import ( "reflect" "testing" ) func TestSplit(t *testing.T) { type args struct { in interface{} } type want struct { out []interface{} } tests := []struct { name string args args want want }{ { "splits slices if interfaces into individual interfaces", args{ in: []interface{}{1, 2, 3, 4, 5}, }, want{ out: []interface{}{1, 2, 3, 4, 5}, }, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { // Create the in channel in := make(chan interface{}) go func() { defer close(in) in <- test.args.in }() // Collect the output var outs []interface{} for o := range Split(in) { outs = append(outs, o) } // Expected out if !reflect.DeepEqual(test.want.out, outs) { t.Errorf("%+v != %+v", test.want.out, outs) } }) } } <|start_filename|>process.go<|end_filename|> package pipeline import ( "context" "github.com/deliveryhero/pipeline/semaphore" ) // Process takes each input from the `in <-chan interface{}` and calls `Processor.Process` on it. // When `Processor.Process` returns an `interface{}`, it will be sent to the output `<-chan interface{}`. // If `Processor.Process` returns an error, `Processor.Cancel` will be called with the corresponding input and error message. // Finally, if the `Context` is canceled, all inputs remaining in the `in <-chan interface{}` will go directly to `Processor.Cancel`. func Process(ctx context.Context, processor Processor, in <-chan interface{}) <-chan interface{} { out := make(chan interface{}) go func() { for i := range in { process(ctx, processor, i, out) } close(out) }() return out } // ProcessConcurrently fans the in channel out to multiple Processors running concurrently, // then it fans the out channels of the Processors back into a single out chan func ProcessConcurrently(ctx context.Context, concurrently int, p Processor, in <-chan interface{}) <-chan interface{} { // Create the out chan out := make(chan interface{}) go func() { // Perform Process concurrently times sem := semaphore.New(concurrently) for i := range in { sem.Add(1) go func(i interface{}) { process(ctx, p, i, out) sem.Done() }(i) } // Close the out chan after all of the Processors finish executing sem.Wait() close(out) }() return out } func process( ctx context.Context, processor Processor, i interface{}, out chan<- interface{}, ) { select { // When the context is canceled, Cancel all inputs case <-ctx.Done(): processor.Cancel(i, ctx.Err()) // Otherwise, Process all inputs default: result, err := processor.Process(ctx, i) if err != nil { processor.Cancel(i, err) return } out <- result } } <|start_filename|>pipeline.go<|end_filename|> // Pipeline is a go library that helps you build pipelines without worrying about channel management and concurrency. // It contains common fan-in and fan-out operations as well as useful utility funcs for batch processing and scaling. // // If you have another common use case you would like to see covered by this package, please (open a feature request) https://github.com/deliveryhero/pipeline/issues. package pipeline <|start_filename|>process_example_test.go<|end_filename|> package pipeline_test import ( "context" "log" "time" "github.com/deliveryhero/pipeline" "github.com/deliveryhero/pipeline/example/processors" ) func ExampleProcess() { // Create a context that times out after 5 seconds ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() // Create a pipeline that emits 1-6 at a rate of one int per second p := pipeline.Delay(ctx, time.Second, pipeline.Emit(1, 2, 3, 4, 5, 6)) // Use the Multiplier to multiply each int by 10 p = pipeline.Process(ctx, &processors.Multiplier{ Factor: 10, }, p) // Finally, lets print the results and see what happened for result := range p { log.Printf("result: %d\n", result) } // Output // result: 10 // result: 20 // result: 30 // result: 40 // result: 50 // error: could not multiply 6, context deadline exceeded } func ExampleProcessConcurrently() { // Create a context that times out after 5 seconds ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() // Create a pipeline that emits 1-7 p := pipeline.Emit(1, 2, 3, 4, 5, 6, 7) // Wait 2 seconds to pass each number through the pipe // * 2 concurrent Processors p = pipeline.ProcessConcurrently(ctx, 2, &processors.Waiter{ Duration: 2 * time.Second, }, p) // Finally, lets print the results and see what happened for result := range p { log.Printf("result: %d\n", result) } // Output // result: 2 // result: 1 // result: 4 // result: 3 // error: could not process 6, process was canceled // error: could not process 5, process was canceled // error: could not process 7, context deadline exceeded } <|start_filename|>merge_test.go<|end_filename|> package pipeline import ( "errors" "fmt" "testing" "time" ) // task will wait for a specified duration of time before returning a certain number of errors type task struct { id string errorCount int waitFor time.Duration } // do performs the task func (t task) do() <-chan interface{} { out := make(chan interface{}) go func() { defer close(out) time.Sleep(t.waitFor) for i := 0; i < t.errorCount; i++ { out <- fmt.Errorf("[task %s] error %d", t.id, i) } }() return out } // TestMerge makes sure that the merged chan // 1. Closes after all of its child chans close // 2. Receives all error messages from the error chans // 3. Stays open if one of its child chans never closes func TestMerge(t *testing.T) { maxTestDuration := time.Second for _, test := range []struct { description string finishBefore time.Duration expectedErrors []error tasks []task }{{ description: "Closes after all of its error chans close", finishBefore: time.Second, tasks: []task{{ id: "a", waitFor: 250 * time.Millisecond, }, { id: "b", waitFor: 500 * time.Millisecond, }, { id: "c", waitFor: 750 * time.Millisecond, }}, }, { description: "Receives all errors from all of its error chans", finishBefore: time.Second, expectedErrors: []error{ errors.New("[task a] error 0"), errors.New("[task c] error 0"), errors.New("[task c] error 1"), errors.New("[task c] error 2"), errors.New("[task b] error 0"), errors.New("[task b] error 1"), }, tasks: []task{{ id: "a", waitFor: 250 * time.Millisecond, errorCount: 1, }, { id: "b", waitFor: 750 * time.Millisecond, errorCount: 2, }, { id: "c", waitFor: 500 * time.Millisecond, errorCount: 3, }}, }, { description: "Stays open if one of its chans never closes", expectedErrors: []error{ errors.New("[task c] error 0"), errors.New("[task b] error 0"), errors.New("[task b] error 1"), }, tasks: []task{{ id: "a", waitFor: 2 * maxTestDuration, // We shoud expect to 'never' receive this error, because it will emit after the maxTestDuration errorCount: 1, }, { id: "b", waitFor: 750 * time.Millisecond, errorCount: 2, }, { id: "c", waitFor: 500 * time.Millisecond, errorCount: 1, }}, }, { description: "Single channel passes through", expectedErrors: []error{ errors.New("[task a] error 0"), errors.New("[task a] error 1"), errors.New("[task a] error 2"), }, tasks: []task{{ id: "a", waitFor: 0, // We shoud expect to 'never' receive this error, because it will emit after the maxTestDuration errorCount: 3, }}, }, { description: "Closed channel returned", expectedErrors: []error{}, tasks: []task{}, }} { t.Run(test.description, func(t *testing.T) { // Start doing all of the tasks var errChans []<-chan interface{} for _, task := range test.tasks { errChans = append(errChans, task.do()) } // Merge all of their error channels together var errs []error merged := Merge(errChans...) // Create the timeout timeout := time.After(maxTestDuration) if test.finishBefore > 0 { timeout = time.After(test.finishBefore) } loop: for { select { case i, ok := <-merged: if !ok { // The chan has closed break loop } else if err, ok := i.(error); ok { errs = append(errs, err) } else { t.Errorf("'%+v' is not an error!", i) return } case <-timeout: if isExpected := test.finishBefore == 0; isExpected { // We're testing that open channels cause a timeout break loop } t.Error("timed out!") } } // Check that all of the expected errors match the errors we received lenErrs, lenExpectedErros := len(errs), len(test.expectedErrors) for i, expectedError := range test.expectedErrors { if i >= lenErrs { t.Errorf("expectedErrors[%d]: '%s' != <nil>", i, expectedError) } else if err := errs[i]; expectedError.Error() != err.Error() { t.Errorf("expectedErrors[%d]: '%s' != %s", i, expectedError, err) } } // Check that we have no additional error messages other than the ones we expected if hasTooManyErrors := lenErrs > lenExpectedErros; hasTooManyErrors { for _, err := range errs[lenExpectedErros-1:] { t.Errorf("'%s' is unexpected!", err) } } }) } } <|start_filename|>emit.go<|end_filename|> package pipeline // Emit fans `is ...interface{}`` out to a `<-chan interface{}` func Emit(is ...interface{}) <-chan interface{} { out := make(chan interface{}) go func() { defer close(out) for _, i := range is { out <- i } }() return out } <|start_filename|>example/db/db.go<|end_filename|> // db is a fake db package for use with some of the examples package db import ( "context" "fmt" "math/rand" "time" ) // Result is returned from the 'database' type Result struct { Title string `json:"title"` Description string `json:"description"` URL string `json:"url"` } func GetAdvertisements(ctx context.Context, query string, rs *[]Result) <-chan interface{} { out := make(chan interface{}) go func() { defer close(out) if err := simulatedDbRequest(ctx, "advertisement", rs); err != nil { out <- err } }() return out } func GetImages(ctx context.Context, query string, rs *[]Result) <-chan interface{} { out := make(chan interface{}) go func() { defer close(out) if err := simulatedDbRequest(ctx, "image", rs); err != nil { out <- err } }() return out } func GetProducts(ctx context.Context, query string, rs *[]Result) <-chan interface{} { out := make(chan interface{}) go func() { defer close(out) if err := simulatedDbRequest(ctx, "product", rs); err != nil { out <- err } }() return out } func GetWebsites(ctx context.Context, query string, rs *[]Result) <-chan interface{} { out := make(chan interface{}) go func() { defer close(out) if err := simulatedDbRequest(ctx, "website", rs); err != nil { out <- err } }() return out } func simulatedDbRequest(ctx context.Context, resultPrefix string, rs *[]Result) error { select { // Return right away if the case <-ctx.Done(): return ctx.Err() // Simulate 25-200ms of latency from a db request case <-time.After(time.Millisecond * time.Duration((25 + (rand.Int() % 175)))): // #nosec break } // Return between 1 and 5 results total := 1 + (rand.Int() % 5) // #nosec for i := 0; i < total; i++ { *rs = append(*rs, Result{ Title: fmt.Sprintf("%s %d title", resultPrefix, i), Description: fmt.Sprintf("%s %d description", resultPrefix, i), URL: fmt.Sprintf("http://%s-%d.com", resultPrefix, i), }) } return nil } <|start_filename|>collect.go<|end_filename|> package pipeline import ( "context" "time" ) // Collect collects `interface{}`s from its in channel and returns `[]interface{}` from its out channel. // It will collect up to `maxSize` inputs from the `in <-chan interface{}` over up to `maxDuration` before returning them as `[]interface{}`. // That means when `maxSize` is reached before `maxDuration`, `[maxSize]interface{}` will be passed to the out channel. // But if `maxDuration` is reached before `maxSize` inputs are collected, `[< maxSize]interface{}` will be passed to the out channel. // When the `context` is canceled, everything in the buffer will be flushed to the out channel. func Collect(ctx context.Context, maxSize int, maxDuration time.Duration, in <-chan interface{}) <-chan interface{} { out := make(chan interface{}) go func() { for { is, open := collect(ctx, maxSize, maxDuration, in) if is != nil { out <- is } if !open { close(out) return } } }() return out } func collect(ctx context.Context, maxSize int, maxDuration time.Duration, in <-chan interface{}) ([]interface{}, bool) { var buffer []interface{} timeout := time.After(maxDuration) for { lenBuffer := len(buffer) select { case <-ctx.Done(): // Reduce the timeout to 1/10th of a second bs, open := collect(context.Background(), maxSize, 100*time.Millisecond, in) return append(buffer, bs...), open case <-timeout: return buffer, true case i, open := <-in: if !open { return buffer, false } else if lenBuffer < maxSize-1 { // There is still room in the buffer buffer = append(buffer, i) } else { // There is no room left in the buffer return append(buffer, i), true } } } } <|start_filename|>example/processors/processors.go<|end_filename|> // processors are a bunch of simple processors used in the examples package processors import ( "context" "errors" "log" "time" ) // Miltiplier is a simple processor that multiplies each integer it receives by some Factor type Multiplier struct { // Factor will change the amount each number is multiplied by Factor int } // Process multiplies a number by factor func (m *Multiplier) Process(_ context.Context, in interface{}) (interface{}, error) { return in.(int) * m.Factor, nil } // Cancel is called when the context is canceled func (m *Multiplier) Cancel(i interface{}, err error) { log.Printf("error: could not multiply %d, %s\n", i, err) } // BatchMultiplier is a simple batch processor that multiplies each `[]int` it receives together type BatchMultiplier struct{} // Process a slice of numbers together and returns a slice of numbers with the results func (m *BatchMultiplier) Process(_ context.Context, ins interface{}) (interface{}, error) { result := 1 for _, in := range ins.([]interface{}) { result *= in.(int) } return []interface{}{result}, nil } // Cancel is called when the context is canceled func (m *BatchMultiplier) Cancel(i interface{}, err error) { log.Printf("error: could not multiply %+v, %s\n", i, err) } // Waiter is a Processor that waits for Duration before returning its output type Waiter struct { Duration time.Duration } // Process waits for `Waiter.Duration` before returning the value passed in func (w *Waiter) Process(ctx context.Context, in interface{}) (interface{}, error) { select { case <-time.After(w.Duration): return in, nil case <-ctx.Done(): return nil, errors.New("process was canceled") } } // Cancel is called when the context is canceled func (w *Waiter) Cancel(i interface{}, err error) { log.Printf("error: could not process %+v, %s\n", i, err) } <|start_filename|>process_batch.go<|end_filename|> package pipeline import ( "context" "time" "github.com/deliveryhero/pipeline/semaphore" ) // ProcessBatch collects up to maxSize elements over maxDuration and processes them together as a slice of `interface{}`s. // It passed an []interface{} to the `Processor.Process` method and expects a []interface{} back. // It passes []interface{} batches of inputs to the `Processor.Cancel` method. // If the receiver is backed up, ProcessBatch can holds up to 2x maxSize. func ProcessBatch( ctx context.Context, maxSize int, maxDuration time.Duration, processor Processor, in <-chan interface{}, ) <-chan interface{} { out := make(chan interface{}) go func() { for { if !processOneBatch(ctx, maxSize, maxDuration, processor, in, out) { break } } close(out) }() return out } // ProcessBatchConcurrently fans the in channel out to multiple batch Processors running concurrently, // then it fans the out channels of the batch Processors back into a single out chan func ProcessBatchConcurrently( ctx context.Context, concurrently, maxSize int, maxDuration time.Duration, processor Processor, in <-chan interface{}, ) <-chan interface{} { // Create the out chan out := make(chan interface{}) go func() { // Perform Process concurrently times sem := semaphore.New(concurrently) lctx, done := context.WithCancel(context.Background()) for !isDone(lctx) { sem.Add(1) go func() { if !processOneBatch(ctx, maxSize, maxDuration, processor, in, out) { done() } sem.Done() }() } // Close the out chan after all of the Processors finish executing sem.Wait() close(out) done() // Satisfy go-vet }() return out } // isDone returns true if the context is canceled func isDone(ctx context.Context) bool { select { case <-ctx.Done(): return true default: return false } } // processOneBatch processes one batch of inputs from the in chan. // It returns true if the in chan is still open. func processOneBatch( ctx context.Context, maxSize int, maxDuration time.Duration, processor Processor, in <-chan interface{}, out chan<- interface{}, ) (open bool) { // Collect interfaces for batch processing is, open := collect(ctx, maxSize, maxDuration, in) if is != nil { select { // Cancel all inputs during shutdown case <-ctx.Done(): processor.Cancel(is, ctx.Err()) // Otherwise Process the inputs default: results, err := processor.Process(ctx, is) if err != nil { processor.Cancel(is, err) return open } // Split the results back into interfaces for _, result := range results.([]interface{}) { out <- result } } } return open } <|start_filename|>merge_example_test.go<|end_filename|> package pipeline_test import ( "context" "encoding/json" "log" "net/http" "github.com/deliveryhero/pipeline" "github.com/deliveryhero/pipeline/example/db" ) // SearchResults returns many types of search results at once type SearchResults struct { Advertisements []db.Result `json:"advertisements"` Images []db.Result `json:"images"` Products []db.Result `json:"products"` Websites []db.Result `json:"websites"` } func ExampleMerge() { r := http.NewServeMux() // `GET /search?q=<query>` is an endpoint that merges concurrently fetched // search results into a single search response using `pipeline.Merge` r.HandleFunc("/search", func(w http.ResponseWriter, r *http.Request) { query := r.URL.Query().Get("q") if len(query) < 1 { w.WriteHeader(http.StatusBadRequest) return } // If the request times out, or we receive an error from our `db` // the context will stop all pending db queries for this request ctx, cancel := context.WithCancel(r.Context()) defer cancel() // Fetch all of the different search results concurrently var results SearchResults for err := range pipeline.Merge( db.GetAdvertisements(ctx, query, &results.Advertisements), db.GetImages(ctx, query, &results.Images), db.GetProducts(ctx, query, &results.Products), db.GetWebsites(ctx, query, &results.Websites), ) { // Stop all pending db requests if theres an error if err != nil { log.Print(err) w.WriteHeader(http.StatusInternalServerError) return } } // Return the search results if bs, err := json.Marshal(&results); err != nil { log.Print(err) w.WriteHeader(http.StatusInternalServerError) } else if _, err := w.Write(bs); err != nil { log.Print(err) w.WriteHeader(http.StatusInternalServerError) } else { w.WriteHeader(http.StatusOK) } }) }
sandepudi/pipeline